The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(search): refresh the session token before the request, not after a 401\n\nThe retry ran after the failure it was recovering from, and that failure is\nnot free. `/agent-integrations/parallel/search` is a POST, so it takes the\nnon-soft branch of `handle_session_jwt_unauthorized`, which publishes\n`DomainEvent::SessionExpired`; `SessionExpiredSubscriber` answers that with an\nunconditional `clear_session` and never compares the rejected token against the\nstored one. The retry could therefore succeed with the freshly-read JWT and the\nqueued event would then delete that same JWT — one working search followed by an\nunexplained sign-out.\n\nResolve the client before the request instead: if the credential store holds a\ndifferent token than the one baked into the cached client, use a client built\nfrom the store. The stale-token 401 is never provoked, so there is no teardown\nto race. A genuinely dead session still 401s and still tears down, which is the\ncorrect outcome and is left alone.\n\nAlso covers the tool built while signed out (`client: None`), which previously\nstayed dead until the tool registry was rebuilt.\n\nTests now pin the behaviour rather than the pre-existing error path: assert on\nthe Authorization header the backend actually received, for both the superseded\ntoken (must send the refreshed one) and the unchanged token (must not swap).\nThe prior test used a 500, which never reaches the SESSION_EXPIRED branch, and\npassed identically with the change reverted. Restores the\n`test_execute_without_backend_client` assertion that was widened to an `||` —\nthe new message still contains "backend session token" verbatim.\n\nRefs #5873\n
M3gA-Mind2157ed57333b
diff --git a/src/openhuman/search/tools/web_search.rs b/src/openhuman/search/tools/web_search.rsindex 6d12c099cb..04ebf52786 100644--- a/src/openhuman/search/tools/web_search.rs+++ b/src/openhuman/search/tools/web_search.rs@@ -40,6 +40,50 @@ pub struct WebSearchTool {}impl WebSearchTool {+ /// The client to use for this call, preferring one whose JWT matches what+ /// the credential store holds *right now*.+ ///+ /// The tool's client is built once, when the search-tool registry is built,+ /// and its JWT is baked in at that moment; after a session refresh it is+ /// stale and posting with it 401s. That 401 is not a cheap failure. For a+ /// non-Composio path `handle_session_jwt_unauthorized` publishes+ /// `DomainEvent::SessionExpired`, and `SessionExpiredSubscriber` answers it+ /// with an unconditional `clear_session` that never compares the rejected+ /// token against the stored one. So recovering *after* the 401 races a+ /// teardown that is already in flight — a retry can succeed with the fresh+ /// JWT and the queued event then deletes that same JWT, signing the user+ /// out on a search that just worked.+ ///+ /// Refreshing *before* the request avoids that entirely: the stale-token+ /// 401 is never provoked. A genuinely dead session still 401s and still+ /// tears down, which is the correct outcome for that case and is+ /// deliberately left alone (#5873).+ ///+ /// Also covers the tool that was built while signed out: `client` is `None`+ /// there, and before this it stayed dead until the registry was rebuilt.+ fn resolve_client(&self) -> Option<Arc<IntegrationClient>> {+ let fresh = self+ .root_config+ .as_deref()+ .and_then(crate::openhuman::integrations::build_client);++ match (fresh, self.client.as_ref()) {+ (Some(fresh), Some(cached)) => {+ if fresh.auth_token == cached.auth_token {+ Some(Arc::clone(cached))+ } else {+ tracing::debug!(+ "[web_search] cached client holds a superseded session token — using the refreshed one"+ );+ Some(fresh)+ }+ }+ (Some(fresh), None) => Some(fresh),+ (None, Some(cached)) => Some(Arc::clone(cached)),+ (None, None) => None,+ }+ }+pub fn new(client: Option<Arc<IntegrationClient>>,root_config: Option<Arc<Config>>,@@ -205,7 +249,7 @@ impl Tool for WebSearchTool {.await;}- let client = self.client.as_ref().ok_or_else(|| {+ let client = self.resolve_client().ok_or_else(|| {anyhow::anyhow!("Web search unavailable: no backend session token. \Sign in to TinyHumans so the server can proxy search, \@@ -238,34 +282,9 @@ impl Tool for WebSearchTool {}});- // On SESSION_EXPIRED the baked-in client carries a JWT that expired- // mid-session. If the user has since re-authenticated, `build_client`- // will read the new JWT from the credential store and the retry- // succeeds. On any other error the original error propagates (#5873).- let resp = match client+ let resp = client.post::<SearchResponse>("/agent-integrations/parallel/search", &body)- .await- {- Ok(resp) => resp,- Err(e) if e.to_string().starts_with("SESSION_EXPIRED:") => {- let fresh = self- .root_config- .as_deref()- .and_then(crate::openhuman::integrations::build_client);- match fresh {- Some(fresh_client) => {- tracing::debug!(- "[web_search] session expired — retrying with fresh client"- );- fresh_client- .post::<SearchResponse>("/agent-integrations/parallel/search", &body)- .await?- }- None => return Err(e),- }- }- Err(e) => return Err(e),- };+ .await?;// Attribute the search to the provider the managed backend resolved to// (Exa by default). The provider name is echoed in the result text sodiff --git a/src/openhuman/search/tools/web_search_tests.rs b/src/openhuman/search/tools/web_search_tests.rsindex 149eaa1e02..fa39b6b9fd 100644--- a/src/openhuman/search/tools/web_search_tests.rs+++ b/src/openhuman/search/tools/web_search_tests.rs@@ -212,8 +212,10 @@ async fn test_execute_empty_query() {async fn test_execute_without_backend_client() {let result = tool().execute(json!({"query": "test"})).await;assert!(result.is_err());- let err = result.unwrap_err().to_string();- assert!(err.contains("session token") || err.contains("Sign in"));+ assert!(result+ .unwrap_err()+ .to_string()+ .contains("backend session token"));}#[tokio::test]@@ -368,36 +370,135 @@ async fn test_execute_uses_direct_search_api_when_configured() {assert!(result.output().contains("https://example.com/direct"));}-/// Regression for #5873: when `root_config` is absent, a SESSION_EXPIRED error-/// from `client.post()` propagates unchanged (no panic, no infinite retry).+/// Regression for #5873: a cached client whose JWT has been superseded must not+/// be the one that talks to the backend — the token currently in the credential+/// store is.+///+/// This is the assertion the fix lives or dies on. Point `resolve_client` back+/// at `self.client` and the backend receives `stale-token`, so the recorded+/// Authorization header below no longer matches.+///+/// Deliberately asserts on the header the *backend actually saw* rather than on+/// a returned value: the whole failure mode is "the right result arrived over+/// the wrong credential", which a result-shaped assertion cannot see.#[tokio::test]-async fn test_session_expired_propagates_when_root_config_absent() {- use axum::{routing::post, Json};- use serde_json::Value;-- // Mock backend returns an error body that IntegrationClient maps to a- // non-SESSION_EXPIRED error so we can test the propagation branch cheaply- // without going through the real 401 handler (which publishes domain events).- // The important guarantee: any error that is NOT SESSION_EXPIRED must be- // returned unchanged. We verify the error reaches the caller.- let app = Router::new().route(- "/agent-integrations/parallel/search",- post(|Json(_): Json<Value>| async move {- (- axum::http::StatusCode::INTERNAL_SERVER_ERROR,- Json(json!({ "success": false, "message": "upstream unavailable" })),- )- }),+async fn test_refreshes_superseded_session_token_before_posting() {+ use crate::openhuman::config::Config;+ use crate::openhuman::security::credentials::profiles::{AuthProfile, AuthProfilesStore};+ use crate::openhuman::security::credentials::APP_SESSION_PROVIDER;+ use std::sync::Mutex;++ #[derive(Clone, Default)]+ struct SeenAuth(Arc<Mutex<Option<String>>>);++ let seen = SeenAuth::default();+ let app = Router::new()+ .route(+ "/agent-integrations/parallel/search",+ post(+ |State(seen): State<SeenAuth>, headers: HeaderMap, Json(_): Json<Value>| async move {+ *seen.0.lock().expect("auth header mutex") = headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+ Json(json!({+ "success": true,+ "data": { "searchId": "s-1", "results": [], "costUsd": 0.0 }+ }))+ },+ ),+ )+ .with_state(seen.clone());++ let base_url = start_mock_backend(app).await;++ // Credential store holds the CURRENT session token.+ let tmp = tempfile::tempdir().expect("tempdir");+ AuthProfilesStore::new(tmp.path(), false)+ .upsert_profile(+ AuthProfile::new_token(APP_SESSION_PROVIDER, "default", "fresh-token".to_string()),+ true,+ )+ .expect("seed app-session profile");++ let mut config = Config::default();+ // Credentials resolve against `config_path`'s parent, so this is what points+ // `build_client` at the seeded store rather than the operator's real one.+ config.config_path = tmp.path().join("config.toml");+ config.api_url = Some(base_url.clone());+ config.secrets.encrypt = false;++ // Cached client carries the token the tool was BUILT with — now superseded.+ let stale = Arc::new(IntegrationClient::new(base_url, "stale-token".to_string()));++ let _ = WebSearchTool::new(Some(stale), Some(Arc::new(config)), 5, 15)+ .execute(json!({"query": "who holds the token"}))+ .await;++ let seen_auth = seen.0.lock().expect("auth header mutex").clone();+ assert_eq!(+ seen_auth.as_deref(),+ Some("Bearer fresh-token"),+ "the request must carry the token from the credential store, not the \+ superseded one baked into the cached client");+}++/// The other half of the same branch: when the cached token is still current,+/// no swap happens and the cached client is reused as-is.+#[tokio::test]+async fn test_keeps_cached_client_when_its_token_is_still_current() {+ use crate::openhuman::config::Config;+ use crate::openhuman::security::credentials::profiles::{AuthProfile, AuthProfilesStore};+ use crate::openhuman::security::credentials::APP_SESSION_PROVIDER;+ use std::sync::Mutex;++ #[derive(Clone, Default)]+ struct SeenAuth(Arc<Mutex<Option<String>>>);++ let seen = SeenAuth::default();+ let app = Router::new()+ .route(+ "/agent-integrations/parallel/search",+ post(+ |State(seen): State<SeenAuth>, headers: HeaderMap, Json(_): Json<Value>| async move {+ *seen.0.lock().expect("auth header mutex") = headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .map(str::to_string);+ Json(json!({+ "success": true,+ "data": { "searchId": "s-1", "results": [], "costUsd": 0.0 }+ }))+ },+ ),+ )+ .with_state(seen.clone());let base_url = start_mock_backend(app).await;- let client = Arc::new(IntegrationClient::new(base_url, "tok".into()));- let result = WebSearchTool::new(Some(client), None, 5, 15)- .execute(json!({"query": "test"}))++ let tmp = tempfile::tempdir().expect("tempdir");+ AuthProfilesStore::new(tmp.path(), false)+ .upsert_profile(+ AuthProfile::new_token(APP_SESSION_PROVIDER, "default", "same-token".to_string()),+ true,+ )+ .expect("seed app-session profile");++ let mut config = Config::default();+ config.config_path = tmp.path().join("config.toml");+ config.api_url = Some(base_url.clone());+ config.secrets.encrypt = false;++ let cached = Arc::new(IntegrationClient::new(base_url, "same-token".to_string()));++ let _ = WebSearchTool::new(Some(cached), Some(Arc::new(config)), 5, 15)+ .execute(json!({"query": "unchanged"})).await;- assert!(- result.is_err(),- "non-200 backend response must surface as Err"+ assert_eq!(+ seen.0.lock().expect("auth header mutex").as_deref(),+ Some("Bearer same-token"),+ "an unchanged token must not trigger a client swap");}