Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

chore(core): remove legacy JSON-RPC HTTP server implementation

Steven Enamakelb7c8fc19e029
diff --git a/crates/openhuman-core/src/core/jsonrpc.rs b/crates/openhuman-core/src/core/jsonrpc.rs
deleted file mode 100644
index 111057d4dd..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc.rs
+++ /dev/null
@@ -1,2450 +0,0 @@
-//! JSON-RPC 2.0 server implementation for OpenHuman.
-//!
-//! This module provides:
-//! - An Axum-based HTTP server for handling JSON-RPC requests.
-//! - Method dispatching to registered controllers.
-//! - SSE (Server-Sent Events) for real-time event streaming.
-//! - Helper routes for health checks, schema discovery, and Telegram authentication.
-
-// Only the gated router build (`build_core_http_router`) uses the bare `Arc`;
-// the kept dispatch/bootstrap paths qualify it (`std::sync::Arc`) or import it
-// locally, so this module-level import is `http-server`-only (#5048).
-#[cfg(feature = "http-server")]
-use std::sync::Arc;
-
-// The axum server surface — router, handlers, middleware, extractors, SSE — is
-// exclusive to the `http-server` feature (#5048). Only the RPC-dispatch surface
-// (`invoke_method`, `parse_json_params`, `default_state`, the `run_server*`
-// CoreBuilder shims, `register_domain_subscribers`, `bootstrap_core_runtime`)
-// stays compiled; a slim build drives it over the CLI / native dispatch path
-// without binding a listener. `Map`/`Value` stay ungated (dispatch uses them).
-#[cfg(feature = "http-server")]
-use axum::extract::{DefaultBodyLimit, Query, State, WebSocketUpgrade};
-#[cfg(feature = "http-server")]
-use axum::http::{header, HeaderValue, Method, StatusCode};
-#[cfg(feature = "http-server")]
-use axum::middleware::{self, Next};
-#[cfg(feature = "http-server")]
-use axum::response::sse::{Event, KeepAlive, Sse};
-#[cfg(feature = "http-server")]
-use axum::response::{IntoResponse, Response};
-#[cfg(feature = "http-server")]
-use axum::routing::{get, post};
-#[cfg(feature = "http-server")]
-use axum::{extract::Request, Json, Router};
-#[cfg(feature = "http-server")]
-use serde::Serialize;
-#[cfg(feature = "http-server")]
-use serde_json::json;
-use serde_json::{Map, Value};
-#[cfg(feature = "http-server")]
-use tokio_stream::StreamExt;
-use tokio_util::sync::CancellationToken;
-
-use crate::core::all;
-use crate::core::types::AppState;
-// The JSON-RPC envelope types are only shaped into HTTP responses by the gated
-// `rpc_handler`; the kept dispatch surface returns `Result<Value, String>`.
-#[cfg(feature = "http-server")]
-use crate::core::types::{RpcError, RpcFailure, RpcRequest, RpcSuccess};
-#[cfg(feature = "http-server")]
-use crate::rpc::StructuredRpcError;
-
-/// Axum handler for JSON-RPC POST requests.
-///
-/// This function:
-/// 1. Receives a JSON-RPC request body.
-/// 2. Extracts the method name and parameters.
-/// 3. Invokes the corresponding handler via [`invoke_method`].
-/// 4. Wraps the result or error in a JSON-RPC 2.0 compliant response.
-///
-/// # Arguments
-///
-/// * `state` - The application state, injected by Axum.
-/// * `req` - The parsed [`RpcRequest`].
-#[cfg(feature = "http-server")]
-pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcRequest>) -> Response {
- let id = req.id.clone();
- let method = req.method.clone();
- let started = std::time::Instant::now();
- let result = invoke_method(state, method.as_str(), req.params).await;
- let ms = started.elapsed().as_millis();
-
- match result {
- Ok(value) => {
- tracing::info!("[rpc] {} -> ok ({}ms)", method, ms);
- (
- StatusCode::OK,
- Json(RpcSuccess {
- jsonrpc: "2.0",
- id,
- result: value,
- }),
- )
- .into_response()
- }
- Err(raw_message) => {
- // Decode the controller-emitted structured envelope (if any)
- // here at the transport boundary. Domains opt in by emitting a
- // `StructuredRpcError` from their handlers — this layer never
- // branches on the RPC method name to recover error semantics.
- let structured = StructuredRpcError::decode(&raw_message);
- let (mut display_message, error_data, expected_user_state) = match structured {
- Some(envelope) => (
- envelope.message,
- envelope.data,
- envelope.expected_user_state,
- ),
- None => (raw_message, None, false),
- };
-
- // Session-expired bubbles up as an "error" but is an expected
- // boundary condition (auth handler clears the local token and the
- // UI re-auths). Don't spam Sentry with it.
- //
- // Param-validation failures ("unknown param 'x' for ns.fn",
- // "missing required param 'x'", "invalid params: …") are also
- // pure boundary mismatches: either the caller is a frontend on a
- // different release than the running core (OPENHUMAN-TAURI-20:
- // v0.53.22 UI shipped `api_key` before the matching schema input
- // landed in #1467) or it is straight client-bug input. Sentry
- // cannot help — we can neither retro-fix already-shipped
- // installs nor learn anything from the noise — so log at info
- // and skip the report.
- //
- // Logging asymmetry between the two skip paths is intentional:
- // session-expired messages are a small set of fixed strings
- // (no caller-supplied content), so the full text is safe to
- // log. Param-validation messages embed caller-supplied param
- // names and, for the `invalid params: …` shape, can carry
- // deserialized values — log structurally with redacted body
- // to keep PII out of the sink while preserving the method
- // for grep / correlation.
- //
- // Domains that surface their own expected-user-state errors
- // (stale thread refs, etc.) set the `expected_user_state` flag
- // on their structured envelope and skip Sentry here uniformly.
- if expected_user_state {
- tracing::info!(
- method = %method,
- "[rpc] expected-user-state error — skipping Sentry: {}",
- display_message
- );
- } else if is_wallet_not_configured_error(&display_message) {
- // A wallet-backed RPC cannot run before wallet setup. This is
- // expected user state, not an internal failure.
- tracing::info!(
- method = %method,
- "[rpc] wallet-not-configured (expected user-state) — skipping Sentry"
- );
- } else if is_param_validation_error(&display_message) {
- tracing::info!(
- method = %method,
- elapsed_ms = ms as u64,
- "[rpc] param-validation error (message redacted; skip-report)"
- );
- } else if is_session_expired_error(&display_message) {
- tracing::info!("[rpc] {} -> err ({}ms): {}", method, ms, display_message);
- } else if crate::core::observability::is_suppressed_usage_probe_backoff(
- &display_message,
- ) {
- // A `/teams/me/usage` probe that the failure-backoff in
- // `team::ops` short-circuited within its window — i.e. an
- // already-reported repeat. The FIRST failure of the streak
- // already hit the backend and reported here normally; demoting
- // the repeats is exactly the flood control GH #4153 asks for
- // (backpressure, not silent drop). Debug-only, never Sentry.
- tracing::debug!(
- method = %method,
- elapsed_ms = ms as u64,
- "[rpc] usage-probe failure-backoff repeat — not reporting to Sentry"
- );
- // Keep the internal demotion marker strictly out-of-band: it
- // exists only to drive the Sentry-demotion decision above and
- // must never reach the RPC client as the error message. Replace
- // it with a clean, user-presentable string before the response
- // is built below (CodeRabbit on #4153 — don't leak the sentinel).
- display_message =
- "Usage temporarily unavailable — the last fetch failed and is backing off; \
- it will refresh shortly."
- .to_string();
- } else if crate::core::observability::is_transient_message_failure(&display_message) {
- // Downstream call (backend_api / integrations / provider) already
- // demoted the underlying transient failure to a warn. The error
- // string still propagates up to here; re-reporting at error level
- // would re-create the very Sentry noise the lower-layer demote
- // was meant to avoid (#8Z, #93, #8W, #96).
- //
- // Redact before logging — `display_message` is upstream-derived
- // (backend / provider response) and can carry URL fragments,
- // query params, or pasted-through provider error text that
- // includes tokens. `sanitize_api_error` runs the same scrub
- // used in the SessionExpired publish path below.
- let redacted = tinyinference_core::sanitize::sanitize_api_error(&display_message);
- tracing::warn!(
- method = %method,
- elapsed_ms = ms as u64,
- error = %redacted,
- "[rpc] transient downstream failure — not reporting to Sentry (message redacted)"
- );
- } else if let Some(unknown_method) =
- crate::core::dispatch::unknown_method_name(&display_message)
- {
- // An unrecognised RPC method is a transport-boundary mismatch
- // (infra probe traffic, or a client on a different release than
- // the running core), not an actionable core defect (#3567).
- // Known external probes never become real methods, so they are
- // debug-only and never reach Sentry; any other unknown method
- // is still recorded for triage but at warn severity (captured,
- // no page) rather than an error event. Either way the JSON-RPC
- // method-not-found response to the caller below is unchanged.
- if crate::core::dispatch::is_known_probe_method(unknown_method) {
- tracing::debug!(
- method = %method,
- elapsed_ms = ms as u64,
- "[rpc] unknown probe/legacy method (allow-listed) — debug only, not reporting to Sentry"
- );
- } else {
- crate::core::observability::report_warning_message(
- display_message.as_str(),
- "rpc",
- "invoke_method",
- &[("method", method.as_str()), ("elapsed_ms", &ms.to_string())],
- );
- }
- } else if crate::memory::tree::tree::rpc::is_invalid_ingest_payload_message(
- &display_message,
- ) {
- // The caller submitted an ingest payload that does not match
- // the canonicaliser schema for its `source_kind` (#5169). The
- // handler already returned a precise error naming the missing
- // or malformed field, and no core-side change can fix a
- // producer sending the wrong shape — so this is a caller
- // error, not an actionable core defect. Same treatment as an
- // unrecognised method above: still captured for triage (a
- // spike means a producer regressed) but at warn severity, so
- // it does not page.
- crate::core::observability::report_warning_message(
- display_message.as_str(),
- "rpc",
- "invoke_method",
- &[("method", method.as_str()), ("elapsed_ms", &ms.to_string())],
- );
- } else {
- crate::core::observability::report_error_or_expected(
- display_message.as_str(),
- "rpc",
- "invoke_method",
- &[("method", method.as_str()), ("elapsed_ms", &ms.to_string())],
- );
- }
- (
- StatusCode::OK,
- Json(RpcFailure {
- jsonrpc: "2.0",
- id,
- error: RpcError {
- code: -32000,
- message: display_message,
- data: error_data,
- },
- }),
- )
- .into_response()
- }
- }
-}
-
-/// Invokes a JSON-RPC method by name.
-///
-/// This is a high-level wrapper around [`invoke_method_inner`] that adds
-/// automatic session management logic. If a call fails with a confirmed
-/// OpenHuman session-expired error, it publishes the event that clears a
-/// backend session. The offline local credential has no backend session to
-/// expire and receives a recoverable hosted-unavailable error instead.
-///
-/// # Arguments
-///
-/// * `state` - The application state.
-/// * `method` - The name of the method to invoke.
-/// * `params` - The JSON parameters for the method.
-pub async fn invoke_method(state: AppState, method: &str, params: Value) -> Result<Value, String> {
- let mut result = invoke_method_inner(state, method, params).await;
-
- // Session auto-cleanup: if the OpenHuman auth session is explicitly
- // expired, publish a `SessionExpired` event. The credentials subscriber
- // clears the stored token, flips the scheduler-gate signed-out override
- // so background workers stand down, and (eventually) pushes a sign-out to
- // the UI. Generic downstream/provider 401s must stay recoverable errors;
- // otherwise a scoped integration failure can log the user out.
- if let Err(ref msg) = result {
- let sanitized_reason = tinyinference_core::sanitize::sanitize_api_error(msg);
- if is_session_expired_error(msg) {
- // The subscriber ignores an offline local session, but Socket.IO
- // also hears this event and broadcasts sign-out independently.
- // Suppress it at the publisher for backend-only routes that the
- // local credential cannot use. This extra config read happens only
- // on a classified session-expiry error, never on the normal path.
- let local =
- crate::security::credentials::session_support::current_session_is_local().await;
- if should_publish_session_expired(msg, local) {
- log::warn!(
- "[jsonrpc] confirmed session expiry for method='{}' — publishing SessionExpired: {}",
- method,
- sanitized_reason
- );
- // `sanitize_api_error` scrubs pasted-through provider replies.
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::SessionExpired {
- source: format!("jsonrpc.invoke_method:{method}"),
- reason: sanitized_reason,
- });
- } else {
- log::info!(
- "[jsonrpc] backend session unavailable for local offline credential method='{}' — leaving local auth intact",
- method
- );
- // The RPC error is also observed by the renderer's auth
- // classifier. Keep the background hosted probe recoverable
- // without asking it to infer the core's credential kind.
- result = Err(translate_local_session_error(msg, local)
- .expect("classified local session error"));
- }
- } else if is_unconfirmed_unauthorized_error(msg) {
- log::info!(
- "[jsonrpc] unconfirmed unauthorized error for method='{}' (not session expiry) — leaving session intact: {}",
- method,
- sanitized_reason
- );
- }
- }
-
- result
-}
-
-fn should_publish_session_expired(msg: &str, credential_is_local: bool) -> bool {
- is_session_expired_error(msg) && !credential_is_local
-}
-
-fn translate_local_session_error(msg: &str, credential_is_local: bool) -> Option<String> {
- (credential_is_local && is_session_expired_error(msg)).then(|| {
- format!(
- "{}Hosted account data is unavailable in local offline mode",
- crate::core::observability::BACKEND_UNAVAILABLE_PREFIX
- )
- })
-}
-
-/// Helper to determine if an error message indicates an expired or invalid
-/// OpenHuman backend session.
-///
-/// **Narrower than the previous implementation** (fixed in issue #2286):
-///
-/// The old predicate matched ANY `"401 + unauthorized"` pattern, which caused
-/// downstream provider 401s (Discord bot token failures, BYO-key OpenAI /
-/// Anthropic failures, Composio direct-mode errors) to clear the user's session
-/// and log them out. The fix distinguishes between:
-///
-/// - **OpenHuman backend 401s** (`authed_json` in `crates/openhuman-core/src/backend/client.rs`): formatted
-/// as `"{METHOD} /path failed (401 Unauthorized): {body}"`, e.g.
-/// `"GET /teams failed (401 Unauthorized): {"success":false}"`. These always
-/// start with an HTTP method verb followed by a space and a forward slash.
-/// - **Provider / downstream 401s** (`api_error` in
-/// `crates/openhuman-core/src/inference/provider/ops.rs`): formatted as
-/// `"{ProviderName} API error (401 Unauthorized): {body}"` or
-/// `"Discord API error: ... (401): Unauthorized"`. These start with a
-/// provider name, NOT an HTTP method verb.
-///
-/// **What still triggers session expiry:**
-/// - `"Session expired"` — explicit body text from the OpenHuman backend.
-/// - `"no backend session token"` — pre-flight guard; auth profile is missing.
-/// - `"session jwt required"` — local guard; JWT already cleared by a prior 401.
-/// - `"SESSION_EXPIRED"` — scheduler-gate sentinel (exact case).
-/// - HTTP-method-prefixed 401s (`GET /`, `POST /`, etc.) — backend path format.
-///
-/// **What no longer triggers session expiry (fixed in #2286):**
-/// - Provider-prefixed 401s (`"Discord API error: ..."`, `"OpenAI API error ..."`)
-/// - `"invalid token"` — too broad; also matches Discord / OAuth provider tokens.
-///
-/// Note: for inference-path OpenHuman backend 401s, `api_error` (in
-/// `inference/provider/ops.rs` lines 479–497) ALREADY publishes `SessionExpired`
-/// directly, so there is no regression if this predicate misses them — the
-/// subscriber is idempotent and a harmless double-publish would still be correct.
-fn is_session_expired_error(msg: &str) -> bool {
- // Explicit session-expired markers from the OpenHuman backend / local
- // guards — delegated to the shared observability classifier so both the
- // Sentry expected-error pipeline and the JSON-RPC publish boundary stay
- // in lock-step.
- if crate::core::observability::is_session_expired_message(msg) {
- return true;
- }
- // OpenHuman backend path 401s via `authed_json`:
- // format is "{METHOD} /path failed (401 Unauthorized): {body}"
- // The HTTP-method prefix distinguishes these from provider-prefixed errors.
- // HEAD and OPTIONS are intentionally excluded — `authed_json` only issues
- // the five listed verbs (GET/POST/PUT/DELETE/PATCH) for REST JSON endpoints.
- let lower = msg.to_ascii_lowercase();
- if (lower.contains("401") && lower.contains("unauthorized"))
- && (msg.starts_with("GET /")
- || msg.starts_with("POST /")
- || msg.starts_with("PUT /")
- || msg.starts_with("DELETE /")
- || msg.starts_with("PATCH /"))
- {
- return true;
- }
- false
-}
-
-/// Detect auth-looking failures that are not specific enough to clear the
-/// OpenHuman session. This is only for diagnostics; it must not feed the
-/// `SessionExpired` publish path.
-///
-/// Matches a generic `401 Unauthorized` OR a bare `"invalid token"` string,
-/// either of which can come from BYO-key providers, Composio, channels, or
-/// other scoped downstream calls. Used exclusively for diagnostic logging
-/// at the `invoke_method` call site so provider auth failures are visible
-/// in the logs without being misclassified as session expiry.
-fn is_unconfirmed_unauthorized_error(msg: &str) -> bool {
- let lower = msg.to_ascii_lowercase();
- (lower.contains("401") && lower.contains("unauthorized")) || lower.contains("invalid token")
-}
-
-/// Returns `true` when the error message comes from JSON-RPC params validation
-/// rather than the underlying handler.
-///
-/// Three shapes, all emitted before the handler ever runs:
-/// * `"unknown param '<key>' for <ns>.<fn>"` — `all::validate_params` (extra field)
-/// * `"missing required param '<key>': <comment>"` — `all::validate_params` (omitted required field)
-/// * `"invalid params: expected object or null, got <type>"` — `params_to_object` (wrong params shape)
-///
-/// These only fire when caller and server schemas drift at the transport layer
-/// — either a frontend on a different release than the running core, or a buggy
-/// external client. Reporting them to Sentry produces unactionable noise (we
-/// cannot patch an already-shipped install, and the message itself already
-/// names the bad field).
-///
-/// Note: domain-level validation errors (e.g. type/format checks emitted *inside*
-/// a controller's `rpc.rs` handler such as `"param 'x' must be a UUID"`) are
-/// intentionally *not* matched here — only the three shapes emitted by the
-/// transport-layer validators before the handler runs. Longer-term a typed
-/// `RpcError::ParamValidation` variant would remove the string-matching
-/// brittleness; the unit tests in `jsonrpc_tests.rs` lock the exact prefixes
-/// against the emit sites in `all::validate_params` and `params_to_object`.
-///
-/// `starts_with` (not `.contains()`) is deliberate: validator errors are always
-/// emitted as the full message body, so an anchored match avoids false positives
-/// from upstream handler text that happens to mention `"unknown param"`. The
-/// session-expired predicate uses `.contains()` because session-expired markers
-/// can appear mid-message — flip these to match and the test
-/// `is_param_validation_error_does_not_match_unrelated_errors` will break.
-#[cfg(feature = "http-server")]
-fn is_param_validation_error(msg: &str) -> bool {
- msg.starts_with("unknown param '")
- || msg.starts_with("missing required param '")
- || msg.starts_with("invalid params: ")
-}
-
-/// Returns `true` when the error is the wallet's "not configured yet" message.
-///
-/// Wallet-backed RPCs return
-/// [`crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE`] before
-/// setup. That is expected user state, not an internal failure.
-///
-/// Matched against the shared wallet constant (exact equality) so a wording
-/// change in the wallet layer fails the coupling test in `jsonrpc_tests.rs`
-/// rather than silently letting the noise back into Sentry.
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error(msg: &str) -> bool {
- msg == crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE
-}
-
-/// Internal method invocation logic.
-///
-/// It first attempts to match the method name against the static controller
-/// registry (schemas). If a schema is found, it validates the input parameters
-/// before execution. If no schema matches, it falls back to the dynamic
-/// [`crate::core::dispatch::dispatch`] system.
-async fn invoke_method_inner(
- state: AppState,
- method: &str,
- params: Value,
-) -> Result<Value, String> {
- // Phase 1: Check static controller registry.
- if let Some(schema) = all::schema_for_rpc_method(method) {
- let params_obj = params_to_object(params.clone())?;
- // Validate inputs against the schema before calling the handler.
- all::validate_params(&schema, &params_obj)?;
- if let Some(result) = all::try_invoke_registered_rpc(method, params_obj).await {
- return result;
- }
- log::debug!(
- "[jsonrpc] schema matched without registered handler; falling back method={}",
- method
- );
- }
-
- // Phase 2: Fall back to dynamic dispatch (internal core methods or legacy paths).
- crate::core::dispatch::dispatch(state, method, params).await
-}
-
-/// Converts JSON parameters into a map, ensuring they are in object format.
-///
-/// JSON-RPC allows parameters to be an Object, an Array, or Null. This implementation
-/// primarily supports Object parameters for named-argument style calls.
-fn params_to_object(params: Value) -> Result<Map<String, Value>, String> {
- match params {
- Value::Object(map) => Ok(map),
- Value::Null => Ok(Map::new()),
- other => Err(format!(
- "invalid params: expected object or null, got {}",
- type_name(&other)
- )),
- }
-}
-
-/// Returns a human-readable string representation of a JSON value's type.
-fn type_name(value: &Value) -> &'static str {
- match value {
- Value::Null => "null",
- Value::Bool(_) => "bool",
- Value::Number(_) => "number",
- Value::String(_) => "string",
- Value::Array(_) => "array",
- Value::Object(_) => "object",
- }
-}
-
-/// Parses a JSON string into a `Value`.
-pub fn parse_json_params(raw: &str) -> Result<Value, String> {
- serde_json::from_str(raw).map_err(|e| format!("invalid JSON params: {e}"))
-}
-
-/// Returns the default application state.
-pub fn default_state() -> AppState {
- AppState {
- core_version: env!("CARGO_PKG_VERSION").to_string(),
- }
-}
-
-// --- HTTP server (Axum) ----------------------------------------------------
-
-/// Returns the HTML for a successful connection page.
-#[cfg(feature = "http-server")]
-fn success_html(message: &str) -> String {
- let escaped_message = escape_html(message);
- r#"<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>OpenHuman &#8212; Connected</title>
- <style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0; display: flex; align-items: center; justify-content: center; min-height: 100vh; }
- .card { background: #1e293b; border-radius: 16px; padding: 48px; text-align: center; max-width: 420px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3); }
- .icon { font-size: 48px; margin-bottom: 16px; }
- h1 { font-size: 24px; margin-bottom: 12px; color: #f8fafc; }
- p { font-size: 16px; color: #94a3b8; line-height: 1.6; }
- </style>
-</head>
-<body>
- <div class="card">
- <div class="icon">&#10004;</div>
- <h1>Connected!</h1>
- <p>__MESSAGE__</p>
- </div>
-</body>
-</html>"#
- .replace("__MESSAGE__", &escaped_message)
-}
-
-/// Simple HTML escaping for error messages.
-#[cfg(feature = "http-server")]
-fn escape_html(s: &str) -> String {
- s.replace('&', "&amp;")
- .replace('<', "&lt;")
- .replace('>', "&gt;")
- .replace('"', "&quot;")
- .replace('\'', "&#x27;")
-}
-
-/// Returns the HTML for an error page.
-#[cfg(feature = "http-server")]
-fn error_html(message: &str) -> String {
- let escaped_message = escape_html(message);
- format!(
- r#"<!DOCTYPE html>
-<html lang="en">
-<head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <title>OpenHuman &#8212; Error</title>
- <style>
- * {{ margin: 0; padding: 0; box-sizing: border-box; }}
- body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #0f172a; color: #e2e8f0; display: flex; align-items: center; justify-content: center; min-height: 100vh; }}
- .card {{ background: #1e293b; border-radius: 16px; padding: 48px; text-align: center; max-width: 420px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3); }}
- .icon {{ font-size: 48px; margin-bottom: 16px; }}
- h1 {{ font-size: 24px; margin-bottom: 12px; color: #f8fafc; }}
- p {{ font-size: 16px; color: #94a3b8; line-height: 1.6; }}
- </style>
-</head>
-<body>
- <div class="card">
- <div class="icon">&#9888;</div>
- <h1>Something went wrong</h1>
- <p>{escaped_message}</p>
- </div>
-</body>
-</html>"#
- )
-}
-
-/// Query params for the MCP browser-OAuth callback (`/oauth/mcp/callback`).
-#[cfg(feature = "http-server")]
-#[derive(Debug, serde::Deserialize)]
-struct OAuthMcpCallbackQuery {
- code: Option<String>,
- state: Option<String>,
- error: Option<String>,
- error_description: Option<String>,
-}
-
-/// Loopback redirect target for MCP browser OAuth (RFC 8252). The authorization
-/// server redirects the browser here with `?code=…&state=…`; we hand it to
-/// `mcp::registry::oauth::complete`, which exchanges the code for a token, stores
-/// it as the server's `Authorization` header, and reconnects.
-#[cfg(feature = "http-server")]
-async fn oauth_mcp_callback_handler(
- Query(query): Query<OAuthMcpCallbackQuery>,
-) -> impl IntoResponse {
- let html = |status: StatusCode, body: String| -> Response {
- (
- status,
- [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
- body,
- )
- .into_response()
- };
-
- if let Some(err) = query.error.as_deref().filter(|s| !s.is_empty()) {
- let desc = query.error_description.as_deref().unwrap_or("");
- log::warn!("[oauth:mcp] authorization error: {err} {desc}");
- return html(
- StatusCode::BAD_REQUEST,
- error_html(&format!("Authorization was denied or failed: {err} {desc}")),
- );
- }
-
- let (code, state) = match (
- query
- .code
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty()),
- query
- .state
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty()),
- ) {
- (Some(c), Some(s)) => (c.to_string(), s.to_string()),
- _ => {
- return html(
- StatusCode::BAD_REQUEST,
- error_html("Missing authorization code or state in the callback."),
- )
- }
- };
-
- log::info!("[oauth:mcp] callback received (state present); completing exchange");
-
- let config = match crate::config::Config::load_or_init().await {
- Ok(c) => c,
- Err(e) => {
- log::warn!("[oauth:mcp] config load failed: {e}");
- return html(
- StatusCode::INTERNAL_SERVER_ERROR,
- error_html("Internal error loading config. Please try again."),
- );
- }
- };
-
- match crate::mcp::registry::oauth::complete(&config, &state, &code).await {
- Ok(server_id) => {
- log::info!("[oauth:mcp] completed sign-in for server_id={server_id}");
- html(
- StatusCode::OK,
- success_html("Signed in. The MCP server is now connected — you can close this tab and return to OpenHuman."),
- )
- }
- Err(e) => {
- log::warn!("[oauth:mcp] complete failed: {e}");
- html(
- StatusCode::BAD_GATEWAY,
- error_html(&format!("Sign-in could not be completed: {e}")),
- )
- }
- }
-}
-
-/// Query parameters for the dictation WebSocket endpoint.
-///
-/// Browser `WebSocket` cannot attach an `Authorization` header on upgrade, so
-/// the FE forwards the per-process core bearer as a `?token=…` query param —
-/// validated against the same in-process RPC token via [`verify_bearer_token`]
-/// (single source of truth, no separate credential).
-#[cfg(feature = "http-server")]
-#[derive(Debug, serde::Deserialize)]
-struct DictationQuery {
- #[serde(default)]
- token: Option<String>,
-}
-
-/// WebSocket upgrade handler for streaming voice dictation.
-///
-/// Authenticated before upgrade (C4 / issue #1924): the request must carry the
-/// per-process core bearer either as `Authorization: Bearer <token>` (CLI /
-/// native callers) or as `?token=<token>` (browser `WebSocket`, which cannot
-/// set headers), and — when an `Origin` header is present — that origin must be
-/// on the local-app allowlist, mirroring the Socket.IO handshake check. Missing
-/// or wrong credentials are rejected with 401 and the socket is never upgraded.
-#[cfg(feature = "http-server")]
-async fn dictation_ws_handler(
- headers: axum::http::HeaderMap,
- Query(query): Query<DictationQuery>,
- ws: WebSocketUpgrade,
-) -> Response {
- log::info!("[ws] dictation WebSocket upgrade requested");
-
- // Origin check (same allowlist Socket.IO enforces): native clients send no
- // Origin and are accepted; cross-origin browser pages are rejected even if
- // they somehow hold the bearer.
- let origin = headers
- .get(header::ORIGIN)
- .and_then(|v| v.to_str().ok())
- .map(str::trim);
- if !crate::core::socketio::origin_is_allowed(origin) {
- log::warn!("[ws] dictation upgrade rejected: disallowed origin {origin:?}");
- return (
- StatusCode::FORBIDDEN,
- Json(json!({
- "ok": false,
- "error": "forbidden",
- "message": "Origin not allowed for the dictation WebSocket."
- })),
- )
- .into_response();
- }
-
- // Bearer check: header first, then `?token=` for browser WebSocket clients.
- let header_token = headers
- .get(header::AUTHORIZATION)
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let bearer_ok = header_token
- .map(crate::core::auth::verify_bearer_token)
- .unwrap_or(false);
- let bearer_ok = bearer_ok
- || query
- .token
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(crate::core::auth::verify_bearer_token)
- .unwrap_or(false);
- if !bearer_ok {
- log::warn!("[ws] dictation upgrade rejected: missing or invalid bearer token");
- return (
- StatusCode::UNAUTHORIZED,
- Json(json!({
- "ok": false,
- "error": "unauthorized",
- "message": "Missing or invalid token. Supply 'Authorization: Bearer <core>' or ?token=<core>."
- })),
- )
- .into_response();
- }
-
- ws.on_upgrade(|socket| async move {
- let config = match crate::config::rpc::load_config_with_timeout().await {
- Ok(c) => Arc::new(c),
- Err(e) => {
- log::error!("[ws] failed to load config for dictation: {e}");
- return;
- }
- };
- crate::voice::streaming::handle_dictation_ws(socket, config).await;
- })
-}
-
-/// Maximum accepted request-body size for the core HTTP server (64 MiB).
-///
-/// Sized to comfortably hold a `channel_web_chat` turn carrying the composer's
-/// maximum image payload — 4 × 8 MiB raw ≈ 43 MiB once base64-encoded into
-/// `[IMAGE:data:…]` markers — plus message text and JSON-RPC envelope overhead.
-/// Axum's 2 MiB default would otherwise reject any image attachment (#3205).
-#[cfg(feature = "http-server")]
-const MAX_RPC_BODY_BYTES: usize = 64 * 1024 * 1024;
-
-/// Builds the main Axum router for the core HTTP server.
-///
-/// Includes routes for health, schema, SSE events, JSON-RPC, and Telegram auth.
-/// Conditionally attaches Socket.IO if enabled.
-///
-/// Middleware order (outermost → innermost):
-/// 1. `cors_middleware` — handles `OPTIONS` preflight and adds CORS headers
-/// 2. `rpc_auth_middleware` — validates `Authorization: Bearer <token>` on protected paths
-/// 3. `http_request_log_middleware` — logs non-RPC HTTP requests with timing
-#[cfg(feature = "http-server")]
-pub fn build_core_http_router(socketio_enabled: bool) -> Router {
- let router = Router::new()
- .route("/", get(root_handler))
- .route("/health", get(health_handler))
- .route("/schema", get(schema_handler))
- .route("/events", get(events_handler))
- .route("/events/webhooks", get(webhook_events_handler))
- .route("/events/domain", get(domain_events_handler))
- // Raise the request-body cap above Axum's 2 MiB default — scoped to
- // `/rpc` only so other routes keep the default. Chat image attachments
- // are inlined into the `channel_web_chat` JSON-RPC body as base64
- // `data:` URIs, and the composer permits up to ATTACHMENT_MAX_IMAGES (4)
- // × ATTACHMENT_MAX_SIZE_BYTES (8 MiB) of raw image ≈ 43 MiB once
- // base64-encoded. Without this the whole turn was rejected at the local
- // RPC boundary with "failed to buffer the request body: length limit
- // exceeded" before anything reached the provider (issue #3205). The
- // server binds to 127.0.0.1 behind a per-launch bearer, so a generous
- // localhost cap is safe.
- .route(
- "/rpc",
- post(rpc_handler).route_layer(DefaultBodyLimit::max(MAX_RPC_BODY_BYTES)),
- )
- .route("/ws/dictation", get(dictation_ws_handler))
- .route("/oauth/mcp/callback", get(oauth_mcp_callback_handler))
- // Dev-only: hand this core (URL + bearer) to a loopback Vite renderer.
- .route(
- "/dev/connect",
- get(crate::core::dev_connect::dev_connect_handler),
- )
- // OpenAI-compatible inference endpoint (/v1/chat/completions, /v1/models)
- .nest("/v1", crate::inference::http::router())
- // Apply `AppState` here so the outer router becomes `Router<()>` and
- // matches any state-less sub-router merged into it.
- .with_state(AppState {
- core_version: env!("CARGO_PKG_VERSION").to_string(),
- });
-
- let router = router
- .fallback(not_found_handler)
- .layer(middleware::from_fn(http_request_log_middleware))
- .layer(middleware::from_fn(crate::core::auth::rpc_auth_middleware))
- .layer(middleware::from_fn(cors_middleware));
-
- if socketio_enabled {
- let (socket_layer, io) = crate::core::socketio::attach_socketio();
- crate::core::socketio::spawn_web_channel_bridge(io);
- return router.layer(socket_layer);
- }
-
- router
-}
-
-/// Middleware for logging incoming HTTP requests.
-///
-/// The `/rpc` path is logged inside [`rpc_handler`] instead (with the
-/// JSON-RPC method name), so we skip it here to avoid a redundant line.
-#[cfg(feature = "http-server")]
-async fn http_request_log_middleware(req: Request, next: Next) -> Response {
- let method = req.method().clone();
- let path = req.uri().path().to_string();
- let query_len = req.uri().query().map(str::len).unwrap_or(0);
- let started = std::time::Instant::now();
-
- let response = next.run(req).await;
-
- if path != "/rpc" {
- let status = response.status().as_u16();
- let ms = started.elapsed().as_millis();
- tracing::info!(
- "[http] {} {}{} -> {} ({}ms)",
- method,
- path,
- if query_len > 0 { "?…" } else { "" },
- status,
- ms
- );
- }
-
- response
-}
-
-/// Environment variable for additional comma-separated origins to allow.
-/// Intended for debug harnesses and E2E setups that don't run on loopback —
-/// e.g. `OPENHUMAN_CORE_ALLOWED_ORIGINS=https://e2e.internal,http://my-debugger:8080`.
-#[cfg(feature = "http-server")]
-const ALLOWED_ORIGINS_ENV: &str = "OPENHUMAN_CORE_ALLOWED_ORIGINS";
-
-/// Decides whether a browser `Origin` header value is allowed to make
-/// authenticated cross-origin requests against the local RPC server.
-///
-/// The RPC server only ever serves three legitimate consumers:
-/// 1. The bundled Tauri v2 webview — `tauri://localhost` on macOS/Linux and
-/// `http(s)://tauri.localhost` on Windows.
-/// 2. The Vite dev server during `pnpm dev` — any port on loopback hosts.
-/// 3. Operator-controlled debug harnesses opted in via
-/// `OPENHUMAN_CORE_ALLOWED_ORIGINS`.
-///
-/// Anything else (a random web page that has somehow obtained the bearer
-/// token via leaked logs / screenshots / a compromised third-party origin
-/// loaded in a CEF child webview) must be refused — the bearer token alone
-/// is not enough authorization without an origin binding.
-#[cfg(feature = "http-server")]
-pub(super) fn is_origin_allowed(origin: &str) -> bool {
- let extra_origins = std::env::var(ALLOWED_ORIGINS_ENV).ok();
- is_origin_allowed_with_extra(origin, extra_origins.as_deref())
-}
-
-#[cfg(feature = "http-server")]
-pub(super) fn is_origin_allowed_with_extra(origin: &str, extra_origins: Option<&str>) -> bool {
- // Tauri v2 webview origins. Windows uses an HTTP(S) custom host; macOS
- // and Linux use the `tauri://` scheme. We accept both for portability.
- if matches!(
- origin,
- "tauri://localhost" | "http://tauri.localhost" | "https://tauri.localhost"
- ) {
- return true;
- }
-
- // Loopback origins on any port (Vite dev server, E2E driver, CLI tools).
- if let Some(rest) = origin.strip_prefix("http://") {
- let authority = rest.split('/').next().unwrap_or("");
- let host = if let Some(stripped) = authority.strip_prefix('[') {
- // IPv6 literal: `[::1]:1420` → `::1`
- stripped.split(']').next().unwrap_or("")
- } else {
- authority.split(':').next().unwrap_or("")
- };
- if matches!(host, "127.0.0.1" | "localhost" | "::1") {
- return true;
- }
- }
-
- // Env override: comma-separated exact matches.
- if let Some(extra) = extra_origins {
- for candidate in extra.split(',').map(str::trim).filter(|s| !s.is_empty()) {
- if candidate == origin {
- return true;
- }
- }
- }
-
- false
-}
-
-/// Middleware for handling Cross-Origin Resource Sharing (CORS).
-///
-/// Reads the request's `Origin` header before invoking the inner handler so
-/// the same value can be echoed back (when allowed) on the response.
-#[cfg(feature = "http-server")]
-async fn cors_middleware(req: Request, next: Next) -> Response {
- let origin = req
- .headers()
- .get(header::ORIGIN)
- .and_then(|v| v.to_str().ok())
- .map(str::to_owned);
-
- if req.method() == Method::OPTIONS {
- return with_cors_headers(StatusCode::NO_CONTENT.into_response(), origin.as_deref());
- }
-
- let response = next.run(req).await;
- with_cors_headers(response, origin.as_deref())
-}
-
-/// Injects CORS headers into a response.
-///
-/// If the request carried an `Origin` header and that origin is on the
-/// allowlist, the value is echoed back in `Access-Control-Allow-Origin` and
-/// `Vary: Origin` is set so intermediate caches keep per-origin responses
-/// distinct. Disallowed origins receive no `Access-Control-Allow-Origin`
-/// header at all — the browser will then refuse to surface the response to
-/// the calling JS. Non-browser callers (no `Origin` header) are unaffected.
-///
-/// For Docker / cloud deployments where the server binds to `0.0.0.0`,
-/// extend the allowlist via the `OPENHUMAN_CORE_ALLOWED_ORIGINS` env var
-/// (comma-separated) rather than wildcarding `Access-Control-Allow-Origin`.
-#[cfg(feature = "http-server")]
-pub(super) fn with_cors_headers(mut response: Response, origin: Option<&str>) -> Response {
- let headers = response.headers_mut();
- headers.append(header::VARY, HeaderValue::from_static("Origin"));
-
- if let Some(o) = origin {
- if is_origin_allowed(o) {
- if let Ok(val) = HeaderValue::from_str(o) {
- headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, val);
- }
- } else {
- tracing::warn!("[cors] rejected disallowed origin: {}", o);
- }
- }
-
- headers.insert(
- header::ACCESS_CONTROL_ALLOW_METHODS,
- HeaderValue::from_static("GET, POST, OPTIONS"),
- );
- headers.insert(
- header::ACCESS_CONTROL_ALLOW_HEADERS,
- HeaderValue::from_static("Content-Type, Authorization"),
- );
- headers.insert(
- header::ACCESS_CONTROL_MAX_AGE,
- HeaderValue::from_static("86400"),
- );
- response
-}
-
-/// Handler for the health check endpoint.
-///
-/// Liveness is granular (#3312): a single degraded *background* component
-/// (scheduler, channels, update_checker, …) no longer 503s the whole container.
-/// `/health` returns 503 only when a *critical* component is unhealthy (see
-/// `health::CRITICAL_COMPONENTS`); otherwise it returns 200 — with a `degraded`
-/// flag and per-component buckets in the body so readiness probes and operators
-/// can still see partial failures.
-#[cfg(feature = "http-server")]
-async fn health_handler() -> impl IntoResponse {
- let snapshot = crate::platform::health::snapshot();
- let verdict = crate::platform::health::verdict(&snapshot);
-
- let status = if verdict.healthy {
- StatusCode::OK
- } else {
- StatusCode::SERVICE_UNAVAILABLE
- };
-
- // Augment the snapshot body with the verdict so the components map stays
- // backward-compatible while exposing overall liveness/readiness.
- let mut body = serde_json::to_value(&snapshot).unwrap_or_else(|_| serde_json::json!({}));
- if let Some(obj) = body.as_object_mut() {
- obj.insert("healthy".to_string(), serde_json::json!(verdict.healthy));
- obj.insert("degraded".to_string(), serde_json::json!(verdict.degraded));
- obj.insert(
- "critical_unhealthy".to_string(),
- serde_json::json!(verdict.critical_unhealthy),
- );
- obj.insert(
- "degraded_components".to_string(),
- serde_json::json!(verdict.degraded_components),
- );
- }
-
- tracing::debug!(
- "[health] status={} components={} healthy={} degraded={} critical_unhealthy={:?} degraded_components={:?}",
- status.as_u16(),
- snapshot.components.len(),
- verdict.healthy,
- verdict.degraded,
- verdict.critical_unhealthy,
- verdict.degraded_components,
- );
-
- (status, Json(body))
-}
-
-/// Handler for the schema discovery endpoint.
-#[cfg(feature = "http-server")]
-async fn schema_handler(State(_state): State<AppState>) -> impl IntoResponse {
- (StatusCode::OK, Json(build_http_schema_dump())).into_response()
-}
-
-/// Query parameters for the events SSE endpoint.
-///
-/// `client_id` selects which broadcast events to forward; `token` is the
-/// single-shot bind token minted by the `core.events_subscribe_token` RPC.
-/// Both are required — browser `EventSource` cannot attach an
-/// `Authorization` header, so the bind token is the only credential the
-/// endpoint accepts.
-#[cfg(feature = "http-server")]
-#[derive(Debug, serde::Deserialize)]
-struct EventsQuery {
- client_id: String,
- #[serde(default)]
- token: Option<String>,
-}
-
-/// Handler for the main events SSE endpoint.
-///
-/// Accepts either of two credentials:
-/// 1. `Authorization: Bearer <core token>` — used by CLI tooling, the
-/// Tauri shell via `core_rpc_relay`, and the in-tree e2e suite that
-/// can set HTTP headers directly. Validated against the same
-/// per-process bearer the rest of `/rpc` uses.
-/// 2. `?token=<bind>` minted via the `core.events_subscribe_token` RPC
-/// — used by browser `EventSource`, which cannot attach custom
-/// headers. The token is bound to a specific `client_id` and is
-/// consumed on validation so a leaked URL cannot be replayed.
-///
-/// Both paths converge on the same broadcast stream filtered by
-/// `client_id`.
-#[cfg(feature = "http-server")]
-async fn events_handler(
- headers: axum::http::HeaderMap,
- Query(query): Query<EventsQuery>,
-) -> Response {
- let bearer = headers
- .get(header::AUTHORIZATION)
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let bearer_ok = bearer
- .map(crate::core::auth::verify_bearer_token)
- .unwrap_or(false);
-
- if !bearer_ok {
- let supplied_token = query
- .token
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let Some(supplied_token) = supplied_token else {
- log::warn!(
- "[events] reject subscribe: missing bind token + missing bearer (client_id_len={})",
- query.client_id.len()
- );
- return (
- StatusCode::UNAUTHORIZED,
- Json(json!({
- "ok": false,
- "error": "unauthorized",
- "message": "Missing credentials. Supply 'Authorization: Bearer <core>' or mint a bind token with the `core.events_subscribe_token` RPC and pass it as ?token="
- })),
- )
- .into_response();
- };
- if !crate::core::event_bind_tokens::consume(&query.client_id, supplied_token) {
- log::warn!(
- "[events] reject subscribe: bind token invalid or expired (client_id_len={})",
- query.client_id.len()
- );
- return (
- StatusCode::UNAUTHORIZED,
- Json(json!({
- "ok": false,
- "error": "unauthorized",
- "message": "Bind token is unknown, expired, or bound to a different client_id."
- })),
- )
- .into_response();
- }
- }
-
- let client_id = query.client_id;
- let rx = crate::web_chat::subscribe_web_channel_events();
- let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(
- move |item| -> Option<Result<Event, std::convert::Infallible>> {
- let event = match item {
- Ok(ev) => ev,
- Err(_) => return None,
- };
- if event.client_id != client_id {
- return None;
- }
- let data = match serde_json::to_string(&event) {
- Ok(data) => data,
- Err(_) => return None,
- };
- Some(Ok(Event::default().event(event.event).data(data)))
- },
- );
-
- Sse::new(stream)
- .keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(10)))
- .into_response()
-}
-
-/// Handler for the webhook debug events SSE endpoint.
-#[cfg(feature = "http-server")]
-async fn webhook_events_handler() -> Response {
- let stream = tokio_stream::once(Ok::<Event, std::convert::Infallible>(
- Event::default()
- .event("webhooks_debug")
- .data("{\"event_type\":\"runtime_removed\"}"),
- ));
- Sse::new(stream)
- .keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(10)))
- .into_response()
-}
-
-/// SSE endpoint streaming DomainEvent bus events for the live event log panel.
-///
-/// Requires bearer auth. Streams all domain events as JSON with event type
-/// set to the domain name (agent, tool, memory, etc.).
-#[cfg(feature = "http-server")]
-async fn domain_events_handler(headers: axum::http::HeaderMap) -> Response {
- let bearer = headers
- .get(header::AUTHORIZATION)
- .and_then(|v| v.to_str().ok())
- .and_then(|v| v.strip_prefix("Bearer "))
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let bearer_ok = bearer
- .map(crate::core::auth::verify_bearer_token)
- .unwrap_or(false);
-
- if !bearer_ok {
- log::warn!("[events/domain] reject subscribe: missing or invalid bearer token");
- return (
- StatusCode::UNAUTHORIZED,
- Json(json!({
- "ok": false,
- "error": "unauthorized",
- "message": "Bearer token required for domain event stream"
- })),
- )
- .into_response();
- }
-
- // Read dashboard config for event stream settings.
- let es_cfg = crate::config::rpc::load_config_with_timeout()
- .await
- .map(|c| c.dashboard.event_stream)
- .unwrap_or_default();
-
- if !es_cfg.enabled {
- return (
- StatusCode::NOT_FOUND,
- Json(json!({ "ok": false, "error": "event stream disabled by config" })),
- )
- .into_response();
- }
-
- let bus = match crate::core::bus::BUS.get() {
- Some(bus) => bus,
- None => {
- log::warn!("[events/domain] event bus not initialized");
- return (
- StatusCode::SERVICE_UNAVAILABLE,
- Json(json!({ "ok": false, "error": "event bus not initialized" })),
- )
- .into_response();
- }
- };
-
- log::debug!("[events/domain] client connected, streaming domain events");
-
- // The active workspace, resolved once here so a client that connects
- // mid-life starts out knowing which rows are its own rather than
- // waiting for the next event to tell it (#5966). This is the one place
- // in this handler that can afford the authoritative read — it happens
- // per connection, not per event — and it refills the cache the row
- // stamping below relies on.
- let active_workspace = crate::config::active_workspace_dir()
- .await
- .map(|dir| crate::config::workspace_handle(&dir))
- .map_err(|error| {
- log::warn!(
- "[events/domain] could not resolve the active workspace ({error}); \
- the client will scope the log once an event says which workspace is active"
- );
- })
- .ok();
-
- // Send config as first SSE event so frontend can apply settings.
- let config_event = Event::default().event("config").data(
- serde_json::to_string(&json!({
- "max_entries": es_cfg.max_entries,
- "new_entries": es_cfg.new_entries,
- "active_workspace": active_workspace,
- }))
- .unwrap_or_default(),
- );
-
- // `BroadcastStream` wraps a raw `broadcast::Receiver`; tinybus hands back a
- // decoding receiver instead, so the stream is built by unfolding it. Lag is
- // already handled inside `recv`, which is why there is no error arm to
- // filter out any more.
- let event_stream = futures::stream::unfold(bus.receiver(), |mut rx| async move {
- rx.recv()
- .await
- .map(|event| (Ok::<_, std::convert::Infallible>(event), rx))
- })
- .filter_map(|item| -> Option<Result<Event, std::convert::Infallible>> {
- let event = match item {
- Ok(ev) => ev,
- Err(_) => return None,
- };
- let domain = event.domain().to_string();
- let event_name = event.variant_name();
- let agent = event.agent_hint().unwrap_or("").to_string();
- // Most variants say everything in their name; the ones whose point is
- // a failure *reason* would otherwise reach the log with the reason
- // discarded, so they opt into one already-redacted line (#5931). It is
- // `null` for every other variant, which renders as no change.
- let detail = event.log_detail();
- // Which workspace this row belongs to, and which one is current
- // (#5966). One process serves more than one workspace over its life,
- // so without these two a row left over from a workspace the user has
- // switched away from is indistinguishable from one belonging to the
- // workspace they are in.
- //
- // Both are *handles*, never `workspace_dir` itself: this envelope
- // feeds a settings panel and its NDJSON download, and the path is
- // under the user's home directory.
- //
- // `active` is read from the cache rather than resolved. This closure
- // is synchronous — `tokio_stream`'s `filter_map` — so it could not
- // await a resolve, and it runs for every domain event the process
- // publishes, so it should not want to. `None` means "not resolved
- // since the last workspace marker write", which the client treats as
- // unknown rather than as a mismatch.
- let workspace = event.workspace_dir().map(crate::config::workspace_handle);
- let active = crate::config::active_workspace_dir_cached()
- .map(|dir| crate::config::workspace_handle(&dir));
- let data = json!({
- "domain": domain,
- "event": event_name,
- "agent": agent,
- "detail": detail,
- "workspace": workspace,
- "active_workspace": active,
- "timestamp": chrono::Utc::now().format("%H:%M:%S").to_string(),
- });
- let data_str = serde_json::to_string(&data).ok()?;
- Some(Ok(Event::default().event(domain).data(data_str)))
- });
-
- let config_stream =
- futures::stream::once(async move { Ok::<_, std::convert::Infallible>(config_event) });
- let stream = config_stream.chain(event_stream);
-
- Sse::new(stream)
- .keep_alive(KeepAlive::new().interval(std::time::Duration::from_secs(5)))
- .into_response()
-}
-
-/// Handler for the root endpoint, returning server information and available endpoints.
-#[cfg(feature = "http-server")]
-async fn root_handler() -> impl IntoResponse {
- // `null` when no backend transport is installed.
- let api_server = match crate::config::Config::load_or_init().await {
- Ok(cfg) => crate::backend::base_url(&cfg.api_url).ok(),
- Err(_) => crate::backend::base_url(&None).ok(),
- };
-
- (
- StatusCode::OK,
- Json(json!({
- "name": "openhuman",
- "ok": true,
- "api_server": api_server,
- "endpoints": {
- "health": "/health",
- "schema": "/schema",
- "events": "/events?client_id=<id>&token=<core.events_subscribe_token>",
- "rpc": "/rpc"
- },
- "usage": {
- "jsonrpc": {
- "version": "2.0",
- "method": "core.ping",
- "params": {}
- }
- }
- })),
- )
-}
-
-/// Fallback handler for unknown routes.
-#[cfg(feature = "http-server")]
-async fn not_found_handler() -> impl IntoResponse {
- (
- StatusCode::NOT_FOUND,
- Json(json!({
- "ok": false,
- "error": "not_found",
- "message": "Route not found. Try /, /health, /schema, or /rpc."
- })),
- )
-}
-
-/// Resolves the port for the core server from environment variables or defaults.
-#[cfg(feature = "http-server")]
-pub(crate) fn core_port() -> u16 {
- std::env::var("OPENHUMAN_CORE_PORT")
- .ok()
- .and_then(|v| v.parse::<u16>().ok())
- .unwrap_or(7788)
-}
-
-/// Resolves the bind address host for the core server from environment variables or defaults.
-#[cfg(feature = "http-server")]
-pub(crate) fn core_host() -> String {
- std::env::var("OPENHUMAN_CORE_HOST")
- .ok()
- .filter(|s| !s.is_empty())
- .unwrap_or_else(|| "127.0.0.1".to_string())
-}
-
-/// Metadata sent back to the Tauri host once the embedded core has selected
-/// and bound its listen port.
-#[derive(Debug, Clone)]
-pub struct EmbeddedReadySignal {
- pub port: u16,
- pub fallback_from: Option<u16>,
-}
-
-/// Runs the HTTP/JSON-RPC server.
-///
-/// This function binds to the specified host and port, initializes the router,
-/// bootstraps long-lived runtime infrastructure, and starts serving requests.
-pub async fn run_server(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
-) -> anyhow::Result<()> {
- run_server_inner(host, port, socketio_enabled, false, None, None, None).await
-}
-
-/// Runs the request/response-only HTTP API without detached background jobs.
-pub async fn run_server_headless(host: Option<&str>, port: Option<u16>) -> anyhow::Result<()> {
- let services = crate::core::runtime::ServiceSet::headless_api();
- run_server_with_services(host, port, services, false, None, None, None).await
-}
-
-/// Like [`run_server`] but marks the instance as embedded.
-pub async fn run_server_embedded(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
- shutdown_token: CancellationToken,
-) -> anyhow::Result<()> {
- run_server_inner(
- host,
- port,
- socketio_enabled,
- true,
- Some(shutdown_token),
- None,
- None,
- )
- .await
-}
-
-/// Embedded entrypoint with an explicit readiness callback.
-///
-/// When the caller already holds the per-launch RPC bearer in memory (the
-/// Tauri shell now that the core runs in-process — PR #1061), it should
-/// pass `Some(token)` so the embedded server can seed its auth subsystem
-/// via [`crate::core::auth::init_rpc_token_with_value`] without ever
-/// reading `OPENHUMAN_CORE_TOKEN` from the process environment. Passing
-/// `None` preserves the env-as-config fallback (CLI / docker / cloud).
-pub async fn run_server_embedded_with_ready(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
- shutdown_token: CancellationToken,
- ready_tx: tokio::sync::oneshot::Sender<EmbeddedReadySignal>,
- rpc_token: Option<std::sync::Arc<String>>,
-) -> anyhow::Result<()> {
- run_server_inner(
- host,
- port,
- socketio_enabled,
- true,
- Some(shutdown_token),
- Some(ready_tx),
- rpc_token,
- )
- .await
-}
-
-/// Internal server entrypoint.
-async fn run_server_inner(
- host: Option<&str>,
- port: Option<u16>,
- socketio_enabled: bool,
- embedded_core: bool,
- shutdown_token: Option<CancellationToken>,
- ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,
- rpc_token: Option<std::sync::Arc<String>>,
-) -> anyhow::Result<()> {
- let mut services = crate::core::runtime::ServiceSet::desktop();
- services.socketio = socketio_enabled;
- run_server_with_services(
- host,
- port,
- services,
- embedded_core,
- shutdown_token,
- ready_tx,
- rpc_token,
- )
- .await
-}
-
-async fn run_server_with_services(
- host: Option<&str>,
- port: Option<u16>,
- services: crate::core::runtime::ServiceSet,
- embedded_core: bool,
- shutdown_token: Option<CancellationToken>,
- ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,
- rpc_token: Option<std::sync::Arc<String>>,
-) -> anyhow::Result<()> {
- // `run_server_inner` is now a thin shim over the CoreBuilder/CoreRuntime
- // composition (Phase 1). It reproduces the legacy behavior exactly: all
- // background services on (`ServiceSet::desktop`), Socket.IO per the caller
- // flag, and the legacy `embedded_core` → `HostKind` mapping (embedded ==
- // Tauri shell; standalone splits CLI / Docker via `detect_standalone`).
- // See the pluggable-core work (`core::runtime`).
- let host_kind = if embedded_core {
- crate::core::types::HostKind::TauriShell
- } else {
- crate::core::types::HostKind::detect_standalone()
- };
- let token = match rpc_token {
- Some(token) => crate::core::runtime::TokenSource::Fixed(token),
- None => crate::core::runtime::TokenSource::EnvOrFile,
- };
- let mut builder = crate::core::runtime::CoreBuilder::new(host_kind)
- .token(token)
- .services(services);
- // The browser E2E harness scripts direct tool calls through its mock model.
- // Keep production's fail-closed packed default, while making those calls
- // visible in the deterministic test core without changing library hosts.
- builder = apply_e2e_tool_groups(builder);
- if let Some(host) = host {
- builder = builder.host(host);
- }
- if let Some(port) = port {
- builder = builder.port(port);
- }
-
- let runtime = builder.build().await?;
- runtime.serve(ready_tx, shutdown_token).await
-}
-
-fn apply_e2e_tool_groups(
- builder: crate::core::runtime::CoreBuilder,
-) -> crate::core::runtime::CoreBuilder {
- if std::env::var_os("OPENHUMAN_E2E").is_some() {
- builder.tool_groups(crate::tools::toolpacks::ToolGroups::advertised())
- } else {
- builder
- }
-}
-
-/// Per-`DomainGroup` gating decision for each event-bus subscriber that
-/// [`register_domain_subscribers`] conditionally registers. Extracted as a
-/// pure value so the subscriber→group mapping has a single source of truth
-/// that the registrar consumes and tests assert directly — without registering
-/// real subscribers or touching the process-global event bus (#4796 DoD item 3).
-///
-/// Unlisted subscribers (health, scheduler-gate, TokenJuice content-router,
-/// session-token seeding, `SessionExpired`, service restart/shutdown) are
-/// always registered as core/platform infra and intentionally absent here.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct DomainSubscriberPlan {
- /// Reserved for subscribers with no family of their own. Currently none:
- /// the reorg gave every subscriber that used to live here a real family
- /// (see the fields below), so this stays for future kernel-level ones.
- pub platform: bool,
- /// composio trigger archive + trigger subscriber + task-sources poller.
- pub integrations: bool,
- /// device tunnel handshake/peer-status subscriber.
- pub security: bool,
- /// notification bridge (desktop-shell delivery).
- pub desktop: bool,
- /// webhook request subscriber (skills own inbound webhook routing).
- pub skills: bool,
- /// channel-inbound + web-only proactive.
- pub channels: bool,
- /// flows trigger dispatch.
- pub flows: bool,
- /// memory conversation-persistence + sync-stage bridge.
- pub memory: bool,
- /// agent handlers + background delivery + run-ledger finalizer + orchestration ingest.
- pub agent: bool,
- /// hosted orchestration ingest.
- pub hosted: bool,
- /// mcp::registry lifecycle bus init.
- pub mcp: bool,
-}
-
-impl DomainSubscriberPlan {
- /// The subscriber-registration plan for `domains`. Pure: no side effects.
- pub fn for_domains(domains: crate::core::runtime::DomainSet) -> Self {
- use crate::core::all::DomainGroup;
- Self {
- platform: domains.allows(DomainGroup::Platform),
- integrations: domains.allows(DomainGroup::Integrations),
- security: domains.allows(DomainGroup::Security),
- desktop: domains.allows(DomainGroup::Desktop),
- skills: domains.allows(DomainGroup::Skills),
- channels: domains.allows(DomainGroup::Channels),
- flows: domains.allows(DomainGroup::Flows),
- memory: domains.allows(DomainGroup::Memory),
- agent: domains.allows(DomainGroup::Agent),
- hosted: domains.allows(DomainGroup::Hosted),
- mcp: domains.allows(DomainGroup::Mcp),
- }
- }
-}
-
-/// Consume a domain's registration token only when the global event bus is
-/// ready. An early bus-unavailable attempt therefore remains retryable.
-fn group_first_time_when_bus_ready(
- completed: &std::sync::Mutex<std::collections::HashSet<crate::core::all::DomainGroup>>,
- group: crate::core::all::DomainGroup,
- bus_ready: bool,
-) -> bool {
- if !bus_ready {
- log::warn!("[event_bus] deferred {group:?} subscriber registration - bus not initialized");
- return false;
- }
-
- completed
- .lock()
- .expect("domain-subscriber registry lock poisoned")
- .insert(group)
-}
-
-fn group_first_time(group: crate::core::all::DomainGroup) -> bool {
- use std::collections::HashSet;
- use std::sync::{Mutex, OnceLock};
-
- static DONE: OnceLock<Mutex<HashSet<crate::core::all::DomainGroup>>> = OnceLock::new();
- group_first_time_when_bus_ready(
- DONE.get_or_init(|| Mutex::new(HashSet::new())),
- group,
- crate::core::bus::BUS.get().is_some(),
- )
-}
-
-/// Consume the learning-subscriber token only when the global event bus is
-/// ready. Learning has a separate token from the Agent group because both
-/// registration blocks must run exactly once.
-fn learning_first_time_when_bus_ready(completed: &std::sync::Mutex<bool>, bus_ready: bool) -> bool {
- if !bus_ready {
- log::warn!(
- "[event_bus] deferred Agent learning subscriber registration - bus not initialized"
- );
- return false;
- }
-
- let mut completed = completed
- .lock()
- .expect("learning-subscriber registry lock poisoned");
- if *completed {
- false
- } else {
- *completed = true;
- true
- }
-}
-
-fn learning_first_time() -> bool {
- static DONE: std::sync::OnceLock<std::sync::Mutex<bool>> = std::sync::OnceLock::new();
- learning_first_time_when_bus_ready(
- DONE.get_or_init(|| std::sync::Mutex::new(false)),
- crate::core::bus::BUS.get().is_some(),
- )
-}
-
-/// Registers all long-lived domain event-bus subscribers, each group at most
-/// once per process.
-///
-/// Ungated core/platform infra runs exactly once behind `INFRA: Once`; each
-/// gated [`DomainGroup`](crate::core::all::DomainGroup) installs the first time
-/// it is enabled after the event bus is ready, so widening the ambient
-/// `DomainSet` on a later call (`harness()` → `full()`) still installs the
-/// newly-enabled groups without double-subscribing the ones already registered.
-fn register_domain_subscribers(
- workspace_dir: std::path::PathBuf,
- config: crate::config::Config,
- embedded_core: bool,
- domains: crate::core::runtime::DomainSet,
-) {
- use crate::core::all::DomainGroup;
- use std::sync::{Arc, Once};
-
- let plan = DomainSubscriberPlan::for_domains(domains);
- log::debug!("[event_bus] register_domain_subscribers: domains={domains:?} plan={plan:?}");
-
- // `subscribe_global` returns `None` only before the process-global bus is
- // initialized. Because that bus is a monotonic `OnceLock`, checking it here
- // guarantees the registrations in the guarded block cannot later lose bus
- // availability. A premature call leaves the group absent from `DONE`, so a
- // later bootstrap retries it instead of permanently skipping subscribers.
-
- // Seed the live tool-execution timeout from the persisted `[agent]` config
- // so a user-configured value (Settings → Agent OS access → Action timeout)
- // is in effect from the first tool call. `OPENHUMAN_TOOL_TIMEOUT_SECS`, when
- // set, still overrides this inside `set_tool_timeout_secs`. This lives on
- // the always-on boot path (not `channels::runtime::startup::start_channels`,
- // which is skipped for channel-less / web-chat-only cores) so the timeout
- // seeds for every install regardless of DomainSet — it is DomainSet-
- // independent process-global state, not a gated subscriber (#5027).
- //
- // Deliberately OUTSIDE the `INFRA: Once` below: `bootstrap_core_runtime`
- // re-runs on an in-process core restart (`CoreProcessHandle::restart` →
- // `ensure_running`, and `reset_local_data`/Clear-Local-Data) with a freshly
- // reloaded `Config`, but `INFRA` is already consumed — so a seed gated by it
- // would leave the process-global timeout pinned to the previous config's
- // value until Settings is re-saved. `set_tool_timeout_secs` is idempotent
- // (a plain atomic store honouring the env override), so re-seeding on every
- // call is correct and cheap and re-applies the current config each boot.
- let effective_timeout =
- crate::tools::timeout::set_tool_timeout_secs(config.agent.agent_timeout_secs);
- log::debug!(
- "[tool_timeout] seeded tool-execution timeout from config: configured={}s effective={}s",
- config.agent.agent_timeout_secs,
- effective_timeout
- );
-
- // Ungated core/platform infra — health, scheduler-gate, TokenJuice
- // content-router, session-token seeding, the SessionExpired handler, and
- // service restart/shutdown. These are DomainSet-independent, so they run
- // exactly once on the first call regardless of which composition boots
- // first. Registered BEFORE any gated subscriber so the SessionExpired
- // handler is live before a gated subscriber could publish a 401-derived
- // event. Leaked `SubscriptionHandle`s live for the whole process
- // (`SubscriptionHandle::drop` aborts the task).
- static INFRA: Once = Once::new();
- INFRA.call_once(|| {
- crate::platform::health::bus::register_health_subscriber();
-
- // Initialise the scheduler gate before any background AI workers start
- // so they observe a real policy on their first iteration (otherwise they
- // fall back to `Policy::Normal` and miss the initial throttle decision on
- // battery-powered hosts).
- crate::cron::scheduler_gate::init_global(&config);
-
- // A headless host (Docker / VPS / CI) has no interactive login; it
- // hands the core a credential through the environment instead. The
- // API key is a plain profile write, so it lands before the gate is
- // seeded from the store below; a session token runs the full
- // `set_credential` path and seeds the gate itself when it finishes.
- crate::security::credentials::seed_api_key_from_env(&config);
- if std::env::var_os(crate::security::credentials::BACKEND_SESSION_TOKEN_ENV).is_some() {
- let config = config.clone();
- tokio::spawn(async move {
- crate::security::credentials::seed_session_from_env(&config).await;
- });
- }
-
- // Seed the scheduler-gate signed-out override from the on-disk
- // credential — an API key (library runtime) or the app session.
- // Without this, a sidecar that boots with no stored credential would
- // happily spin up cron / channel loops and fire LLM requests that all
- // 401.
- if crate::security::credentials::api_key::has_api_key(&config) {
- log::info!("[auth] api-key credential present at startup — scheduler gate signed in");
- crate::cron::scheduler_gate::set_signed_out(false);
- } else {
- match crate::security::credentials::jwt::get_session_token(&config) {
- Ok(Some(_)) => {
- crate::cron::scheduler_gate::set_signed_out(false);
- }
- Ok(None) => {
- log::info!(
- "[auth] no session token at startup — scheduler gate set to signed_out \
- (config_path={}, keyring_backend={})",
- config.config_path.display(),
- crate::security::keyring::backend_name(),
- );
- crate::cron::scheduler_gate::set_signed_out(true);
- }
- Err(err) => {
- log::warn!(
- "[auth] failed to read session token at startup ({err}) — assuming signed_out \
- (config_path={}, keyring_backend={})",
- config.config_path.display(),
- crate::security::keyring::backend_name(),
- );
- crate::cron::scheduler_gate::set_signed_out(true);
- }
- }
- }
-
- // Register the SessionExpired handler before any subscribers that might
- // publish 401-derived events, so the very first 401 is routed through
- // `clear_session` + the scheduler-gate override.
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::security::credentials::bus::SessionExpiredSubscriber::new(),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register SessionExpired subscriber — bus not initialized"
- );
- }
-
- // Restart requests go through a subscriber so every trigger path shares
- // the same respawn logic.
- crate::platform::service::bus::register_restart_subscriber();
- if embedded_core {
- log::info!(
- "[event_bus] embedded core: service shutdown subscriber not registered; Tauri cancellation token owns shutdown"
- );
- } else {
- // Shutdown requests use the same pattern; the standalone CLI
- // subscriber exits the current process after a short grace period.
- crate::platform::service::bus::register_shutdown_subscriber();
- }
- });
-
- // ---- Gated domain subscribers — each group installed at most once, the
- // first time its owning DomainGroup is enabled. -------------------------
-
- // Carved-out families: webhook (Skills), notification bridge (Desktop),
- // composio + task-sources (Integrations), and device tunnel (Security).
- if plan.skills {
- if group_first_time(DomainGroup::Skills) {
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::skills::webhooks::bus::WebhookRequestSubscriber::new(),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register webhook subscriber — bus not initialized"
- );
- }
- }
- } else {
- log::debug!("[event_bus] webhook subscriber SKIPPED — Skills domain disabled");
- }
-
- if plan.desktop {
- if group_first_time(DomainGroup::Desktop) {
- crate::desktop::notifications::register_notification_bridge_subscriber(config.clone());
- }
- } else {
- log::debug!("[event_bus] notification bridge SKIPPED — Desktop domain disabled");
- }
-
- if plan.integrations {
- if group_first_time(DomainGroup::Integrations) {
- if let Err(error) =
- crate::integrations::composio::init_composio_trigger_history(workspace_dir.clone())
- {
- log::warn!("[composio][history] failed to initialize trigger archive: {error}");
- }
- crate::integrations::composio::register_composio_trigger_subscriber();
- crate::integrations::task_sources::bus::register_task_sources_subscriber();
- }
- } else {
- log::debug!(
- "[event_bus] composio + task-sources subscribers SKIPPED — Integrations domain disabled"
- );
- }
-
- if plan.security {
- if group_first_time(DomainGroup::Security) {
- // Device tunnel subscriber: handles tunnel:frame handshakes,
- // peer-status events, and register acks. Must be live before any
- // tunnel:frame events can arrive.
- crate::security::devices::bus::register_device_tunnel_subscriber();
- }
- } else {
- log::debug!("[event_bus] device-tunnel subscriber SKIPPED — Security domain disabled");
- }
-
- if plan.agent {
- if learning_first_time() {
- // Always-on learning subscribers (email-signature producer, rebuild
- // trigger + periodic loop, ProfileMdRenderer). Previously wired only
- // in `channels::runtime::startup::start_channels`, which is skipped
- // when no channel is configured — silently dropping ALL learning for
- // channel-less users (#5003). `agent::learning` is an Agent-family
- // domain; it sat on the Platform boot path only because `learning`
- // used to be a top-level directory. Idempotent.
- crate::agent::learning::startup::register_learning_subscribers(workspace_dir.clone());
- }
- } else {
- log::debug!("[event_bus] learning subscribers SKIPPED — Agent domain disabled");
- }
-
- // Channels: inbound dispatch + web-only proactive messaging.
- // The `plan.channels` runtime guard cannot stand in for the compile-time
- // gate: the `channels::bus::ChannelInboundSubscriber` +
- // `channels::proactive` type paths below must still resolve for this to
- // compile, so the whole block is `#[cfg]`-gated too (mirrors the flows
- // dual-gate below).
- #[cfg(feature = "channels")]
- if plan.channels {
- if group_first_time(DomainGroup::Channels) {
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::channels::bus::ChannelInboundSubscriber::new(),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register channel subscriber — bus not initialized"
- );
- }
- // Web-only proactive message subscriber (no external channel
- // instances are registered here in the desktop runtime).
- crate::channels::proactive::register_web_only_proactive_subscriber();
- }
- } else {
- log::debug!(
- "[event_bus] Channels subscribers (inbound + web-only proactive) SKIPPED — Channels domain disabled"
- );
- }
- #[cfg(not(feature = "channels"))]
- log::debug!(
- "[event_bus] Channels subscribers (inbound + web-only proactive) SKIPPED — channels feature disabled at compile time"
- );
-
- // Flows trigger dispatch (issue B2): maps FlowScheduleTick /
- // ComposioTriggerReceived / WebhookIncomingRequest onto enabled flows and
- // runs `flows::ops::flows_run`, so schedule/app-event workflows still
- // dispatch when no realtime channel is configured or
- // `OPENHUMAN_DISABLE_CHANNEL_LISTENERS` short-circuits `start_channels`.
- // The `plan.flows` runtime guard cannot stand in for the compile-time gate:
- // the `flows::bus::FlowTriggerSubscriber` type path below must still resolve
- // for this to compile, so the whole block is `#[cfg]`-gated too.
- #[cfg(feature = "flows")]
- if plan.flows {
- if group_first_time(DomainGroup::Flows) {
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::flows::bus::FlowTriggerSubscriber::new(Arc::new(config.clone())),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register flows trigger subscriber — bus not initialized"
- );
- }
- // Post-run memory digest (issue #5173): on a successful
- // `FlowRunFinished`, writes a compact summary into the flow's own
- // private memory namespace so a later run can `flow_memory_recall`
- // it (e.g. a scheduled digest flow deduping what it already sent).
- // Registered in the same `group_first_time(DomainGroup::Flows)`
- // block as the trigger subscriber above — that guard only returns
- // `true` once per process, so a second, separate call here would
- // never register.
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::flows::bus::FlowRunDigestSubscriber::new(Arc::new(config.clone())),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register flows run-digest subscriber — bus not initialized"
- );
- }
- // Dedup commit-on-success (issue #5263 PR2): on every terminal
- // `FlowRunFinished`, settles each `dedup` node in the flow's graph
- // — unions tentative keys into committed on success, releases
- // (clears) tentative on failure/cancel/interrupt. This is the
- // host half of the `dedup` node's exactly-once contract; the node
- // itself (`tinyflows::nodes::control_flow::dedup`) only ever
- // reads `committed` and writes `tentative`. Registered in the
- // same `group_first_time(DomainGroup::Flows)` block as the other
- // two flows subscribers above — see the digest subscriber's
- // comment just above for why a second `group_first_time` guard
- // here would be redundant.
- if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(
- crate::flows::bus::DedupCommitSubscriber::new(Arc::new(config.clone())),
- )) {
- std::mem::forget(handle);
- } else {
- log::warn!(
- "[event_bus] failed to register flows dedup-commit subscriber — bus not initialized"
- );
- }
- }
- } else {
- log::debug!("[event_bus] flows trigger subscriber SKIPPED — Flows domain disabled");
- }
- #[cfg(not(feature = "flows"))]
- log::debug!(
- "[event_bus] flows trigger subscriber SKIPPED — flows feature disabled at compile time"
- );
-
- // Memory: conversation-persistence + sync-stage bridge.
- if plan.memory {
- if group_first_time(DomainGroup::Memory) {
- crate::memory::conversations::register_conversation_persistence_subscriber(
- workspace_dir.clone(),
- );
- crate::memory::sync_events_bridge::register_sync_stage_bridge(&config);
- }
- } else {
- log::debug!(
- "[event_bus] memory conversation-persistence + sync bridge SKIPPED — Memory domain disabled"
- );
- }
-
- // Agent: native agent handlers + background-completion delivery +
- // run-ledger finalizer.
- if plan.agent {
- if group_first_time(DomainGroup::Agent) {
- // Native request handlers — the agent `agent.run_turn` handler is
- // what channel dispatch calls instead of importing
- // `run_tool_call_loop` directly.
- crate::agent::bus::register_agent_handlers();
- // Background-completion delivery: when a detached sub-agent
- // (spawn_async_subagent) finishes, surface its result back into the
- // originating chat as an idle-gated, batched, system-injected turn.
- crate::agent::orchestration::background_delivery::register_background_delivery();
- // Run-ledger finalizer: detached `spawn_async_subagent` runs outlive
- // their parent turn, so their terminal `AgentProgress` never reaches
- // the per-turn progress bridge that settles the ledger. This
- // global-bus subscriber settles `agent_runs` from
- // `DomainEvent::Subagent{Completed,Failed}`, preventing rows from
- // leaking as perpetual `running` timeline entries on thread reopen.
- crate::agent::orchestration::run_ledger_finalize::register_run_ledger_finalize_subscriber(&config);
- }
- } else {
- log::debug!(
- "[event_bus] agent handlers + background delivery + run-ledger finalizer SKIPPED — Agent domain disabled"
- );
- }
-
- // MCP clients lifecycle subscriber: logs McpServer{Installed,Connected,
- // Disconnected} + McpClientToolExecuted for observability. The boot-time
- // spawn of installed servers (boot::spawn_installed_servers) runs later in
- // bootstrap_core_runtime; this subscriber must be live before then so those
- // connect events are observed (issue #3039 gap A1).
- //
- // What bringing the domain up means is the domain's own; this only says
- // when. The service it opens is wanted here rather than later for the same
- // reason as the subscriber: every RPC handler in the domain reaches for it,
- // and opening it from the boot-connect job would leave a window where a
- // handler answers "still starting" to a caller whose domain is, as far as
- // anything else can tell, already up.
- if plan.mcp {
- if group_first_time(DomainGroup::Mcp) {
- crate::mcp::start(&config);
- }
- } else {
- log::debug!("[event_bus] mcp_registry bus init SKIPPED — Mcp domain disabled");
- }
-
- log::info!("[event_bus] domain subscriber registration complete: plan={plan:?}");
-}
-
-/// Initializes long-lived socket/event-bus infrastructure.
-///
-/// `host_kind` identifies the embedding process (Tauri desktop shell vs
-/// standalone CLI / Docker). It drives the approval-gate's host-aware
-/// decision tree: under the Tauri shell, the `OPENHUMAN_APPROVAL_GATE=0`
-/// env override is ignored and a domain event is published so the UI can
-/// surface a banner; under CLI / Docker the override is honored (with a
-/// noisy log + a domain event so any connected dashboard can flag it).
-pub async fn bootstrap_core_runtime(
- host_kind: crate::core::types::HostKind,
- config: Option<crate::config::Config>,
- domains: crate::core::runtime::DomainSet,
-) {
- use crate::platform::socket::{set_global_socket_manager, SocketManager};
- use std::sync::Arc;
- // `embedded_core` derived from host_kind so the rest of the function (which
- // already keys behavior off the boolean) stays unchanged.
- let embedded_core = host_kind.is_desktop_shell();
- let Some(mut cfg) = config else {
- log::error!(
- "[runtime] Config unavailable for runtime bootstrap; workspace-bound startup skipped"
- );
- return;
- };
- let workspace_dir = cfg.workspace_dir.clone();
-
- // --- Event bus bootstrap ---
- // Ensure the global event bus is initialized (no-op if already done by start_channels).
- crate::core::bus::init().await.expect("bus init");
- let agent_enabled = domains.allows(crate::core::all::DomainGroup::Agent);
- if agent_enabled {
- crate::agent::file_state::init_global();
- } else {
- log::debug!("[boot] agent file-state coordinator SKIPPED — Agent domain disabled");
- }
- // Register domain subscribers for cross-module event handling. Ungated infra
- // runs once (INFRA: Once) and each DomainGroup installs at most once via the
- // per-group `group_first_time` set, so repeated calls to
- // bootstrap_core_runtime() cannot double-subscribe (and a later, wider
- // DomainSet still installs its newly-enabled groups).
- register_domain_subscribers(workspace_dir.clone(), cfg.clone(), embedded_core, domains);
-
- // Latch the config-corruption recovery signal (#5167) so `app_state_snapshot`
- // keeps reporting it after the loader heals the file on this same boot; the
- // frontend raises a one-shot "settings were reset" notice off it.
- crate::desktop::app_state::latch_from_config(&cfg);
-
- // --- Configurable hooks -------------------------------------------
- // Read every `hooks.json` layer and, only if something is configured,
- // install the harness bridge. Boot is the right moment: a hook that is
- // meant to gate the first tool call of the first turn has to be loaded
- // before any session exists, and the alternative — loading lazily on the
- // first event — would let that first call through while the file is read.
- crate::hooks::init(&cfg).await;
-
- // --- Turn-state recovery -------------------------------------------
- // Any per-thread turn snapshots left on disk from a previous process
- // are stale by definition — there is no live driver to resume them.
- // Stamp them as `Interrupted` so the UI can offer a retry without
- // confusing a stale `Streaming` lifecycle for an in-flight turn.
- {
- let now = chrono::Utc::now().to_rfc3339();
- match crate::threads::turn_state::store::mark_all_interrupted(workspace_dir.clone(), &now) {
- Ok(0) => {}
- Ok(count) => {
- log::info!("[runtime] marked {count} stale turn snapshot(s) as interrupted")
- }
- Err(err) => {
- log::warn!("[runtime] failed to mark stale turn snapshots interrupted: {err}")
- }
- }
- }
-
- // --- Run-ledger recovery -------------------------------------------
- // Detached sub-agent runs (`spawn_async_subagent`) from a previous process
- // are gone with that process. Any `agent_runs` row still marked `running`
- // at boot is orphaned — its driver died without firing a terminal event, so
- // the finalizer never settled it. Stamp such rows `interrupted` so they stop
- // rendering as perpetual "running" timeline entries on thread reopen.
- if agent_enabled {
- match tinyagents_session::run_ledger::interrupt_orphaned_agent_runs(&cfg.workspace_dir) {
- Ok(0) => {}
- Ok(count) => log::info!("[runtime] settled {count} orphaned agent run(s) on startup"),
- Err(err) => log::warn!("[runtime] failed to settle orphaned agent runs: {err}"),
- }
-
- // --- Detached sub-agent TaskStore reconciliation -------------------
- // The durable orchestration TaskStore (`<workspace>/.openhuman/
- // orchestration_tasks.jsonl`) can hold non-terminal sub-agent records left
- // by a previous process — their detached executor (abort handle +
- // cooperative CancellationToken) died with that process, so they cannot be
- // re-attached. Reconcile each orphan to a terminal state and emit the typed
- // terminal lifecycle event so the run ledger finalizes. Best-effort and
- // non-fatal (issue #4249 / 07.2 steps 2 & 4).
- let reconciled =
- crate::agent::orchestration::running_subagents::reconcile_orphaned_tasks_on_boot(
- &workspace_dir,
- );
- if reconciled > 0 {
- log::info!(
- "[runtime] reconciled {reconciled} orphaned detached sub-agent task(s) on startup"
- );
- }
- } else {
- log::debug!(
- "[boot] agent run-ledger + orchestration task reconciliation SKIPPED — Agent domain disabled"
- );
- }
-
- // --- Cost dashboard tracker ---
- // Activates the previously-dormant CostTracker so the dashboard RPC
- // surface (`openhuman.cost_get_dashboard`) and `record_provider_usage`
- // share one JSONL-backed store. Idempotent.
- crate::platform::cost::init_global(cfg.cost.clone(), &workspace_dir);
-
- // --- x402 payment ledger ---
- // Initializes the JSONL-backed spending ledger for machine-payable API
- // payments (x402 protocol). Budget defaults can be overridden via
- // the `openhuman.x402_update_budget` RPC. Gated on the Web3 domain (#4808
- // review): under `harness()`/`none()` the x402 controllers are absent, so
- // their ledger must not initialize either.
- if domains.allows(crate::core::all::DomainGroup::Web3) {
- let x402_session = format!("x402-{}", uuid::Uuid::new_v4());
- crate::web3::x402::init_ledger(&workspace_dir, &x402_session);
- } else {
- log::debug!("[boot] x402 payment ledger SKIPPED — Web3 domain disabled");
- }
-
- // --- Sub-agent definition registry bootstrap ---
- // Loads built-in archetype definitions plus any custom TOML files
- // under `<workspace>/agents/*.toml`. Idempotent — safe to call
- // multiple times. Uses the per-user scoped workspace_dir.
- if agent_enabled {
- if let Err(err) =
- crate::agent::harness::AgentDefinitionRegistry::init_global(&workspace_dir)
- {
- log::warn!(
- "[runtime] AgentDefinitionRegistry::init_global failed: {err} — \
- spawn_subagent will be unavailable until restart"
- );
- }
- } else {
- log::debug!("[boot] agent definition registry SKIPPED — Agent domain disabled");
- }
-
- // --- Agent sandbox + projects dirs ---
- // Create the action sandbox + default projects home and register the
- // projects dir as a ReadWrite trusted root BEFORE building the live policy
- // below (so the trusted root is reflected in `from_config`). This is the
- // always-run boot for web-chat-only desktop cores; without it a fresh
- // install with no messaging integrations leaves `~/OpenHuman/projects`
- // uncreated and every shell-tool `current_dir` fails with ERROR_DIRECTORY
- // (os error 267) on Windows / ENOENT on Unix (#3353, RC-A). Idempotent — a
- // later `start_channels` calls the same helper.
- crate::config::ensure_agent_dirs(&mut cfg).await;
-
- // --- Live SecurityPolicy ---
- // Install the process-global live policy on the always-run serve boot, not
- // only inside `start_channels` (which is skipped for web-chat-only cores
- // with no messaging integrations). Without this, `live_policy::current()`
- // would be empty on those cores, so the ApprovalGate's `auto_approve`
- // allowlist and `config.update_autonomy_settings` reloads (`reload_from`)
- // would be inert until a session with integrations starts. `from_config`
- // injects the default projects root, so this matches what `start_channels`
- // installs; idempotent — a later `start_channels` re-installs an equivalent
- // policy.
- let action_dir = cfg.action_dir.clone();
- crate::security::live_policy::install(
- std::sync::Arc::new(
- crate::security::SecurityPolicy::from_config(
- &cfg.autonomy,
- &workspace_dir,
- &action_dir,
- )
- .with_privacy_mode(cfg.privacy.mode),
- ),
- workspace_dir.clone(),
- action_dir,
- );
-
- // --- Triggered-workflow subscriber ---
- // Install on the always-run serve boot, not only inside `start_channels`
- // (skipped for web-chat-only cores with no messaging integrations, and when
- // `OPENHUMAN_DISABLE_CHANNEL_LISTENERS=1`). Without this, any workflow
- // declaring `triggers:` was silently ignored on web-chat-only desktop
- // installs. Idempotent — shares a process-global OnceLock with the
- // `start_channels` site so it registers exactly once regardless of which
- // path runs first. (Matching only for now; activation handoff still pending.)
- // Gated on the Skills domain (#4808 review): under `harness()`/`none()` the
- // skills controllers are absent, so their trigger subscriber must not install.
- if domains.allows(crate::core::all::DomainGroup::Skills) {
- crate::skills::bus::ensure_triggered_workflow_subscriber(&workspace_dir);
- } else {
- log::debug!("[boot] triggered-workflow subscriber SKIPPED — Skills domain disabled");
- }
-
- // --- Approval gate (#1339) ---
- // ON by default; opt out with `OPENHUMAN_APPROVAL_GATE=0` (or `false`).
- // Prompt-class `external_effect()` tool calls route through
- // `ApprovalGate::intercept` and park until the UI dispatches
- // `approval_decide` (or the 10-minute TTL elapses → deny). Safe to default
- // on now that the release surface exists (ApprovalRequestCard + the Agent
- // OS access panel) AND only *interactive chat* turns park — background /
- // triage / cron turns carry no chat context and pass straight through, so
- // autonomous automation is never blocked.
- //
- // Host-aware override evaluation: under the Tauri desktop shell the env
- // override is treated as advisory only — the gate ALWAYS installs and a
- // `DomainEvent::ApprovalGateOverrideIgnored` is published so the UI can
- // surface a one-shot banner explaining the override was rejected. Under
- // standalone CLI / Docker (env-as-config is the operator's chosen
- // surface) the override is honored, but a `DomainEvent::ApprovalGateDisabled`
- // is still published so any connected dashboard / log shipper can
- // surface the elevated-privilege state.
- let env_override_requested = std::env::var("OPENHUMAN_APPROVAL_GATE")
- .map(|v| {
- let t = v.trim();
- t == "0" || t.eq_ignore_ascii_case("false")
- })
- .unwrap_or(false);
- let decision =
- crate::core::types::approval_gate_boot_decision(host_kind, env_override_requested);
- // Record the boot decision before publishing the warning event so the
- // first poll of `approval_get_gate_state` after boot reflects the same
- // host-aware verdict the event itself describes — no race.
- crate::security::approval::gate::record_boot_state(
- crate::security::approval::gate::ApprovalGateBootState {
- installed: decision.install_gate,
- disabled_by_env: decision.gate_disabled_by_override,
- override_ignored: decision.override_ignored,
- host: match host_kind {
- crate::core::types::HostKind::TauriShell => "tauri-shell",
- crate::core::types::HostKind::Cli => "cli",
- crate::core::types::HostKind::Docker => "docker",
- crate::core::types::HostKind::Library => "library",
- },
- },
- );
- if decision.override_ignored {
- log::warn!(
- "[runtime] OPENHUMAN_APPROVAL_GATE=0 IGNORED under desktop shell — \
- gate is always on for the Tauri host (host={})",
- host_kind.tag()
- );
- crate::core::bus::BUS.publish(
- crate::core::events::DomainEvent::ApprovalGateOverrideIgnored {
- host: host_kind.tag().to_string(),
- },
- );
- }
- // Bridge interactive web-surface events to the frontend: ApprovalRequested →
- // `approval_request` AND PlanReviewRequested → `plan_review_request` (both
- // handled by the same subscriber). Registered UNCONDITIONALLY here on the
- // always-run serve boot — the plan-review gate is independent of the approval
- // gate and parks turns even when `OPENHUMAN_APPROVAL_GATE=0`, while
- // `start_channels` is skipped for web-chat-only cores. Without this an
- // unguarded standalone/CLI/Docker core would park a plan review that never
- // reaches the UI and dies at the gate TTL. Idempotent (Once-guarded).
- crate::web_chat::register_approval_surface_subscriber();
- // Egress-surface bridge (privacy epic S2, #4436) — registered
- // unconditionally alongside the approval surface so external-transfer
- // disclosures reach the UI even on cores that skip `start_channels` or run
- // with the approval gate disabled. Idempotent (OnceLock-guarded).
- crate::web_chat::register_egress_surface_subscriber();
- // Agent-surface bridge (goals/todos/queue, C3) — registered unconditionally
- // for the same reason as the two bridges above: this JSON-RPC serve boot
- // path can run without `start_channels`. Idempotent (OnceLock-guarded).
- crate::web_chat::register_agent_surface_subscriber();
-
- if decision.install_gate {
- // Per-launch correlation token for the approval gate. This is
- // a fresh UUID every boot — it is NOT derived from the
- // JSON-RPC bearer (`OPENHUMAN_CORE_TOKEN` / the in-memory
- // auth subsystem) and carries no credential material, so it
- // is safe to log, persist, and surface in audit events.
- // `approval_list_pending` is session-agnostic so pending rows
- // from prior launches remain visible after restart; only the
- // per-session audit grouping changes across launches.
- let session_id = format!("session-{}", uuid::Uuid::new_v4());
- let _ =
- crate::security::approval::ApprovalGate::init_global(cfg.clone(), session_id.clone());
- log::info!(
- "[runtime] approval gate installed (on by default; set OPENHUMAN_APPROVAL_GATE=0 to disable, session_id={session_id}) — \
- Prompt-class external-effect tool calls park for approval in interactive chat turns"
- );
- // (The approval/plan-review surface bridge is registered unconditionally
- // above — it must run even when this gate-install branch is skipped.)
- crate::web_chat::register_artifact_surface_subscriber();
- } else {
- log::info!(
- "[runtime] approval gate DISABLED (OPENHUMAN_APPROVAL_GATE=0 honored on host={}) — \
- Prompt-class external-effect tool calls run unprompted",
- host_kind.tag()
- );
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ApprovalGateDisabled {
- host: host_kind.tag().to_string(),
- reason: "env-override".to_string(),
- });
- }
- // Artifact surface bridges DomainEvent::ArtifactReady/Failed onto the web
- // channel ("Files in this chat" panel + ArtifactCard updates). This is
- // independent of the approval-gate config — keep it outside the
- // `if approval_gate` block so artifact events still publish when the user
- // sets OPENHUMAN_APPROVAL_GATE=0 (CR #3328947323 on PR #3026). Idempotent
- // (OnceLock-guarded inside register_artifact_surface_subscriber).
- crate::web_chat::register_artifact_surface_subscriber();
- // Memory-activity surface bridges DomainEvent::MemoryStored/Recalled onto
- // the web channel's `memory_activity` event (C5) — same unconditional
- // placement rationale as the bridges above. Idempotent (OnceLock-guarded).
- crate::web_chat::register_memory_activity_surface_subscriber();
-
- // --- Workspace migrations --------------------------------------------
- crate::platform::startup::run_workspace_migrations(&workspace_dir);
-
- // --- Socket manager bootstrap ---
- let socket_mgr = Arc::new(SocketManager::new());
- set_global_socket_manager(socket_mgr.clone());
- log::info!("[socket] SocketManager initialized and registered globally");
-}
-
-/// Starts selected background jobs after the runtime has entered `serve()`.
-///
-/// This deliberately sits outside [`bootstrap_core_runtime`]: embedders may call
-/// `CoreBuilder::build()` only to use in-process RPC, and a failed listener bind
-/// must not leave pollers, one-shot jobs, MCP processes, or socket reconnect work
-/// running without a live runtime.
-pub async fn start_core_runtime_services(
- services: crate::core::runtime::ServiceSet,
- config: Option<&crate::config::Config>,
-) {
- let Some(cfg) = config else {
- log::error!(
- "[runtime] Config unavailable for runtime service startup; selected services skipped"
- );
- return;
- };
-
- // Long-lived bootstrap loops selected by ServiceSet.
- // One-time first-run initialization (managed Python runtime, spaCy model,
- // managed Node runtime). Spawned AFTER subscribers are live but does NOT
- // block the ready signal — the core becomes RPC-ready immediately and the
- // frontend watches per-step progress via `openhuman.harness_init_status`.
- // On a warm host every step's `is_done` probe passes and this settles
- // instantly. See `crate::agent::harness_init`.
- crate::core::runtime::services::start_boot_once_jobs(services, cfg).await;
-
- // Long-lived bootstrap loops selected by ServiceSet. These start only
- // after the boot-once jobs above have completed.
- crate::core::runtime::services::start_bootstrap_jobs(services, cfg);
-
- match crate::platform::socket::global_socket_manager() {
- Some(socket_mgr) => {
- crate::core::runtime::services::spawn_socket_auto_connect(services, socket_mgr.clone());
- }
- None => {
- log::warn!(
- "[socket] SocketManager unavailable during runtime service startup; auto-connect skipped"
- );
- }
- }
-}
-
-/// JSON-serializable wrapper for the entire RPC schema dump.
-#[cfg(feature = "http-server")]
-#[derive(Serialize)]
-struct HttpSchemaDump {
- /// List of all available RPC methods and their schemas.
- methods: Vec<HttpMethodSchema>,
-}
-
-/// JSON-serializable schema for a single RPC method.
-#[cfg(feature = "http-server")]
-#[derive(Serialize)]
-struct HttpMethodSchema {
- /// Fully qualified JSON-RPC method name.
- method: String,
- /// Namespace of the function.
- namespace: String,
- /// Function name within the namespace.
- function: String,
- /// Human-readable description of what the method does.
- description: String,
- /// List of input parameters.
- inputs: Vec<crate::core::FieldSchema>,
- /// List of output fields.
- outputs: Vec<crate::core::FieldSchema>,
-}
-
-/// Aggregates schemas from all registered controllers into a single dump.
-///
-/// Also includes built-in core methods like `core.ping` and `core.version`.
-#[cfg(feature = "http-server")]
-fn build_http_schema_dump() -> HttpSchemaDump {
- let mut methods: Vec<HttpMethodSchema> = all::all_http_method_schemas()
- .into_iter()
- .map(|method| HttpMethodSchema {
- method: method.method,
- namespace: method.namespace.to_string(),
- function: method.function.to_string(),
- description: method.description.to_string(),
- inputs: method.inputs,
- outputs: method.outputs,
- })
- .collect();
-
- // Sort methods alphabetically for consistent output.
- methods.sort_by(|a, b| a.method.cmp(&b.method));
-
- HttpSchemaDump { methods }
-}
-
-#[cfg(test)]
-#[path = "jsonrpc_tests.rs"]
-mod tests;
-
-// Every cors test names a gated CORS symbol (`is_origin_allowed`,
-// `with_cors_headers`), so the whole module gates in lockstep (#5048).
-#[cfg(all(test, feature = "http-server"))]
-#[path = "jsonrpc_cors_tests.rs"]
-mod cors_tests;
diff --git a/crates/openhuman-core/src/core/jsonrpc_tests.rs b/crates/openhuman-core/src/core/jsonrpc_tests.rs
deleted file mode 100644
index 42c9ec37a3..0000000000
--- a/crates/openhuman-core/src/core/jsonrpc_tests.rs
+++ /dev/null
@@ -1,1510 +0,0 @@
-use serde_json::json;
-use std::ffi::OsString;
-#[cfg(all(feature = "crash-reporting", feature = "http-server"))]
-use std::sync::Arc;
-use std::sync::MutexGuard;
-use std::time::Duration;
-use tokio_util::sync::CancellationToken;
-
-use super::{
- apply_e2e_tool_groups, default_state, group_first_time_when_bus_ready, invoke_method,
- is_session_expired_error, is_unconfirmed_unauthorized_error,
- learning_first_time_when_bus_ready, params_to_object, parse_json_params,
- should_publish_session_expired, translate_local_session_error, type_name, DomainSubscriberPlan,
-};
-
-#[test]
-fn e2e_environment_enables_advertised_tool_groups() {
- let _guard = EnvVarGuard::set_many(vec![("OPENHUMAN_E2E", "1".into())]);
- let builder = crate::core::runtime::CoreBuilder::new(crate::core::types::HostKind::Cli);
- let _ = apply_e2e_tool_groups(builder);
-}
-// These are the `http-server`-gated RPC-surface symbols (#5048); the tests that
-// name them below carry the same `#[cfg]` so the disabled-build test compile
-// (`cargo test --no-default-features`) stays green.
-#[cfg(feature = "http-server")]
-use super::{
- build_http_schema_dump, escape_html, is_param_validation_error, is_wallet_not_configured_error,
- rpc_handler,
-};
-
-// ---- domain-subscriber gating (#4796 DoD item 3) ----------------------------
-// `register_domain_subscribers` registers on the process-global event bus behind
-// a `Once`, so its gating is proven via the pure `DomainSubscriberPlan` the
-// registrar consumes — no real subscribers, no bus mutation.
-
-#[test]
-fn domain_subscriber_plan_full_registers_every_gated_subscriber() {
- let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::full());
- assert_eq!(
- plan,
- DomainSubscriberPlan {
- platform: true,
- integrations: true,
- security: true,
- desktop: true,
- skills: true,
- channels: true,
- flows: true,
- memory: true,
- agent: true,
- hosted: true,
- mcp: true,
- },
- "full() must register every gated domain subscriber"
- );
-}
-
-#[test]
-fn domain_subscriber_plan_none_registers_no_gated_subscriber() {
- let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::none());
- assert_eq!(
- plan,
- DomainSubscriberPlan {
- platform: false,
- integrations: false,
- security: false,
- desktop: false,
- skills: false,
- channels: false,
- flows: false,
- memory: false,
- agent: false,
- hosted: false,
- mcp: false,
- },
- "none() must register no gated domain subscriber (core infra still runs, ungated)"
- );
-}
-
-#[test]
-fn domain_subscriber_plan_harness_gates_by_owning_group() {
- let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::harness());
- // harness() = agent + memory + threads + config + security.
- assert!(plan.agent, "harness keeps agent subscribers");
- assert!(
- plan.memory,
- "harness keeps memory conversation-persistence + sync bridge"
- );
- // Platform / Channels / Flows / Meet / Mcp are NOT in harness.
- assert!(
- !plan.platform,
- "harness must skip webhook/notification/composio/task-sources/device-tunnel"
- );
- assert!(
- !plan.channels,
- "harness must skip channel-inbound + web-only proactive"
- );
- assert!(!plan.flows, "harness must skip flows trigger dispatch");
- assert!(
- !plan.hosted,
- "harness must skip hosted orchestration ingest"
- );
- assert!(!plan.mcp, "harness must skip mcp_registry bus init");
-}
-
-#[test]
-fn domain_subscriber_registration_retries_after_bus_becomes_ready() {
- use crate::core::all::DomainGroup;
- use std::collections::HashSet;
- use std::sync::Mutex;
-
- let completed = Mutex::new(HashSet::new());
-
- assert!(!group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Flows,
- false,
- ));
- assert!(
- completed.lock().expect("registry lock").is_empty(),
- "a deferred attempt must not mark the group complete"
- );
-
- assert!(group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Flows,
- true,
- ));
- assert!(
- completed
- .lock()
- .expect("registry lock")
- .contains(&DomainGroup::Flows),
- "the ready retry must mark the group complete"
- );
-}
-
-#[test]
-fn domain_subscriber_registration_is_idempotent_after_success() {
- use crate::core::all::DomainGroup;
- use std::collections::HashSet;
- use std::sync::Mutex;
-
- let completed = Mutex::new(HashSet::new());
-
- assert!(group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Channels,
- true,
- ));
- assert!(!group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Channels,
- true,
- ));
- assert_eq!(
- completed.lock().expect("registry lock").len(),
- 1,
- "a completed group must be recorded exactly once"
- );
-}
-
-#[test]
-fn learning_subscriber_registration_retries_after_bus_becomes_ready() {
- let completed = std::sync::Mutex::new(false);
-
- assert!(!learning_first_time_when_bus_ready(&completed, false));
- assert!(
- !*completed.lock().expect("registry lock"),
- "a deferred learning attempt must not consume its token"
- );
-
- assert!(learning_first_time_when_bus_ready(&completed, true));
- assert!(
- *completed.lock().expect("registry lock"),
- "the ready retry must consume the learning token"
- );
-}
-
-#[test]
-fn learning_subscriber_registration_is_idempotent_after_success() {
- let completed = std::sync::Mutex::new(false);
-
- assert!(learning_first_time_when_bus_ready(&completed, true));
- assert!(!learning_first_time_when_bus_ready(&completed, true));
-}
-
-#[test]
-fn domain_subscriber_registration_readiness_helper_is_idempotent() {
- use crate::core::all::DomainGroup;
- use std::collections::HashSet;
- use std::sync::Mutex;
-
- let completed = Mutex::new(HashSet::new());
- assert!(group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Media,
- true
- ));
- assert!(!group_first_time_when_bus_ready(
- &completed,
- DomainGroup::Media,
- true
- ));
-}
-/// #5027 — the tool-execution timeout must be seeded on the always-on core boot
-/// path (`register_domain_subscribers`), NOT inside
-/// `channels::runtime::startup::start_channels`, which is skipped for
-/// channel-less / web-chat-only cores (and when `OPENHUMAN_DISABLE_CHANNEL_LISTENERS`
-/// is set). A minimal `DomainSet::none()` must still seed, because the seed is
-/// DomainSet-independent.
-///
-/// The seed sits just *before* the ungated `INFRA: Once` block, so it re-runs on
-/// every `register_domain_subscribers` call (each `bootstrap_core_runtime`),
-/// re-applying the freshly reloaded config on an in-process restart — a seed gated
-/// by the process-global `Once` would only fire on the first boot. `TEST_ENV_LOCK`
-/// (via `EnvVarGuard`) serializes with `OPENHUMAN_TOOL_TIMEOUT_SECS` cleared so the
-/// operator env override cannot mask the config-derived value. Runs under a tokio
-/// runtime like the real boot paths — the INFRA block calls `subscribe_global`,
-/// which `tokio::spawn`s when the global bus is already initialized by another test
-/// in the binary.
-#[tokio::test]
-async fn tool_timeout_seeds_on_channelless_core_boot() {
- // Clear the operator override behind a panic-safe RAII guard: if any assertion
- // below panics, `Drop` still restores the previous value, so sibling tests that
- // share `TEST_ENV_LOCK` never inherit the cleared var.
- let _env = EnvVarGuard::remove_many(vec!["OPENHUMAN_TOOL_TIMEOUT_SECS"]);
-
- // Distinctive, in-range (1..=3600) value so the assertion can only pass on a
- // real seed, never on the default. Channel-less: `channels_config` stays empty,
- // which is exactly the config for which `start_channels` is skipped.
- let mut config = crate::config::Config::default();
- config.agent.agent_timeout_secs = 1234;
- assert!(
- config.channels_config.active_channel.is_none(),
- "test premise: channel-less config, so start_channels would be skipped"
- );
-
- let tmp = tempfile::tempdir().expect("tempdir");
- // Minimal DomainSet — INFRA (and thus the timeout seed) is DomainSet-independent,
- // so even `none()` must seed. `embedded_core = true` skips the standalone
- // process-exit shutdown subscriber.
- super::register_domain_subscribers(
- tmp.path().to_path_buf(),
- config,
- true,
- crate::core::runtime::DomainSet::none(),
- );
-
- assert_eq!(
- crate::tools::timeout::tool_execution_timeout_secs(),
- 1234,
- "channel-less core boot must seed the tool-execution timeout from [agent].agent_timeout_secs"
- );
-}
-
-struct EnvVarGuard {
- old_values: Vec<(&'static str, Option<OsString>)>,
- _lock: MutexGuard<'static, ()>,
-}
-
-impl EnvVarGuard {
- fn set_many(vars: Vec<(&'static str, OsString)>) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .expect("test env lock poisoned");
- let mut old_values = Vec::with_capacity(vars.len());
- for (key, value) in vars {
- let old = std::env::var_os(key);
- std::env::set_var(key, value);
- old_values.push((key, old));
- }
- Self {
- old_values,
- _lock: lock,
- }
- }
-
- /// Remove the named vars (capturing their prior values) for the guard's
- /// lifetime, restoring each on `Drop`. Mirrors [`set_many`] for tests that
- /// need an env var *absent* rather than set to a fixed value.
- fn remove_many(keys: Vec<&'static str>) -> Self {
- let lock = crate::config::TEST_ENV_LOCK
- .lock()
- .expect("test env lock poisoned");
- let mut old_values = Vec::with_capacity(keys.len());
- for key in keys {
- let old = std::env::var_os(key);
- std::env::remove_var(key);
- old_values.push((key, old));
- }
- Self {
- old_values,
- _lock: lock,
- }
- }
-}
-
-impl Drop for EnvVarGuard {
- fn drop(&mut self) {
- for (key, old) in self.old_values.iter().rev() {
- match old {
- Some(value) => std::env::set_var(key, value),
- None => std::env::remove_var(key),
- }
- }
- }
-}
-
-async fn wait_until_port_accepts(port: u16) {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
- loop {
- if tokio::net::TcpStream::connect(("127.0.0.1", port))
- .await
- .is_ok()
- {
- return;
- }
- assert!(
- tokio::time::Instant::now() < deadline,
- "server did not start accepting on port {port}"
- );
- tokio::time::sleep(Duration::from_millis(25)).await;
- }
-}
-
-async fn wait_until_port_released(port: u16) {
- let deadline = tokio::time::Instant::now() + Duration::from_secs(2);
- loop {
- if tokio::net::TcpStream::connect(("127.0.0.1", port))
- .await
- .is_err()
- {
- return;
- }
- assert!(
- tokio::time::Instant::now() < deadline,
- "server did not release port {port}"
- );
- tokio::time::sleep(Duration::from_millis(25)).await;
- }
-}
-
-/// Regression test for issue #920 — the embedded server's `axum::serve`
-/// accept loop must stop within the cancellation timeout when its
-/// `CancellationToken` is fired.
-///
-/// **Ignored by default.** This test calls `run_server_embedded`,
-/// which triggers the full production bootstrap (`bootstrap_core_runtime`
-/// → `register_domain_subscribers` → `scheduler_gate::init_global` +
-/// `memory::tree::jobs::start` + `composio::start_periodic_sync` +
-/// cron scheduler). Those code paths spawn detached `tokio::spawn`
-/// background tasks and write to several process-global statics
-/// (`STATE: OnceLock`, `SIGNED_OUT: AtomicBool`, `LLM_PERMITS`
-/// semaphore, `GLOBAL_REGISTRY` agent.run_turn handler, `STARTED`
-/// `std::sync::Once`s, …) — *none of which have teardown semantics*.
-/// In a unit-test binary the leaked tasks then race with every other
-/// test, multiplying CI wall time by 10–20× (PR #1552 thread). The
-/// right shape for this regression is an integration test in a
-/// dedicated `tests/` binary where global pollution doesn't affect
-/// siblings — tracked as a follow-up.
-///
-/// To run manually: `cargo test --lib -p openhuman -- --ignored
-/// shutdown_token`.
-#[tokio::test]
-#[ignore = "calls full server bootstrap; leaks process-global state into sibling tests (#1552). Re-cover via integration test."]
-async fn shutdown_token_stops_axum_listener_within_timeout() {
- let _signed_out_restore = crate::cron::scheduler_gate::SignedOutTestGuard::set(false);
-
- let workspace = tempfile::tempdir().expect("workspace tempdir");
-
- // Pin scheduler-gate policy to Aggressive while this test runs so
- // the bootstrap's `init_global` snapshot can't capture transient
- // CPU pressure and freeze the cached policy at Paused.
- std::fs::write(
- workspace.path().join("config.toml"),
- "[scheduler_gate]\nmode = \"always_on\"\n",
- )
- .expect("seed scheduler_gate=always_on config.toml");
- let _env = EnvVarGuard::set_many(vec![
- (
- "OPENHUMAN_WORKSPACE",
- workspace.path().as_os_str().to_os_string(),
- ),
- ("OPENHUMAN_DISABLE_CHANNEL_LISTENERS", OsString::from("1")),
- (
- "OPENHUMAN_CORE_TOKEN",
- OsString::from("test-token-shutdown"),
- ),
- ]);
-
- let probe = std::net::TcpListener::bind("127.0.0.1:0").expect("allocate test port");
- let port = probe.local_addr().expect("local addr").port();
- drop(probe);
-
- let shutdown_token = CancellationToken::new();
- let server_token = shutdown_token.clone();
- let server = tokio::spawn(async move {
- super::run_server_embedded(Some("127.0.0.1"), Some(port), false, server_token).await
- });
-
- wait_until_port_accepts(port).await;
- shutdown_token.cancel();
-
- let result = tokio::time::timeout(Duration::from_secs(2), server)
- .await
- .expect("embedded server task should stop within timeout")
- .expect("embedded server task should not panic");
- result.expect("embedded server should shut down cleanly");
- wait_until_port_released(port).await;
-}
-
-#[tokio::test]
-async fn invoke_health_snapshot_via_registry() {
- let result = invoke_method(default_state(), "openhuman.health_snapshot", json!({}))
- .await
- .expect("health snapshot should succeed");
- assert!(result.get("result").is_some());
-}
-
-#[tokio::test]
-async fn invoke_encrypt_secret_missing_required_param_fails_validation() {
- let err = invoke_method(default_state(), "openhuman.encrypt_secret", json!({}))
- .await
- .expect_err("missing plaintext should fail");
- assert!(err.contains("missing required param 'plaintext'"));
-}
-
-#[tokio::test]
-async fn invoke_doctor_models_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.doctor_models",
- json!({ "invalid": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'invalid'"));
-}
-
-// Uses a `flows.*` method as its gated-family vehicle: without the `flows`
-// feature there is no flows controller in the registry and the `.expect()`
-// below would panic. The transport-layer gating it proves is orthogonal to the
-// compile-time gate (#4797).
-#[cfg(feature = "flows")]
-#[tokio::test]
-async fn gated_method_is_unknown_at_transport_even_with_malformed_params() {
- // #4808 review (CodeRabbit): prove the schema-gate fix at the JSON-RPC
- // TRANSPORT layer (`invoke_method`), not only via direct dispatch. Under a
- // harness() ambient context a gated method must return an unknown-method
- // error for BOTH well-formed and malformed params — never the controller's
- // param-validation error, which would leak that the hidden method exists.
- use crate::core::runtime::context::CoreContext;
- use crate::core::runtime::DomainSet;
-
- let gated_method = crate::core::all::all_registered_controllers()
- .into_iter()
- .find(|c| c.schema.namespace == "flows")
- .map(|c| c.rpc_method_name())
- .expect("a flows.* method exists in the full registry");
-
- for params in [json!({}), json!({ "obviously_not_a_real_param_xyz": true })] {
- let ctx = CoreContext::for_test(DomainSet::harness(), None, None);
- let err = CoreContext::scope(
- ctx,
- invoke_method(default_state(), &gated_method, params.clone()),
- )
- .await
- .expect_err("gated flows method must error under harness()");
- assert!(
- err.contains("unknown method"),
- "gated `{gated_method}` with params {params} must be unknown-method at transport, got: {err}"
- );
- assert!(
- !err.contains("param"),
- "gated `{gated_method}` must NOT leak a param-validation error (surface leak), got: {err}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_config_get_runtime_flags_via_registry() {
- let result = invoke_method(
- default_state(),
- "openhuman.config_get_runtime_flags",
- json!({}),
- )
- .await
- .expect("runtime flags should succeed");
- assert!(result.get("result").is_some());
-}
-
-#[tokio::test]
-async fn invoke_auth_store_session_missing_token_fails_validation() {
- let err = invoke_method(default_state(), "openhuman.auth_store_session", json!({}))
- .await
- .expect_err("missing token should fail");
- assert!(err.contains("missing required param 'token'"));
-}
-
-#[tokio::test]
-async fn invoke_service_status_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.service_status",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[tokio::test]
-async fn invoke_memory_init_accepts_empty_params() {
- // jwt_token is optional (accepted for backward compat but ignored).
- // The call may still fail for workspace reasons in test, but must NOT
- // fail with a missing-param error for jwt_token.
- let result = invoke_method(default_state(), "openhuman.memory_init", json!({})).await;
- if let Err(ref e) = result {
- assert!(
- !e.contains("missing required param") || !e.contains("jwt_token"),
- "jwt_token should be optional, got: {e}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_memory_list_namespaces_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_list_namespaces",
- json!({ "extra": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("extra"));
-}
-
-#[tokio::test]
-async fn invoke_memory_query_namespace_missing_namespace_fails() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_query_namespace",
- json!({ "query": "who owns atlas" }),
- )
- .await
- .expect_err("missing namespace should fail");
- assert!(err.contains("namespace"));
-}
-
-#[tokio::test]
-async fn invoke_memory_recall_memories_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.memory_recall_memories",
- json!({ "namespace": "team", "extra": true }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("extra"));
-}
-
-#[tokio::test]
-async fn invoke_migrate_openclaw_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.migrate_openclaw",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[tokio::test]
-async fn invoke_migrate_hermes_rejects_unknown_param() {
- let err = invoke_method(
- default_state(),
- "openhuman.migrate_hermes",
- json!({ "x": 1 }),
- )
- .await
- .expect_err("unknown param should fail");
- assert!(err.contains("unknown param 'x'"));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn http_schema_dump_includes_openhuman_and_core_methods() {
- let dump = build_http_schema_dump();
- let methods = dump.methods;
- assert!(
- methods
- .iter()
- .any(|m| m.method == "core.version" && m.namespace == "core"),
- "schema dump should include core methods"
- );
-
- assert!(
- methods
- .iter()
- .any(|m| m.method == "openhuman.health_snapshot"),
- "schema dump should include migrated openhuman methods"
- );
-}
-
-// --- helper coverage -----------------------------------------------------
-
-#[test]
-fn params_to_object_accepts_object() {
- let map = params_to_object(json!({"a": 1, "b": "x"})).unwrap();
- assert_eq!(map.len(), 2);
- assert_eq!(map.get("a"), Some(&json!(1)));
-}
-
-#[test]
-fn params_to_object_accepts_null_as_empty_map() {
- let map = params_to_object(json!(null)).unwrap();
- assert!(map.is_empty());
-}
-
-#[test]
-fn params_to_object_rejects_array() {
- let err = params_to_object(json!([1, 2, 3])).unwrap_err();
- assert!(err.contains("invalid params"));
- assert!(err.contains("array"));
-}
-
-#[test]
-fn params_to_object_rejects_scalars() {
- assert!(params_to_object(json!(42)).unwrap_err().contains("number"));
- assert!(params_to_object(json!("hi"))
- .unwrap_err()
- .contains("string"));
- assert!(params_to_object(json!(true)).unwrap_err().contains("bool"));
-}
-
-#[test]
-fn type_name_labels_every_json_variant() {
- assert_eq!(type_name(&json!(null)), "null");
- assert_eq!(type_name(&json!(true)), "bool");
- assert_eq!(type_name(&json!(3)), "number");
- assert_eq!(type_name(&json!("s")), "string");
- assert_eq!(type_name(&json!([])), "array");
- assert_eq!(type_name(&json!({})), "object");
-}
-
-#[test]
-fn parse_json_params_roundtrips_object() {
- let v = parse_json_params(r#"{"k":1}"#).unwrap();
- assert_eq!(v, json!({"k": 1}));
-}
-
-#[test]
-fn parse_json_params_reports_error_message() {
- let err = parse_json_params("{not json").unwrap_err();
- assert!(err.contains("invalid JSON params"));
-}
-
-#[test]
-fn is_session_expired_error_matches_backend_path_401() {
- // Issue #2286: only OpenHuman backend path 401s (HTTP-method prefix) should
- // match, not generic 401/Unauthorized strings.
- assert!(is_session_expired_error(
- "GET /teams failed (401 Unauthorized): {\"success\":false}"
- ));
- assert!(is_session_expired_error(
- "POST /auth/token failed (401 Unauthorized): session expired"
- ));
- assert!(is_session_expired_error(
- "DELETE /sessions/abc failed (401 Unauthorized): unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_flattened_backend_unauthorized() {
- // #3297: after #2781 the backend 401 is a typed `BackendApiError::Unauthorized`
- // that team/billing ops flatten via `api::flatten_authed_error`. The dispatcher
- // classifier MUST recognise that flattened string as session expiry, so the
- // 401 is suppressed from Sentry (TAURI-RUST-8WY on `/teams/me/usage`,
- // TAURI-RUST-8WZ on `/payments/stripe/currentPlan`) AND triggers the
- // `SessionExpired` publish. End-to-end: build the typed error → flatten → classify.
- let flat = crate::backend::flatten_authed_error(anyhow::Error::new(
- crate::backend::BackendApiError::Unauthorized {
- method: "GET".to_string(),
- path: "/teams/me/usage".to_string(),
- },
- ));
- assert!(
- is_session_expired_error(&flat),
- "flattened backend Unauthorized must classify as session expiry: {flat}"
- );
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_generic_401_unauthorized() {
- // Generic 401+unauthorized strings without HTTP-method prefix must NOT match.
- assert!(!is_session_expired_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(!is_session_expired_error("401 UNAUTHORIZED"));
- assert!(!is_session_expired_error("got 401 and unauthorized body"));
-}
-
-#[test]
-fn unconfirmed_unauthorized_error_matches_generic_401_for_diagnostics_only() {
- // Generic 401+unauthorized text feeds the diagnostic-only branch — never
- // SessionExpired publication.
- assert!(is_unconfirmed_unauthorized_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(is_unconfirmed_unauthorized_error("401 UNAUTHORIZED"));
- assert!(is_unconfirmed_unauthorized_error(
- "got 401 and unauthorized body"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_partial_auth_text() {
- // 401 alone is not sufficient — could be HTTP/3.01 nonsense or
- // unrelated text. We require the string "unauthorized" too, plus an
- // HTTP-method prefix for the 401 path.
- assert!(!is_session_expired_error("server returned 401"));
- assert!(!is_session_expired_error("unauthorized without code"));
-}
-
-#[test]
-fn is_session_expired_error_matches_openhuman_backend_path_401() {
- // OpenHuman backend calls via authed_json use the format:
- // "{METHOD} /path failed (401 Unauthorized): {body}"
- assert!(is_session_expired_error(
- "GET /teams failed (401 Unauthorized): {\"success\":false}"
- ));
- assert!(is_session_expired_error(
- "POST /auth/token failed (401 Unauthorized): session expired"
- ));
- assert!(is_session_expired_error(
- "GET /teams/me/usage failed (401 Unauthorized): unauthorized"
- ));
- assert!(is_session_expired_error(
- "PUT /profile failed (401 Unauthorized): token expired"
- ));
- assert!(is_session_expired_error(
- "PATCH /settings failed (401 Unauthorized): unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_discord_api_error() {
- // Issue #2286: Discord bot token 401 must not clear the user session.
- assert!(!is_session_expired_error(
- "Discord API error: Discord list guilds failed (401): Unauthorized"
- ));
- assert!(!is_session_expired_error(
- "Discord API error: Discord get bot user failed (401): bad token"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_byo_key_provider_401() {
- // BYO-key provider 401 should not clear the user session.
- assert!(!is_session_expired_error(
- "OpenAI API error (401 Unauthorized): invalid api key"
- ));
- assert!(!is_session_expired_error(
- "Anthropic API error (401 Unauthorized): authentication error"
- ));
- assert!(!is_session_expired_error(
- "Composio v3 API error: HTTP 401: Unauthorized"
- ));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_backend_wrapped_composio_invalid_api_key() {
- // Issue #2537: the backend can return a 500 whose body wraps a Composio
- // upstream 401. That is a scoped integration/service failure, not proof
- // that the user's OpenHuman app session expired.
- let msg = r#"[composio] list_connections failed: Backend returned 500 Internal Server Error for GET https://api.tinyhumans.ai/agent-integrations/composio/connections: 401 {"error":{"message":"Invalid API key: ak_o1Og5*****","code":10401,"slug":"HTTP_Unauthorized","status":401}}"#;
-
- assert!(
- !is_session_expired_error(msg),
- "Composio upstream 401 wrapped by the backend must not publish SessionExpired"
- );
- assert!(
- is_unconfirmed_unauthorized_error(msg),
- "auth-looking upstream failures should still be logged diagnostically"
- );
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_invalid_token_case_insensitive() {
- // "invalid token" is no longer a session-expiry trigger (issue #2286):
- // it was too broad and caught Discord/OAuth provider token errors. It is
- // still surfaced via the diagnostic-only `is_unconfirmed_unauthorized_error`.
- assert!(!is_session_expired_error("Invalid Token"));
- assert!(!is_session_expired_error("got an invalid token here"));
- assert!(is_unconfirmed_unauthorized_error("Invalid Token"));
- assert!(is_unconfirmed_unauthorized_error(
- "got an invalid token here"
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_openhuman_session_expired_body() {
- // Even without an HTTP-method prefix, an explicit "Session expired" body
- // text triggers session expiry via the shared observability classifier.
- assert!(is_session_expired_error(
- r#"OpenHuman API error (401 Unauthorized): {"success":false,"error":"Session expired. Please log in again."}"#
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_session_expired_sentinel() {
- // The SESSION_EXPIRED sentinel is case-sensitive by design.
- assert!(is_session_expired_error("SESSION_EXPIRED: please re-auth"));
- assert!(!is_session_expired_error("session_expired lowercase"));
-}
-
-#[test]
-fn is_session_expired_error_does_not_match_unrelated_errors() {
- assert!(!is_session_expired_error("network timeout"));
- assert!(!is_session_expired_error("500 internal server error"));
- assert!(!is_session_expired_error(""));
-}
-
-#[test]
-fn is_session_expired_error_skips_discord_rewrap_for_2285() {
- // Cross-module regression guard for #2285: the Discord domain
- // controller intentionally formats its upstream-auth failures so
- // they do NOT match this dispatch-time classifier. If anyone
- // changes the wording on either side back into a string that
- // contains both "401" and "unauthorized", a connected-Discord
- // card click would once again log the user out of OpenHuman.
- //
- // We pin the exact substrings the Discord rewrap was designed
- // to avoid, plus the canonical post-rewrap message body, so
- // either-side drift fails loudly.
- let canonical_rewrap = "Discord API error: Discord list_guilds: bot token was rejected \
- (upstream HTTP four-oh-one). Open Connections → Channels → Discord \
- and rotate / reconnect the bot token.";
- assert!(
- !is_session_expired_error(canonical_rewrap),
- "Discord rewrap must NOT trip the session-expired classifier: {canonical_rewrap}"
- );
- // Defensive: also pin the 403 variant. Same rewrap path, same
- // requirement — neither '403' nor 'forbidden' is part of the
- // session classifier today, but locking the message in keeps a
- // future regression visible.
- let canonical_rewrap_403 =
- "Discord API error: Discord list_channels: bot token lacks required Discord permissions \
- (upstream HTTP four-oh-three). Open Connections → Channels → Discord \
- and rotate / reconnect the bot token.";
- assert!(!is_session_expired_error(canonical_rewrap_403));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_param_validation_error_matches_the_three_validator_shapes() {
- // Regression guard for OPENHUMAN-TAURI-20: pre-#1467 cores rejected
- // `api_key` because it wasn't in the schema yet. The error string
- // must keep matching here so it gets logged at info level and never
- // reaches Sentry as an unactionable client/server skew event.
- assert!(is_param_validation_error(
- "unknown param 'api_key' for config.update_model_settings"
- ));
- // `all::validate_params` — missing required field.
- assert!(is_param_validation_error(
- "missing required param 'session_id': active session identifier"
- ));
- // `params_to_object` — params field is the wrong JSON shape.
- assert!(is_param_validation_error(
- "invalid params: expected object or null, got array"
- ));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_param_validation_error_does_not_match_unrelated_errors() {
- // Handler-side / network / auth failures must still be reported.
- assert!(!is_param_validation_error(
- "backend returned 401 Unauthorized"
- ));
- assert!(!is_param_validation_error("network timeout"));
- assert!(!is_param_validation_error(
- "config.update_model_settings: store write failed"
- ));
- // Empty and substring-only matches don't qualify either.
- assert!(!is_param_validation_error(""));
- assert!(!is_param_validation_error(
- "rpc failed: unknown param 'x' for ns.fn"
- ));
-}
-
-#[test]
-fn is_session_expired_error_matches_missing_backend_session_token() {
- // Composio / web search / billing / team / webhooks / referral all surface
- // a "no backend session token" variant when the auth profile is gone. Each
- // of these should funnel into the auto-cleanup path instead of being
- // reported to Sentry as a fresh error on every 5 s poll.
- assert!(is_session_expired_error(
- "composio unavailable: no backend session token. Sign in first (auth_store_session)."
- ));
- assert!(is_session_expired_error(
- "no backend session token; run auth_store_session first"
- ));
- assert!(is_session_expired_error(
- "Web search unavailable: no backend session token. Sign in first so the server can proxy search."
- ));
- // Case-insensitive match — the helper lowercases first.
- assert!(is_session_expired_error("NO BACKEND SESSION TOKEN"));
-}
-
-#[test]
-fn local_offline_credential_does_not_publish_backend_session_expiry() {
- let local = crate::security::credentials::session_support::is_local_session_token(
- "header.payload.local",
- );
- let jwt = crate::security::credentials::session_support::is_local_session_token(
- "header.payload.signature",
- );
- for error in [
- "composio unavailable: no backend session token. Sign in first (auth_store_session).",
- "SESSION_EXPIRED: backend rejected session token on GET /teams/me/usage",
- ] {
- assert!(!should_publish_session_expired(error, local), "{error}");
- assert!(should_publish_session_expired(error, jwt), "{error}");
- let translated = translate_local_session_error(error, local).expect("local fallback");
- assert!(
- translated.starts_with(crate::core::observability::BACKEND_UNAVAILABLE_PREFIX),
- "{translated}"
- );
- assert!(!is_session_expired_error(&translated));
- assert!(translate_local_session_error(error, jwt).is_none());
- }
-}
-
-#[tokio::test(flavor = "current_thread")]
-#[cfg(feature = "http-server")]
-async fn structured_rpc_error_envelope_passes_through_generic_dispatch() {
- // The transport layer must surface any controller-emitted
- // `StructuredRpcError` payload without inspecting the method name —
- // this is what makes the boundary domain-agnostic. We register a
- // throwaway method-name on a thread-scoped op and confirm the
- // wire-shape carries the `kind`/`thread_id` data verbatim.
- use axum::body::to_bytes;
- use axum::extract::State;
- use axum::Json;
-
- let workspace = tempfile::tempdir().expect("workspace tempdir");
- let _env = EnvVarGuard::set_many(vec![(
- "OPENHUMAN_WORKSPACE",
- workspace.path().as_os_str().to_os_string(),
- )]);
-
- let stale_thread_request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(7),
- method: "openhuman.threads_generate_title".to_string(),
- params: json!({ "thread_id": "thread-ghost" }),
- };
- let response = rpc_handler(State(default_state()), Json(stale_thread_request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
- assert_eq!(body["error"]["data"]["kind"], "ThreadNotFound");
- assert_eq!(body["error"]["data"]["thread_id"], "thread-ghost");
- // The structured-error message must be human-readable on the wire —
- // never the encoded sentinel envelope.
- let message = body["error"]["message"].as_str().expect("error message");
- assert!(
- !message.contains("__OPENHUMAN_STRUCTURED_RPC_ERROR_V1__"),
- "sentinel-encoded envelope leaked onto the wire: {message}"
- );
- assert!(message.contains("thread-ghost"));
-}
-
-#[cfg(feature = "crash-reporting")]
-#[tokio::test(flavor = "current_thread")]
-#[cfg(feature = "http-server")]
-async fn thread_not_found_rpc_error_does_not_report_to_sentry() {
- use axum::body::to_bytes;
- use axum::extract::State;
- use axum::Json;
- use sentry::test::TestTransport;
- use tracing::Level;
- use tracing_subscriber::layer::SubscriberExt;
-
- let workspace = tempfile::tempdir().expect("workspace tempdir");
- let _env = EnvVarGuard::set_many(vec![(
- "OPENHUMAN_WORKSPACE",
- workspace.path().as_os_str().to_os_string(),
- )]);
-
- let transport = TestTransport::new();
- let sentry_options = sentry::ClientOptions {
- dsn: Some("https://[email protected]/1".parse().unwrap()),
- transport: Some(Arc::new(transport.clone())),
- ..Default::default()
- };
- let sentry_hub = Arc::new(sentry::Hub::new(
- Some(Arc::new(sentry_options.into())),
- Arc::new(Default::default()),
- ));
- let _sentry_guard = sentry::HubSwitchGuard::new(sentry_hub);
-
- let subscriber = tracing_subscriber::registry().with(
- sentry::integrations::tracing::layer().event_filter(|metadata| {
- // Mirror the production sentry-tracing layer: events emitted from
- // `report_error_message` are captured directly via
- // `sentry::capture_message` and must not be picked up here too
- // (otherwise this test sees double events).
- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {
- return sentry::integrations::tracing::EventFilter::Ignore;
- }
- match *metadata.level() {
- Level::ERROR => sentry::integrations::tracing::EventFilter::Event,
- Level::WARN | Level::INFO => sentry::integrations::tracing::EventFilter::Breadcrumb,
- _ => sentry::integrations::tracing::EventFilter::Ignore,
- }
- }),
- );
- let _subscriber_guard = tracing::subscriber::set_default(subscriber);
-
- let stale_thread_request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(1),
- method: "openhuman.threads_message_append".to_string(),
- params: json!({
- "thread_id": "thread-missing",
- "message": {
- "id": "msg-1",
- "content": "hello",
- "type": "text",
- "extraMetadata": {},
- "sender": "user",
- "createdAt": "2026-01-01T00:00:00Z"
- }
- }),
- };
- let response = rpc_handler(State(default_state()), Json(stale_thread_request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
- assert_eq!(body["error"]["data"]["kind"], "ThreadNotFound");
- assert!(
- transport.fetch_and_clear_events().is_empty(),
- "ThreadNotFound should not reach Sentry"
- );
-
- let unrelated_error_request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(2),
- method: "core.not_a_real_method".to_string(),
- params: json!({}),
- };
- let response = rpc_handler(State(default_state()), Json(unrelated_error_request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
- assert_eq!(body["error"]["data"], serde_json::Value::Null);
-
- let events = transport.fetch_and_clear_events();
- assert_eq!(
- events.len(),
- 1,
- "unrelated RPC errors should still reach Sentry"
- );
- assert_eq!(
- events[0].tags.get("domain").map(String::as_str),
- Some("rpc")
- );
- assert_eq!(
- events[0].tags.get("operation").map(String::as_str),
- Some("invoke_method")
- );
- assert_eq!(
- events[0].tags.get("method").map(String::as_str),
- Some("core.not_a_real_method")
- );
- // #3567: an unrecognised (non-allow-listed) method is still recorded for
- // triage, but downgraded from error to *warning* severity so it no longer
- // pages. The JSON-RPC method-not-found response above is unchanged.
- assert_eq!(
- events[0].level,
- sentry::Level::Warning,
- "unknown-method events should be warn-level (triage, not paging)"
- );
-}
-
-#[cfg(feature = "crash-reporting")]
-#[tokio::test(flavor = "current_thread")]
-#[cfg(feature = "http-server")]
-async fn unknown_method_severity_split_by_probe_allow_list() {
- // #3567: prove the full severity split at the transport boundary —
- // (1) an allow-listed probe name is NOT captured to Sentry (debug-only),
- // (2) a genuinely-unknown method still surfaces at warn for triage,
- // (3) the JSON-RPC error response to the caller is unchanged in both cases.
- use axum::body::to_bytes;
- use axum::extract::State;
- use axum::Json;
- use sentry::test::TestTransport;
- use tracing::Level;
- use tracing_subscriber::layer::SubscriberExt;
-
- let workspace = tempfile::tempdir().expect("workspace tempdir");
- let _env = EnvVarGuard::set_many(vec![(
- "OPENHUMAN_WORKSPACE",
- workspace.path().as_os_str().to_os_string(),
- )]);
-
- let transport = TestTransport::new();
- let sentry_options = sentry::ClientOptions {
- dsn: Some("https://[email protected]/1".parse().unwrap()),
- transport: Some(Arc::new(transport.clone())),
- ..Default::default()
- };
- let sentry_hub = Arc::new(sentry::Hub::new(
- Some(Arc::new(sentry_options.into())),
- Arc::new(Default::default()),
- ));
- let _sentry_guard = sentry::HubSwitchGuard::new(sentry_hub);
-
- let subscriber = tracing_subscriber::registry().with(
- sentry::integrations::tracing::layer().event_filter(|metadata| {
- // Mirror production: diagnostics from the report_* helpers are
- // captured directly via `sentry::capture_message`, so the bridge
- // must ignore their marker target to avoid double events.
- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {
- return sentry::integrations::tracing::EventFilter::Ignore;
- }
- match *metadata.level() {
- Level::ERROR => sentry::integrations::tracing::EventFilter::Event,
- Level::WARN | Level::INFO => sentry::integrations::tracing::EventFilter::Breadcrumb,
- _ => sentry::integrations::tracing::EventFilter::Ignore,
- }
- }),
- );
- let _subscriber_guard = tracing::subscriber::set_default(subscriber);
-
- // (1) Allow-listed probe → debug-only, never reaches Sentry.
- let probe_request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(1),
- method: "rpc.discover".to_string(),
- params: json!({}),
- };
- let response = rpc_handler(State(default_state()), Json(probe_request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
- // (3) Response is the unchanged JSON-RPC method-not-found envelope.
- assert_eq!(body["error"]["code"], json!(-32000));
- assert_eq!(
- body["error"]["message"],
- json!("unknown method: rpc.discover")
- );
- assert_eq!(body["error"]["data"], serde_json::Value::Null);
- assert!(
- transport.fetch_and_clear_events().is_empty(),
- "allow-listed probe methods must not reach Sentry"
- );
-
- // (2) Genuinely-unknown method → still captured, but at warn for triage.
- let unknown_request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(2),
- method: "totally.made.up.method".to_string(),
- params: json!({}),
- };
- let response = rpc_handler(State(default_state()), Json(unknown_request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
- // (3) Same unchanged method-not-found envelope for the unknown method.
- assert_eq!(body["error"]["code"], json!(-32000));
- assert_eq!(
- body["error"]["message"],
- json!("unknown method: totally.made.up.method")
- );
- assert_eq!(body["error"]["data"], serde_json::Value::Null);
-
- let events = transport.fetch_and_clear_events();
- assert_eq!(
- events.len(),
- 1,
- "genuinely-unknown methods should still be captured for triage"
- );
- assert_eq!(events[0].level, sentry::Level::Warning);
- assert_eq!(
- events[0].tags.get("domain").map(String::as_str),
- Some("rpc")
- );
- assert_eq!(
- events[0].tags.get("method").map(String::as_str),
- Some("totally.made.up.method")
- );
-}
-
-#[cfg(feature = "crash-reporting")]
-#[tokio::test(flavor = "current_thread")]
-#[cfg(feature = "http-server")]
-async fn invalid_ingest_payload_is_captured_at_warn_not_error() {
- // #5169 (CORE-RUST-1P0): a caller submitting an ingest payload that does
- // not match the canonicaliser schema is a *caller* error — the handler
- // already names the offending field and no core change can fix a producer
- // sending the wrong shape. Prove the same split as the unknown-method case
- // above: the JSON-RPC error response is unchanged, but the Sentry event is
- // warn (triage) rather than error (pages).
- use axum::body::to_bytes;
- use axum::extract::State;
- use axum::Json;
- use sentry::test::TestTransport;
- use tracing::Level;
- use tracing_subscriber::layer::SubscriberExt;
-
- let workspace = tempfile::tempdir().expect("workspace tempdir");
- let _env = EnvVarGuard::set_many(vec![(
- "OPENHUMAN_WORKSPACE",
- workspace.path().as_os_str().to_os_string(),
- )]);
-
- let transport = TestTransport::new();
- let sentry_options = sentry::ClientOptions {
- dsn: Some("https://[email protected]/1".parse().unwrap()),
- transport: Some(Arc::new(transport.clone())),
- ..Default::default()
- };
- let sentry_hub = Arc::new(sentry::Hub::new(
- Some(Arc::new(sentry_options.into())),
- Arc::new(Default::default()),
- ));
- let _sentry_guard = sentry::HubSwitchGuard::new(sentry_hub);
-
- let subscriber = tracing_subscriber::registry().with(
- sentry::integrations::tracing::layer().event_filter(|metadata| {
- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {
- return sentry::integrations::tracing::EventFilter::Ignore;
- }
- match *metadata.level() {
- Level::ERROR => sentry::integrations::tracing::EventFilter::Event,
- Level::WARN | Level::INFO => sentry::integrations::tracing::EventFilter::Breadcrumb,
- _ => sentry::integrations::tracing::EventFilter::Ignore,
- }
- }),
- );
- let _subscriber_guard = tracing::subscriber::set_default(subscriber);
-
- // `platform` is genuinely required by `ChatBatch` (unlike `timestamp`,
- // which now defaults — see `chat_payload_without_timestamp_is_accepted`),
- // so this reaches the invalid-payload branch rather than succeeding.
- let request = crate::core::types::RpcRequest {
- jsonrpc: "2.0".to_string(),
- id: json!(1),
- method: "openhuman.memory_tree_ingest".to_string(),
- params: json!({
- "source_kind": "chat",
- "source_id": "#general",
- "payload": { "messages": [] },
- }),
- };
- let response = rpc_handler(State(default_state()), Json(request)).await;
- let body = to_bytes(response.into_body(), usize::MAX)
- .await
- .expect("response body");
- let body: serde_json::Value = serde_json::from_slice(&body).expect("json response");
-
- // The caller still gets the precise, unchanged validation error.
- assert_eq!(body["error"]["code"], json!(-32000));
- let message = body["error"]["message"]
- .as_str()
- .expect("error message string");
- assert!(
- message.starts_with("invalid chat payload: "),
- "expected an invalid-chat-payload error, got {message:?}"
- );
-
- let events = transport.fetch_and_clear_events();
- assert_eq!(
- events.len(),
- 1,
- "invalid ingest payloads should still be captured for triage"
- );
- assert_eq!(
- events[0].level,
- sentry::Level::Warning,
- "caller payload errors must be warn-level (triage, not paging)"
- );
- assert_eq!(
- events[0].tags.get("method").map(String::as_str),
- Some("openhuman.memory_tree_ingest")
- );
-}
-
-#[test]
-fn is_session_expired_error_matches_session_jwt_required() {
- // Regression: Sentry issue 7472592145.
- // A prior 401 clears the stored JWT; the very next RPC call (e.g.
- // channels_telegram_login_start) finds no token and returns "session JWT
- // required; complete login first". This is the same auth-boundary condition
- // and must not be reported to Sentry.
- assert!(is_session_expired_error(
- "session JWT required; complete login first"
- ));
- assert!(is_session_expired_error(
- "session JWT required; complete login and store_session first"
- ));
- assert!(is_session_expired_error("session JWT required"));
- // Case-insensitive.
- assert!(is_session_expired_error("SESSION JWT REQUIRED"));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn escape_html_escapes_all_special_chars() {
- let raw = r#"<script>alert("x&y'z")</script>"#;
- let escaped = escape_html(raw);
- assert!(!escaped.contains('<'));
- assert!(!escaped.contains('>'));
- assert!(!escaped.contains('"'));
- assert!(!escaped.contains('\''));
- assert!(escaped.contains("&lt;"));
- assert!(escaped.contains("&gt;"));
- assert!(escaped.contains("&quot;"));
- assert!(escaped.contains("&#x27;"));
- // `&` must be escaped first so later substitutions don't double-encode.
- assert!(escaped.contains("&amp;y"));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn escape_html_is_noop_for_safe_text() {
- assert_eq!(escape_html("safe text 123"), "safe text 123");
- assert_eq!(escape_html(""), "");
-}
-
-// --- telegram callback fetch-metadata gate --------------------------------
-
-#[tokio::test]
-async fn invoke_method_rejects_array_params_for_registered_method() {
- // Registered controllers expect named-argument style (JSON object).
- // Passing an array must fail with a clear "invalid params" error
- // instead of silently calling the handler with no args.
- let err = invoke_method(
- default_state(),
- "openhuman.health_snapshot",
- json!([1, 2, 3]),
- )
- .await
- .expect_err("array params should be rejected");
- assert!(err.contains("invalid params"));
- assert!(err.contains("array"));
-}
-
-#[tokio::test]
-async fn invoke_method_rejects_string_params_for_registered_method() {
- let err = invoke_method(default_state(), "openhuman.health_snapshot", json!("oops"))
- .await
- .expect_err("string params should be rejected");
- assert!(err.contains("invalid params"));
- assert!(err.contains("string"));
-}
-
-#[tokio::test]
-async fn invoke_method_accepts_null_params_for_registered_method() {
- // JSON-RPC 2.0 allows omitting params; null must be treated like {}.
- let result = invoke_method(default_state(), "openhuman.health_snapshot", json!(null)).await;
- // Call should succeed or fail for domain reasons — but must NOT
- // fail with the "invalid params" shape error.
- if let Err(e) = result {
- assert!(
- !e.contains("invalid params"),
- "null should be accepted as empty object, got: {e}"
- );
- }
-}
-
-#[tokio::test]
-async fn invoke_method_unknown_method_returns_unknown_error() {
- let err = invoke_method(default_state(), "openhuman.totally_made_up_xyz", json!({}))
- .await
- .expect_err("unknown methods must error");
- assert!(err.contains("unknown method"));
-}
-
-#[tokio::test]
-async fn invoke_method_core_ping_via_tier1() {
- // core.* methods aren't in the registry; they route through tier 1.
- let result = invoke_method(default_state(), "core.ping", json!({}))
- .await
- .expect("core.ping should succeed via tier 1");
- assert_eq!(result, json!({ "ok": true }));
-}
-
-#[tokio::test]
-async fn invoke_method_core_version_via_tier1_reflects_state() {
- let state = super::AppState {
- core_version: "0.0.1-abc".into(),
- };
- let result = invoke_method(state, "core.version", json!({}))
- .await
- .expect("core.version should succeed");
- assert_eq!(result, json!({ "version": "0.0.1-abc" }));
-}
-
-#[tokio::test]
-#[cfg(feature = "http-server")]
-async fn test_http_health_handler_returns_correct_status() {
- use axum::body::to_bytes;
- use axum::http::StatusCode;
- use axum::response::IntoResponse;
-
- // Call the handler once and derive both the status and expected status from
- // the same response — avoids a TOCTOU race where a separate snapshot()
- // call before/after the handler could observe different component state.
- let resp = super::health_handler().await.into_response();
- let status = resp.status();
-
- let body = to_bytes(resp.into_body(), usize::MAX)
- .await
- .expect("failed to read body");
- let snapshot: serde_json::Value =
- serde_json::from_slice(&body).expect("failed to deserialize health snapshot");
-
- let components = snapshot["components"]
- .as_object()
- .expect("components should be an object");
-
- // Granular liveness (#3312): the HTTP status is driven by the `healthy`
- // verdict (no *critical* component unhealthy), not by all-components-ok.
- // Derive the expectation from the body so the test asserts the handler's
- // internal consistency rather than racing on live component state.
- let body_healthy = snapshot["healthy"]
- .as_bool()
- .expect("body exposes a `healthy` verdict flag");
- let expected_status = if body_healthy {
- StatusCode::OK
- } else {
- StatusCode::SERVICE_UNAVAILABLE
- };
- assert_eq!(status, expected_status);
-
- // `healthy` must mean "no critical component is unhealthy", and any
- // unhealthy component must be bucketed as either critical or degraded.
- let critical_unhealthy = snapshot["critical_unhealthy"]
- .as_array()
- .expect("body exposes critical_unhealthy");
- assert_eq!(body_healthy, critical_unhealthy.is_empty());
-
- let unhealthy_count = components
- .values()
- .filter(|c| {
- let s = c["status"].as_str().unwrap_or("");
- s != "ok" && s != "starting"
- })
- .count();
- let degraded_count = snapshot["degraded_components"]
- .as_array()
- .expect("body exposes degraded_components")
- .len();
- assert_eq!(
- unhealthy_count,
- critical_unhealthy.len() + degraded_count,
- "every unhealthy component is bucketed as critical or degraded"
- );
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_matches_wallet_constant() {
- // The classifier keys off the wallet layer's exact "not configured"
- // message so wallet-backed RPCs stay out of Sentry.
- assert!(is_wallet_not_configured_error(
- crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE
- ));
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_is_coupled_to_the_wallet_constant() {
- // Drift guard: if the wallet wording changes without updating the shared
- // constant the classifier matches, this fails — preventing the noise from
- // silently returning to Sentry. Mirrors the param-validation prefix locks.
- assert_eq!(
- crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE,
- "wallet is not configured; run wallet setup first"
- );
-}
-
-#[test]
-#[cfg(feature = "http-server")]
-fn is_wallet_not_configured_error_does_not_match_other_errors() {
- // Other wallet/seed-derivation failures (decrypt, key derivation, locked
- // keychain) are real defects and must keep reaching Sentry.
- assert!(!is_wallet_not_configured_error(
- "wallet signer init: bad seed"
- ));
- assert!(!is_wallet_not_configured_error(
- "decrypt secret: kms timeout"
- ));
- assert!(!is_wallet_not_configured_error(""));
- // Substring-only must not qualify — exact equality is required.
- assert!(!is_wallet_not_configured_error(
- "rpc failed: wallet is not configured; run wallet setup first"
- ));
-}
diff --git a/tests/config_auth_app_state_connectivity_e2e.rs b/tests/config_auth_app_state_connectivity_e2e.rs
index fbe5d0fc62..cc09949f3c 100644
--- a/tests/config_auth_app_state_connectivity_e2e.rs
+++ b/tests/config_auth_app_state_connectivity_e2e.rs
@@ -59,6 +59,7 @@ use openhuman_tinyhumans::backend::url::{
looks_like_local_ai_endpoint, normalize_api_base_url, APP_ENV_VAR, DEFAULT_API_BASE_URL,
DEFAULT_STAGING_API_BASE_URL, OPENHUMAN_INFERENCE_PATH, VITE_APP_ENV_VAR,
};
+use openhuman_rpc::server::build_core_http_router;
use tinybus::EventHandler;
const TEST_RPC_TOKEN: &str = "worker-a-domain-e2e-token";