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(web_chat): bound open calls in the idle guard and keep stop replies in the turn's workspace
killbill6c9091f465cc
diff --git a/crates/openhuman-core/src/web_chat/turn_activity.rs b/crates/openhuman-core/src/web_chat/turn_activity.rsindex 65573441c3..e47d1c688c 100644--- a/crates/openhuman-core/src/web_chat/turn_activity.rs+++ b/crates/openhuman-core/src/web_chat/turn_activity.rs@@ -11,7 +11,8 @@//! * While a parent-scope model call (`IterationStarted` →//! `ModelCallCompleted`) or a tool call (`ToolCallStarted` →//! `ToolCallCompleted`) is open, the turn is never idle, however long the-//! call is silent. Those calls carry their own bounds: the harness per-model+//! call is silent, up to [`OPEN_CALL_EXPIRY`] (a lost completion event must+//! not hold the guard off for the rest of the turn). Those calls carry their own bounds: the harness per-model//! call ceiling and the tool's own `timeout_secs`, both under the harness//! turn ceiling. A silent provider retry (minutes) or a long shell build is//! in flight, not idle.@@ -29,7 +30,7 @@//! not counted as idle, and tests can drive it with a paused runtime.use std::borrow::Cow;-use std::collections::HashSet;+use std::collections::HashMap;use std::future::Future;use std::sync::{Arc, Mutex};use std::time::Duration;@@ -45,6 +46,14 @@ pub(crate) const DEFAULT_TURN_IDLE_SECS: u64 = 900;/// Environment override for the idle window, in seconds; `0` disables it.pub(crate) const TURN_IDLE_ENV: &str = "OPENHUMAN_WEB_TURN_IDLE_SECS";+/// How long a call may stay open without its completion event before the+/// record stops counting it as in flight. Completion events can be dropped+/// under sustained backpressure; without a bound one lost `ToolCallCompleted`+/// would hold the idle guard off for the rest of the turn. Twice the harness's+/// per-model-call ceiling (900s). A long shell call is unaffected: its progress+/// heartbeat (every 15s) keeps the turn active on its own.+const OPEN_CALL_EXPIRY: Duration = Duration::from_secs(1_800);+/// Longest the watchdog sleeps between checks while a call is in flight. A/// call that closes is followed by a full idle window measured from its close,/// so this only bounds how late the watchdog notices that.@@ -67,8 +76,10 @@ pub(crate) fn configured_idle_window() -> Option<Duration> {#[derive(Debug)]struct State {last_event: Instant,- open_tool_calls: HashSet<String>,- model_call_open: bool,+ /// Open tool calls by call id, with when each started.+ open_tool_calls: HashMap<String, Instant>,+ /// When the open parent model call started, if one is open.+ model_call_open: Option<Instant>,/// What the last event said the turn did, for the stop reply.last_step: Option<Cow<'static, str>>,turn_completed: bool,@@ -155,8 +166,8 @@ impl TurnActivity {Self {state: Arc::new(Mutex::new(State {last_event: Instant::now(),- open_tool_calls: HashSet::new(),- model_call_open: false,+ open_tool_calls: HashMap::new(),+ model_call_open: None,last_step: None,turn_completed: false,turn_config: None,@@ -170,27 +181,38 @@ impl TurnActivity {}/// Fold one progress event into the record.+ ///+ /// Completion events can be lost, so later events also close what they+ /// prove finished. The agent loop runs model call, then that call's tool+ /// round, then the next model call: a `ToolCallStarted` means the model+ /// call that requested it returned, and an `IterationStarted` means the+ /// previous tool round finished.pub(crate) fn observe(&self, event: &AgentProgress) {+ let now = Instant::now();let mut state = self.lock();- state.last_event = Instant::now();+ state.last_event = now;if let Some(step) = step_of(event) {state.last_step = Some(step);}match event {- AgentProgress::IterationStarted { .. } => state.model_call_open = true,+ AgentProgress::IterationStarted { .. } => {+ state.open_tool_calls.clear();+ state.model_call_open = Some(now);+ }AgentProgress::ModelCallCompleted {subagent_task_id: None,..- } => state.model_call_open = false,+ } => state.model_call_open = None,AgentProgress::ToolCallStarted { call_id, .. } => {- state.open_tool_calls.insert(call_id.clone());+ state.model_call_open = None;+ state.open_tool_calls.insert(call_id.clone(), now);}AgentProgress::ToolCallCompleted { call_id, .. } => {state.open_tool_calls.remove(call_id);}AgentProgress::TurnCompleted { .. } => {state.open_tool_calls.clear();- state.model_call_open = false;+ state.model_call_open = None;state.turn_completed = true;}_ => {}@@ -198,10 +220,14 @@ impl TurnActivity {}/// How long the turn has been idle as of `now`, or `None` while a model or- /// tool call is in flight.+ /// tool call is in flight. A call open longer than [`OPEN_CALL_EXPIRY`] no+ /// longer counts: its completion event was most likely lost.pub(crate) fn idle_for(&self, now: Instant) -> Option<Duration> {let state = self.lock();- if state.model_call_open || !state.open_tool_calls.is_empty() {+ let live = |started: &Instant| now.saturating_duration_since(*started) < OPEN_CALL_EXPIRY;+ if state.model_call_open.as_ref().is_some_and(live)+ || state.open_tool_calls.values().any(live)+ {return None;}Some(now.saturating_duration_since(state.last_event))diff --git a/crates/openhuman-core/src/web_chat/turn_activity_tests.rs b/crates/openhuman-core/src/web_chat/turn_activity_tests.rsindex 33401b03d7..7ed80b2e31 100644--- a/crates/openhuman-core/src/web_chat/turn_activity_tests.rs+++ b/crates/openhuman-core/src/web_chat/turn_activity_tests.rs@@ -90,7 +90,7 @@ async fn every_event_restarts_the_idle_clock() {async fn an_open_model_call_is_never_idle() {let activity = TurnActivity::new();activity.observe(&iteration_started());- tokio::time::advance(Duration::from_secs(3_000)).await;+ tokio::time::advance(Duration::from_secs(1_500)).await;assert_eq!(activity.idle_for(Instant::now()), None);activity.observe(&model_call_completed(None));assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));@@ -111,7 +111,7 @@ async fn open_tool_calls_are_never_idle() {let activity = TurnActivity::new();activity.observe(&tool_started("a"));activity.observe(&tool_started("b"));- tokio::time::advance(Duration::from_secs(3_000)).await;+ tokio::time::advance(Duration::from_secs(1_500)).await;activity.observe(&tool_completed("a"));assert_eq!(activity.idle_for(Instant::now()), None);activity.observe(&tool_completed("b"));@@ -162,7 +162,7 @@ async fn a_long_tool_call_holds_off_the_watchdog_until_it_closes() {let activity = TurnActivity::new();activity.observe(&tool_started("build"));let watchdog = tokio::spawn(idle_watchdog(activity.clone(), WINDOW));- tokio::time::sleep(Duration::from_secs(2_400)).await;+ tokio::time::sleep(Duration::from_secs(1_500)).await;assert!(!watchdog.is_finished());activity.observe(&tool_completed("build"));let idle = watchdog.await.expect("watchdog task");@@ -255,3 +255,60 @@ fn the_turn_context_is_what_the_turn_recorded() {assert!(Arc::ptr_eq(&seen.expect("config recorded"), &config));assert_eq!(locale.as_deref(), Some("de"));}++/// A lost `ToolCallCompleted` does not leave the call open: the next model+/// call proves the tool round finished.+#[tokio::test(start_paused = true)]+async fn the_next_model_call_closes_a_tool_whose_completion_was_lost() {+ let activity = TurnActivity::new();+ activity.observe(&tool_started("a"));+ // `tool_completed("a")` is dropped under backpressure.+ activity.observe(&iteration_started());+ activity.observe(&model_call_completed(None));+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++/// A lost `ModelCallCompleted` does not leave the model call open: the tool+/// call it requested proves it returned.+#[tokio::test(start_paused = true)]+async fn a_tool_call_closes_a_model_call_whose_completion_was_lost() {+ let activity = TurnActivity::new();+ activity.observe(&iteration_started());+ // `model_call_completed(None)` is dropped under backpressure.+ activity.observe(&tool_started("a"));+ activity.observe(&tool_completed("a"));+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++/// When a lost completion is the turn's last event, the call stops counting+/// as in flight after the expiry, so the idle guard still stops the turn.+#[tokio::test(start_paused = true)]+async fn a_call_left_open_by_a_lost_completion_expires() {+ let activity = TurnActivity::new();+ activity.observe(&tool_started("a"));+ // `tool_completed("a")` is dropped, and the turn then goes silent.+ tokio::time::advance(OPEN_CALL_EXPIRY - Duration::from_secs(1)).await;+ assert_eq!(activity.idle_for(Instant::now()), None);+ tokio::time::advance(Duration::from_secs(1)).await;+ assert_eq!(activity.idle_for(Instant::now()), Some(OPEN_CALL_EXPIRY));+ let idle = idle_watchdog(activity, WINDOW).await;+ assert!(idle >= WINDOW);+}++/// A long shell call keeps reporting progress, so it stays active past the+/// expiry of its open-call record.+#[tokio::test(start_paused = true)]+async fn a_long_call_that_reports_progress_stays_active_past_the_expiry() {+ let activity = TurnActivity::new();+ activity.observe(&tool_started("build"));+ let watchdog = tokio::spawn(idle_watchdog(activity.clone(), WINDOW));+ for _ in 0..(3_600 / 15) {+ tokio::time::sleep(Duration::from_secs(15)).await;+ activity.observe(&AgentProgress::ToolCallProgress {+ call_id: "build".into(),+ message: "running".into(),+ });+ }+ assert!(!watchdog.is_finished(), "an hour of progress beats");+ watchdog.abort();+}diff --git a/crates/openhuman-core/src/web_chat/turn_close.rs b/crates/openhuman-core/src/web_chat/turn_close.rsindex 4305bb0e06..7ccd39d7d9 100644--- a/crates/openhuman-core/src/web_chat/turn_close.rs+++ b/crates/openhuman-core/src/web_chat/turn_close.rs@@ -12,7 +12,9 @@//! [`CLOSE_TIMEOUT`]. The provider may be what stalled, so when that call//! fails, times out or returns nothing, a plain reply built from the same//! evidence is used instead. Either way the turn ends in an ordinary-//! delivered reply that is saved in the thread.+//! delivered reply that is saved in the thread. A turn that stopped before+//! resolving its own config has no workspace to write to and nothing to+//! summarize, so it ends in the guard's `turn_timeout` error instead.use std::time::Duration;@@ -21,7 +23,6 @@ use tinyagents_session::turn_state::{ToolTimelineStatus, TurnState};use tinyinference_llm::message::Message;use tinyinference_llm::model::ModelRequest;-use crate::config::rpc as config_rpc;use crate::inference::provider;use super::turn_activity::StuckPoint;@@ -306,23 +307,22 @@ async fn read_snapshot(}}-/// The reply that closes `turn`, or `None` when no configuration is available-/// (the caller then reports the stop as an error). The caller bounds the-/// whole call.+/// The reply that closes `turn`, or `None` when the turn stopped before it+/// resolved its own config (the caller then reports the stop as an error).+///+/// The reply is written to and read from the turn's own workspace only. A turn+/// that never resolved its config has no workspace of its own, and loading the+/// active profile instead could file the reply under a different user after a+/// credential switch. Such a turn also has nothing to summarize: it stopped+/// before the agent saw the request. The caller bounds the whole call.pub(crate) async fn close_reply(turn: StoppedTurn<'_>) -> Option<WebChatTaskResult> {- let config = match turn.config.clone() {- Some(config) => config,- // The turn stopped before it resolved its own config.- None => match config_rpc::load_config_with_timeout().await {- Ok(config) => std::sync::Arc::new(config),- Err(error) => {- log::warn!(- "{LOG_PREFIX} config load failed request_id={}: {error}",- turn.request_id- );- return None;- }- },+ let Some(config) = turn.config.clone() else {+ log::info!(+ "{LOG_PREFIX} turn stopped before resolving its config; reporting the stop \+ request_id={}",+ turn.request_id+ );+ return None;};let snapshot = read_snapshot(config.workspace_dir.clone(),diff --git a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rsindex 40db0932cf..3efce5de53 100644--- a/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests_session_and_concurrency_tests.rs@@ -304,12 +304,13 @@ async fn cancel_chat_cooperatively_stops_in_flight_turn() {/// wedged main agent stuck mid tool-call, or a delegated sub-agent that never/// returns (modeled here by the parked test block) — must still end in a/// terminal event, never an empty reply / an endless `inference_heartbeat`-/// stream until the socket dies. The web turn driver's wall-clock backstop fires,-/// tears the wedged future down cooperatively (its `Drop` guard flips well-/// before the 30s test sleep would elapse), and closes the turn with a reply-/// saying why it stopped and where it got stuck.+/// stream until the socket dies. The web turn driver's wall-clock backstop fires+/// and tears the wedged future down cooperatively (its `Drop` guard flips well+/// before the 30s test sleep would elapse). The block parks before the turn+/// resolves its config, so there is no workspace to write a closing reply to:+/// the turn ends in the graceful, retryable `turn_timeout` chat_error.#[tokio::test]-async fn wedged_turn_hits_wall_clock_backstop_and_is_closed_with_a_reply() {+async fn wedged_turn_hits_wall_clock_backstop_and_emits_turn_timeout_chat_error() {let _serial = FORCED_ERROR_TEST_LOCK.lock().await;// Panic-safe teardown of the process-global env override: if any assertion// below unwinds, this guard still clears `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` so@@ -336,21 +337,13 @@ async fn wedged_turn_hits_wall_clock_backstop_and_is_closed_with_a_reply() {.await.expect("turn should start");- let reply = timeout(+ let recv = timeout(Duration::from_secs(20),- terminal_reply(&mut rx, &request_id),+ terminal_event(&mut rx, &request_id),).await.expect("a wedged turn must still emit a terminal event (issue #4746)");- assert!(- reply.starts_with("I stopped this turn because it hit its time limit of 1 second"),- "{reply}"- );- assert!(reply.contains("before the agent started"), "{reply}");- assert!(- !reply.contains("openhuman_turn_wall_clock_timeout"),- "internal marker must not leak into user copy: {reply}"- );+ assert_turn_timeout(&recv);// The wedged future is torn down cooperatively when the backstop drops it// (the Drop guard flips), not left sleeping to its 30s test wall.@@ -361,11 +354,11 @@ async fn wedged_turn_hits_wall_clock_backstop_and_is_closed_with_a_reply() {}/// The idle guard ends a turn that emits no progress with nothing in flight,-/// well inside the wall-clock ceiling, and closes it with a reply that says-/// where it got stuck. The parked test block emits nothing, like a turn wedged-/// in session checkout.+/// well inside the wall-clock ceiling. The parked test block emits nothing and+/// parks before the turn resolves its config, like a turn wedged in session+/// checkout, so the turn ends in the graceful `turn_timeout` chat_error.#[tokio::test]-async fn silent_turn_hits_idle_guard_and_is_closed_with_a_reply() {+async fn silent_turn_hits_idle_guard_and_emits_turn_timeout_chat_error() {let _serial = FORCED_ERROR_TEST_LOCK.lock().await;let _env_guard =crate::config::test_env::EnvVarGuard::locked_set_async("OPENHUMAN_WEB_TURN_IDLE_SECS", "1")@@ -387,20 +380,13 @@ async fn silent_turn_hits_idle_guard_and_is_closed_with_a_reply() {.await.expect("turn should start");- let reply = timeout(+ let recv = timeout(Duration::from_secs(20),- terminal_reply(&mut rx, &request_id),+ terminal_event(&mut rx, &request_id),).await.expect("a silent turn must end in a terminal event");- assert!(- reply.starts_with("I stopped this turn because nothing happened for 1 second"),- "{reply}"- );- assert!(- reply.contains("It got stuck before the agent started"),- "{reply}"- );+ assert_turn_timeout(&recv);wait_for_flag(&block.dropped, "silent turn future dropped by idle guard").await;set_test_run_chat_task_block(None).await;@@ -642,22 +628,29 @@ async fn unscoped_cancel_stops_the_threads_detached_subagents() {assert!(joined.expect_err("child aborted").is_cancelled());}-/// The reply a stopped turn was closed with: the `chat_done` text for-/// `request_id`. A `chat_error` for it fails the test, since a stopped turn-/// must be closed with a reply.-async fn terminal_reply(+/// The terminal event (`chat_done` or `chat_error`) for `request_id`.+async fn terminal_event(rx: &mut tokio::sync::broadcast::Receiver<crate::web_chat::WebChannelEvent>,request_id: &str,-) -> String {+) -> crate::web_chat::WebChannelEvent {loop {let event = rx.recv().await.expect("event stream should stay open");- if event.request_id != request_id {- continue;- }- match event.event.as_str() {- "chat_done" => return event.full_response.unwrap_or_default(),- "chat_error" => panic!("stopped turn ended in chat_error: {:?}", event.message),- _ => {}+ if event.request_id == request_id+ && matches!(event.event.as_str(), "chat_done" | "chat_error")+ {+ return event;}}}++/// A graceful, retryable `turn_timeout` whose user copy hides the marker.+fn assert_turn_timeout(event: &crate::web_chat::WebChannelEvent) {+ assert_eq!(event.event, "chat_error", "{event:?}");+ assert_eq!(event.error_type.as_deref(), Some("turn_timeout"));+ assert_eq!(event.error_retryable, Some(true));+ let message = event.message.clone().unwrap_or_default();+ assert!(+ !message.contains("openhuman_turn_wall_clock_timeout"),+ "internal marker must not leak into user copy: {message}"+ );+}