Skip to content

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

fix(web_chat): carry caller core context into spawned turns

Steven Enamakel7351f27f050a
diff --git a/crates/openhuman-core/src/agent_runs/agent_chat/controllers.rs b/crates/openhuman-core/src/agent_runs/agent_chat/controllers.rs
index 583957575d..c159f9bd52 100644
--- a/crates/openhuman-core/src/agent_runs/agent_chat/controllers.rs
+++ b/crates/openhuman-core/src/agent_runs/agent_chat/controllers.rs
@@ -156,7 +156,13 @@ fn handle_agent_chat(
.with_provider_options(params.inference_provider_options)
.with_reasoning_effort(params.inference_reasoning_effort)
}),
- super::AgentChatEnv::default(),
+ super::AgentChatEnv {
+ host: crate::agent::turn_env::HostTurnEnv {
+ core: ctx.downgrade(),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
)
.await?
.into_rpc_json()
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index 022663faa6..7c956a9c9e 100644
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@ -241,7 +241,11 @@ where
request_id,
});
let deadline = resolve_web_turn_deadline(ctx).await;
- let (env, turn_cancellation) = turn_host_env(deadline);
+ let (mut env, turn_cancellation) = turn_host_env(deadline);
+ // The turn context crosses task boundaries with this value. Carry its
+ // owner explicitly so tools (especially sub-agent persistence) do not
+ // depend on a task-local CoreContext surviving the web-chat spawn.
+ env.core = ctx.downgrade();
run_until_stopped(
cancel_token,
turn_cancellation,
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
index e5e840d94d..050f0b4344 100644
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
@@ -29,6 +29,42 @@ fn disabled_backstop_carries_no_deadline() {
assert!(env.turn_deadline.is_none());
}
+/// A spawned web turn retains its caller's owner context for tools that open
+/// tenant-scoped persistence after the task-local scope has ended.
+#[tokio::test]
+async fn guarded_turn_env_carries_the_callers_core_context() {
+ let core = crate::core::runtime::CoreContext::for_test(
+ crate::core::runtime::DomainSet::full(),
+ None,
+ );
+ let ctx = crate::core::runtime::DispatchCtx::new(Arc::clone(&core));
+ let returned = run_turn_under_cancel_and_deadline(
+ &ctx,
+ CancellationToken::new(),
+ crate::security::turn_origin::AgentTurnOrigin::WebChat {
+ thread_id: "thread".into(),
+ client_id: "client".into(),
+ request_id: None,
+ },
+ crate::security::approval::ApprovalChatContext {
+ thread_id: "thread".into(),
+ client_id: "client".into(),
+ request_id: None,
+ },
+ |env, _, _| async move {
+ let carried = env
+ .core
+ .as_ref()
+ .and_then(std::sync::Weak::upgrade)
+ .expect("guarded turn carries its caller CoreContext");
+ assert!(Arc::ptr_eq(&carried, &core));
+ Ok(result("done"))
+ },
+ )
+ .await;
+ assert!(returned.is_some());
+}
+
/// The env's cancellation is the very token a Stop fires.
#[test]
fn guarded_turn_env_shares_its_cancellation_with_the_stop_handle() {
diff --git a/tests/in_process/agent_prompt_comprehension_e2e.rs b/tests/in_process/agent_prompt_comprehension_e2e.rs
index 2374d1cd16..77ea4be96d 100644
--- a/tests/in_process/agent_prompt_comprehension_e2e.rs
+++ b/tests/in_process/agent_prompt_comprehension_e2e.rs
@@ -442,12 +442,17 @@ struct Stack {
rpc_base: String,
_guards: Vec<EnvVarGuard>,
_tmp: tempfile::TempDir,
+ previous_storage: Option<std::sync::Arc<dyn openhuman_core::storage::StorageBackend>>,
joins: Vec<tokio::task::JoinHandle<Result<(), std::io::Error>>>,
}
impl Drop for Stack {
fn drop(&mut self) {
self.joins.iter().for_each(|j| j.abort());
+ openhuman_core::storage::clear();
+ if let Some(previous) = self.previous_storage.take() {
+ openhuman_core::storage::install(previous);
+ }
}
}
@@ -455,7 +460,6 @@ async fn boot_stack(extra_config: &str) -> Stack {
// The managed chat provider is installed by the TinyHumans layer; without
// it every turn ends in `chat_error.inference` and no request reaches the
// scripted upstream.
- crate::tinyhumans_boot::boot();
AGENT_DEF_REGISTRY_INIT.get_or_init(|| {
AgentDefinitionRegistry::init_global_builtins()
.expect("AgentDefinitionRegistry::init_global_builtins must not fail");
@@ -468,7 +472,10 @@ async fn boot_stack(extra_config: &str) -> Stack {
let tmp = tempdir().expect("tempdir");
let home = tmp.path().to_path_buf();
let openhuman_home = home.join(".openhuman");
- let guards = vec![
+ let previous_storage = openhuman_core::storage::install(std::sync::Arc::new(
+ tinystoragedrivers_testkit::MemoryBackend::new(),
+ ));
+ let mut guards = vec![
EnvVarGuard::set_to_path("HOME", &home),
EnvVarGuard::unset("OPENHUMAN_WORKSPACE"),
EnvVarGuard::unset("BACKEND_URL"),
@@ -477,6 +484,12 @@ async fn boot_stack(extra_config: &str) -> Stack {
let (mock_addr, mock_join) = serve_on_ephemeral(scripted_upstream_router()).await;
let mock_origin = format!("http://{mock_addr}");
+ // `api_url` is the inference override. Backend routing deliberately
+ // rejects arbitrary loopback endpoints as hosted APIs, so point the
+ // backend-specific resolver at this same local fixture explicitly.
+ guards.push(EnvVarGuard::set("BACKEND_URL", &mock_origin));
+ guards.push(EnvVarGuard::set("VITE_BACKEND_URL", &mock_origin));
+ crate::tinyhumans_boot::boot();
write_min_config(&openhuman_home, &mock_origin, extra_config);
write_min_config(
&openhuman_home.join("users").join("e2e-user"),
@@ -501,6 +514,7 @@ async fn boot_stack(extra_config: &str) -> Stack {
rpc_base,
_guards: guards,
_tmp: tmp,
+ previous_storage,
joins: vec![mock_join, rpc_join],
}
}
@@ -890,7 +904,10 @@ fn orchestrator_searches_for_and_calls_the_integration_action() {
],
advertises_nothing: false,
max_consecutive_calls_of: None,
- extra_config: "",
+ // Keep discovery local and deterministic; the default Jev ranker is
+ // installed by the host and this fixture does not mock its ranking
+ // service.
+ extra_config: "[agent.tool_search]\nranker = \"bm25\"\n",
});
}
diff --git a/tests/json_rpc_threads_e2e.rs b/tests/json_rpc_threads_e2e.rs
index ad4e1a2321..19bfac6dad 100644
--- a/tests/json_rpc_threads_e2e.rs
+++ b/tests/json_rpc_threads_e2e.rs
@@ -1004,29 +1004,50 @@ async fn json_rpc_threads_token_usage_reads_persisted_thread_totals() {
rpc_join.abort();
}
-/// Seed a raw append-only session transcript at
-/// `{workspace}/session_raw/{stem}.jsonl` (meta header + body lines).
-fn seed_raw_transcript(workspace: &Path, stem: &str, thread_id: &str, body: &[&str]) {
- let raw_dir = workspace.join("session_raw");
- std::fs::create_dir_all(&raw_dir).expect("create session_raw");
- let meta = format!(
- r#"{{"_meta":{{"version":1,"agent":"orchestrator","dispatcher":"native","created":"2026-07-21T00:00:00Z","updated":"2026-07-21T00:00:10Z","turn_count":1,"input_tokens":30,"output_tokens":13,"cached_input_tokens":0,"charged_amount_usd":0.003,"thread_id":"{thread_id}"}}}}"#
- );
- let mut buf = meta;
- buf.push('\n');
- for line in body {
- buf.push_str(line);
- buf.push('\n');
- }
- std::fs::write(raw_dir.join(format!("{stem}.jsonl")), buf).expect("write transcript");
+/// Seed the same driver-backed session store the RPC reads. Workspace
+/// transcripts moved from `session_raw/*.jsonl` into the session-store port;
+/// writing legacy files here left this endpoint with an empty transcript.
+fn seed_transcript(
+ locator: &std::sync::Arc<dyn tinyagents_session::transcript::TranscriptLocator>,
+ stem: &str,
+ thread_id: &str,
+ agent_name: &str,
+ agent_type: Option<&str>,
+ messages: &[tinyagents_session::transcript::TranscriptMessage],
+) {
+ use tinyagents_session::transcript::TranscriptMeta;
+
+ let meta = TranscriptMeta {
+ agent_name: agent_name.to_string(),
+ agent_id: Some(agent_name.to_string()),
+ agent_type: agent_type.map(str::to_string),
+ dispatcher: "native".to_string(),
+ provider: Some("anthropic".to_string()),
+ model: Some("claude-x".to_string()),
+ created: "2026-07-21T00:00:00Z".to_string(),
+ updated: "2026-07-21T00:00:10Z".to_string(),
+ turn_count: 1,
+ prefix_message_count: None,
+ input_tokens: 30,
+ output_tokens: 13,
+ cached_input_tokens: 0,
+ charged_amount_usd: 0.003,
+ thread_id: Some(thread_id.to_string()),
+ task_id: None,
+ session_id: None,
+ parent_session_id: None,
+ };
+ locator
+ .open_stem(stem, meta)
+ .expect("open transcript")
+ .replace(messages)
+ .expect("write transcript messages");
}
#[tokio::test]
async fn json_rpc_threads_transcript_get_projects_and_paginates() {
let _env_lock = json_rpc_e2e_env_lock_async().await;
let tmp = tempdir().expect("tempdir");
- // Config resolves the runtime workspace to `OPENHUMAN_WORKSPACE/workspace`
- // (see resolve_config_dir_for_workspace), so seed transcripts there.
let workspace = tmp.path().join("workspace");
std::fs::create_dir_all(&workspace).expect("create workspace");
let workspace = workspace.as_path();
@@ -1036,32 +1057,108 @@ async fn json_rpc_threads_transcript_get_projects_and_paginates() {
let _vite_backend_url_guard = EnvVarGuard::unset("VITE_BACKEND_URL");
let _api_url_guard = EnvVarGuard::unset("OPENHUMAN_API_URL");
+ let provider = openhuman_core::storage::sessions::provider_for_workspace(workspace);
+ let locator = provider.for_agent("orchestrator").transcripts;
+
let thread_id = "thr_transcript_e2e";
let root_stem = "1000_orchestrator";
- // A full turn: system scaffolding (dropped), user with injected datetime
- // prefix, assistant tool-calling step (reasoning + tool_calls), tool result,
- // final assistant answer.
- seed_raw_transcript(
- workspace,
+ use tinyagents_session::transcript::{
+ MessageUsage, ToolFailure, TranscriptMessage, TranscriptToolCall, TurnUsage,
+ };
+
+ let mut user = TranscriptMessage::user(
+ "Current Date & Time: 2026-07-21 09:00:00 UTC\n\nWeather in NYC?",
+ );
+ user.request_id = Some("req-1".to_string());
+ let mut assistant = TranscriptMessage::assistant_with_calls(
+ "Checking.",
+ vec![
+ TranscriptToolCall {
+ id: "call-1".to_string(),
+ name: "get_weather".to_string(),
+ arguments: r#"{"city":"NYC"}"#.to_string(),
+ extra_content: None,
+ },
+ TranscriptToolCall {
+ id: "call-2".to_string(),
+ name: "get_traffic".to_string(),
+ arguments: r#"{"city":"NYC"}"#.to_string(),
+ extra_content: None,
+ },
+ ],
+ );
+ assistant.request_id = Some("req-1".to_string());
+ assistant.turn_usage = Some(TurnUsage {
+ provider: "anthropic".to_string(),
+ model: "claude-x".to_string(),
+ usage: MessageUsage {
+ input: 10,
+ output: 5,
+ cost_usd: 0.001,
+ ..MessageUsage::default()
+ },
+ ts: "2026-07-21T09:00:01Z".to_string(),
+ reasoning_content: Some("call the tool".to_string()),
+ tool_calls: Vec::new(),
+ iteration: 1,
+ });
+ let mut weather = TranscriptMessage::tool_result("call-1", "72F sunny");
+ weather.request_id = Some("req-1".to_string());
+ let mut traffic = TranscriptMessage::tool_result(
+ "call-2",
+ "error: traffic service unavailable",
+ );
+ traffic.request_id = Some("req-1".to_string());
+ traffic.tool_failure = Some(ToolFailure {
+ failed: true,
+ detail: Some("traffic service unavailable".to_string()),
+ });
+ let mut answer = TranscriptMessage::assistant("72F and sunny.");
+ answer.request_id = Some("req-1".to_string());
+ answer.turn_usage = Some(TurnUsage {
+ provider: "anthropic".to_string(),
+ model: "claude-x".to_string(),
+ usage: MessageUsage {
+ input: 20,
+ output: 8,
+ cost_usd: 0.002,
+ ..MessageUsage::default()
+ },
+ ts: "2026-07-21T09:00:02Z".to_string(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration: 2,
+ });
+ seed_transcript(
+ &locator,
root_stem,
thread_id,
- &[
- r#"{"role":"system","content":"[tool-policy preamble] ..."}"#,
- r#"{"role":"user","content":"Current Date & Time: 2026-07-21 09:00:00 UTC\n\nWeather in NYC?","request_id":"req-1"}"#,
- r#"{"role":"assistant","content":"Checking.","provider":"anthropic","model":"claude-x","usage":{"input":10,"output":5,"cached_input":0,"cost_usd":0.001},"ts":"2026-07-21T09:00:01Z","reasoning_content":"call the tool","tool_calls":[{"id":"call-1","name":"get_weather","arguments":"{\"city\":\"NYC\"}"},{"id":"call-2","name":"get_traffic","arguments":"{\"city\":\"NYC\"}"}],"iteration":1,"request_id":"req-1"}"#,
- r#"{"role":"tool","content":"72F sunny","id":"call-1","request_id":"req-1"}"#,
- r#"{"role":"tool","content":"error: traffic service unavailable","id":"call-2","request_id":"req-1","failure":true,"failure_detail":"traffic service unavailable"}"#,
- r#"{"role":"assistant","content":"72F and sunny.","provider":"anthropic","model":"claude-x","usage":{"input":20,"output":8,"cached_input":0,"cost_usd":0.002},"ts":"2026-07-21T09:00:02Z","iteration":2,"request_id":"req-1"}"#,
- ],
+ "orchestrator",
+ None,
+ &[user, assistant, weather, traffic, answer],
);
// A sub-agent sibling sharing the root stem.
- seed_raw_transcript(
- workspace,
+ let mut subagent_answer = TranscriptMessage::assistant("sub work done");
+ subagent_answer.turn_usage = Some(TurnUsage {
+ provider: "anthropic".to_string(),
+ model: "claude-x".to_string(),
+ usage: MessageUsage {
+ input: 5,
+ output: 3,
+ ..MessageUsage::default()
+ },
+ ts: "2026-07-21T09:10:00Z".to_string(),
+ reasoning_content: None,
+ tool_calls: Vec::new(),
+ iteration: 1,
+ });
+ seed_transcript(
+ &locator,
&format!("{root_stem}__50_coder"),
thread_id,
- &[
- r#"{"role":"assistant","content":"sub work done","provider":"anthropic","model":"claude-x","usage":{"input":5,"output":3,"cached_input":0,"cost_usd":0.0},"ts":"2026-07-21T09:10:00Z","iteration":1}"#,
- ],
+ "coder",
+ Some("subagent"),
+ &[subagent_answer],
);
let (rpc_addr, rpc_join) = serve_on_ephemeral(build_core_http_router(false)).await;
diff --git a/tests/raw_coverage/composio_backend_tools_e2e.rs b/tests/raw_coverage/composio_backend_tools_e2e.rs
index 3acee73940..13c898e8a8 100644
--- a/tests/raw_coverage/composio_backend_tools_e2e.rs
+++ b/tests/raw_coverage/composio_backend_tools_e2e.rs
@@ -117,6 +117,7 @@ fn store_session_token(config: &Config) {
#[tokio::test]
async fn round20_backend_agent_tools_cover_markdown_filtering_and_errors() {
let _lock = env_lock_async().await;
+ let _storage = crate::HostStorage::install(&_lock);
let state = MockState::default();
let base = start_loopback(
Router::new()
@@ -218,6 +219,7 @@ async fn round20_backend_agent_tools_cover_markdown_filtering_and_errors() {
#[tokio::test]
async fn round20_composio_ops_cover_authorize_scopes() {
let _lock = env_lock_async().await;
+ let _storage = crate::HostStorage::install(&_lock);
let state = MockState::default();
let base = start_loopback(
Router::new()
diff --git a/tests/raw_coverage/composio_direct_tools_e2e.rs b/tests/raw_coverage/composio_direct_tools_e2e.rs
index 45462dfe54..9c6557f457 100644
--- a/tests/raw_coverage/composio_direct_tools_e2e.rs
+++ b/tests/raw_coverage/composio_direct_tools_e2e.rs
@@ -114,6 +114,7 @@ async fn setup_direct_config(base: &str) -> Harness {
#[tokio::test]
async fn round25_direct_mode_ops_use_loopback_factory_for_tools_connections_and_execute() {
let _lock = env_lock_async().await;
+ let _storage = crate::HostStorage::install(&_lock);
invalidate_connected_integrations_cache();
let state = MockState::default();