Skip to content

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

fix(search): retry web search on SESSION_EXPIRED with fresh integration client

shanu8de5567524a1
diff --git a/src/openhuman/search/engines/managed.rs b/src/openhuman/search/engines/managed.rs
index c52db94f78..a0501ef7b6 100644
--- a/src/openhuman/search/engines/managed.rs
+++ b/src/openhuman/search/engines/managed.rs
@@ -1,6 +1,7 @@
use crate::openhuman::config::Config;
use crate::openhuman::search::registry::SearchToolParams;
use crate::openhuman::tools::Tool;
+use std::sync::Arc;
pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
tracing::debug!(
@@ -10,6 +11,7 @@ pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<d
vec![Box::new(crate::openhuman::search::WebSearchTool::new(
crate::openhuman::integrations::build_client(root_config),
+ Some(Arc::new(root_config.clone())),
params.max_results,
params.timeout_secs,
))]
diff --git a/src/openhuman/search/engines/parallel.rs b/src/openhuman/search/engines/parallel.rs
index 4ee5936d30..1b2827c21f 100644
--- a/src/openhuman/search/engines/parallel.rs
+++ b/src/openhuman/search/engines/parallel.rs
@@ -14,6 +14,7 @@ pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<d
);
return vec![Box::new(crate::openhuman::search::WebSearchTool::new(
None,
+ Some(Arc::new(root_config.clone())),
params.max_results,
params.timeout_secs,
))];
@@ -40,6 +41,7 @@ pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<d
)),
Box::new(crate::openhuman::search::WebSearchTool::new(
Some(Arc::clone(&client)),
+ Some(Arc::new(root_config.clone())),
params.max_results,
params.timeout_secs,
)),
diff --git a/src/openhuman/search/tools/web_search.rs b/src/openhuman/search/tools/web_search.rs
index 911e9f8b7f..a7396fb89d 100644
--- a/src/openhuman/search/tools/web_search.rs
+++ b/src/openhuman/search/tools/web_search.rs
@@ -1,4 +1,5 @@
use super::{SearchResponse, SearchResultItem, SeltzSearchTool};
+use crate::openhuman::config::Config;
use crate::openhuman::integrations::IntegrationClient;
use crate::openhuman::tools::traits::{Tool, ToolCallOptions, ToolResult};
use async_trait::async_trait;
@@ -29,6 +30,10 @@ pub(crate) fn resolve_managed_provider(resp: &SearchResponse) -> &str {
/// Web search tool backed by the server-side Parallel integration proxy.
pub struct WebSearchTool {
client: Option<Arc<IntegrationClient>>,
+ /// Root config held so `execute_with_options` can rebuild a fresh
+ /// `IntegrationClient` when the baked-in one carries a stale JWT
+ /// (i.e. when the user re-authenticated after token expiry — #5873).
+ root_config: Option<Arc<Config>>,
direct_search: Option<SeltzSearchTool>,
max_results: usize,
timeout_secs: u64,
@@ -37,11 +42,13 @@ pub struct WebSearchTool {
impl WebSearchTool {
pub fn new(
client: Option<Arc<IntegrationClient>>,
+ root_config: Option<Arc<Config>>,
max_results: usize,
timeout_secs: u64,
) -> Self {
Self {
client,
+ root_config,
direct_search: None,
max_results: max_results.clamp(1, 10),
timeout_secs: timeout_secs.max(1),
@@ -200,7 +207,9 @@ impl Tool for WebSearchTool {
let client = self.client.as_ref().ok_or_else(|| {
anyhow::anyhow!(
- "Web search unavailable: no backend session token. Sign in first so the server can proxy search."
+ "Web search unavailable: no backend session token. \
+ Sign in to TinyHumans so the server can proxy search, \
+ or configure a direct search API key under Settings → Search."
)
})?;
@@ -229,9 +238,37 @@ impl Tool for WebSearchTool {
}
});
- let resp = client
+ // 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
.post::<SearchResponse>("/agent-integrations/parallel/search", &body)
- .await?;
+ .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),
+ };
// Attribute the search to the provider the managed backend resolved to
// (Exa by default). The provider name is echoed in the result text so
diff --git a/src/openhuman/search/tools/web_search_tests.rs b/src/openhuman/search/tools/web_search_tests.rs
index 87e0cc0030..cd6b51c630 100644
--- a/src/openhuman/search/tools/web_search_tests.rs
+++ b/src/openhuman/search/tools/web_search_tests.rs
@@ -4,7 +4,7 @@ use serde_json::Value;
use std::sync::atomic::{AtomicBool, Ordering};
fn tool() -> WebSearchTool {
- WebSearchTool::new(None, 5, 15)
+ WebSearchTool::new(None, None, 5, 15)
}
async fn start_mock_backend(app: Router) -> String {
@@ -135,7 +135,7 @@ fn test_parse_parallel_results_with_data() {
#[test]
fn test_parse_parallel_results_respects_max_results() {
- let tool = WebSearchTool::new(None, 2, 15);
+ let tool = WebSearchTool::new(None, None, 2, 15);
let results = vec![
SearchResultItem {
title: "Result 1".into(),
@@ -212,10 +212,8 @@ 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());
- assert!(result
- .unwrap_err()
- .to_string()
- .contains("backend session token"));
+ let err = result.unwrap_err().to_string();
+ assert!(err.contains("session token") || err.contains("Sign in"));
}
#[tokio::test]
@@ -259,7 +257,7 @@ async fn test_execute_posts_to_backend_and_renders_results() {
let base_url = start_mock_backend(app).await;
let client = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- let result = WebSearchTool::new(Some(client), 5, 15)
+ let result = WebSearchTool::new(Some(client), None, 5, 15)
.execute(json!({"query": "test success"}))
.await
.expect("execute() should return rendered backend results");
@@ -303,7 +301,7 @@ async fn test_execute_attributes_backend_reported_provider() {
let base_url = start_mock_backend(app).await;
let client = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- let result = WebSearchTool::new(Some(client), 5, 15)
+ let result = WebSearchTool::new(Some(client), None, 5, 15)
.execute(json!({"query": "anything"}))
.await
.expect("execute() should render backend results");
@@ -353,7 +351,7 @@ async fn test_execute_uses_direct_search_api_when_configured() {
.with_state(state);
let base_url = start_mock_backend(app).await;
- let result = WebSearchTool::new(None, 5, 15)
+ let result = WebSearchTool::new(None, None, 5, 15)
.with_direct_search(Some(SeltzSearchTool::new(
Some("test-key".into()),
Some(base_url),
@@ -369,3 +367,34 @@ async fn test_execute_uses_direct_search_api_when_configured() {
assert!(result.output().contains("Direct Search Result"));
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).
+#[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" })),
+ )
+ }),
+ );
+
+ 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"}))
+ .await;
+
+ assert!(result.is_err(), "non-200 backend response must surface as Err");
+}