Skip to content

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

Merge upstream/main into fix/web-turn-inactivity-guard

killbill7f50971ebcc4
diff --cc crates/openhuman-core/src/agent/turn_deadline.rs
index 3ebbdf0993,cb1ec2895e..9bea1fcbb0
--- a/crates/openhuman-core/src/agent/turn_deadline.rs
+++ b/crates/openhuman-core/src/agent/turn_deadline.rs
@@@ -8,10 -8,11 +8,11 @@@
//! `tinyagents::turn_policy`) was later than the backstop, so the harness
//! never got the chance to stop the turn itself.
//!
- //! This module is the single source of truth for the backstop and for the two
- //! points the harness derives from it:
+ //! The deadline value (`tinyagents_harness::turn_deadline::TurnDeadline`)
+ //! owns the two points the harness derives from the backstop; this module
+ //! keeps the host side (env override, task-local scope):
//!
-//! * **wind-down** (`backstop - min(120s, backstop/5)`, 780s by default): the
+//! * **wind-down** (`backstop - min(120s, backstop/5)`, 3480s by default): the
//! harness pauses the run at the next safe point, after a model call or a
//! tool result. The driver then writes the grounded close from the work
//! already in hand. The margin before the backstop pays for that close.
@@@ -21,14 -22,7 +22,15 @@@
//! typed `Timeout` before the backstop drops the turn.
//!
//! For every positive backstop, `wind_down < hard_stop < backstop`
--//! (see `turn_deadline_tests.rs`).
++//! (see the harness `turn_deadline_tests.rs`).
+//!
- //! The backstop defaults to the harness turn ceiling (3600s). It bounds a turn
++//! The web backstop defaults to [`DEFAULT_WEB_TURN_BACKSTOP_SECS`] (3600s, the
++//! harness turn ceiling), not the harness default of 900s. It bounds a turn
+//! that stays busy; it is not the hang detector. A turn that goes silent with
+//! no model or tool call in flight is ended much earlier by the web-turn idle
- //! guard (`web_chat::turn_activity`, 900s of inactivity by default). The
- //! backstop used to be 900s and did both jobs, so a turn that was working
- //! steadily was still wound down at 780s.
++//! guard (`web_chat::turn_activity`, 900s of inactivity by default). At 900s
++//! the backstop did both jobs, so a turn that was working steadily was wound
++//! down at 780s like a wedged one.
//!
//! The web-turn guard scopes the deadline on a task-local
//! ([`with_turn_deadline`]). The top-level session turn
@@@ -37,104 -31,30 +39,46 @@@
//! `None` and keep their previous behaviour.
use std::future::Future;
- use std::time::{Duration, Instant};
+ use std::time::Duration;
- /// Default outer wall-clock backstop for one web-chat turn, in seconds: the
- /// harness's own default turn ceiling (`DEFAULT_AGENT_TURN_TIMEOUT_SECS`).
- pub const DEFAULT_TURN_BACKSTOP_SECS: u64 = 3_600;
-use tinyagents_harness::turn_deadline::{parse_backstop, TurnDeadline};
++use tinyagents_harness::turn_deadline::TurnDeadline;
/// Environment override for the backstop, in seconds; `0` disables it.
pub const TURN_BACKSTOP_ENV: &str = "OPENHUMAN_WEB_TURN_TIMEOUT_SECS";
- /// Upper bound on the gap between wind-down and the backstop. It has to cover
- /// the tool round already in flight plus the grounded close (one model call,
- /// its verification, and at most one repair).
- const WIND_DOWN_MARGIN: Duration = Duration::from_secs(120);
+ /// Time kept back from the post-loop grounded close so the turn can commit and
+ /// emit its reply before the backstop drops it.
+ const CLOSE_RESERVE: Duration = Duration::from_secs(10);
+
+ /// How long the post-loop grounded close may run as of `now`: the backstop
+ /// remainder minus [`CLOSE_RESERVE`], zero once that has passed (#7716).
+ /// Host-side until the harness `TurnDeadline` grows the same accessor.
+ pub fn close_budget(deadline: &TurnDeadline, now: std::time::Instant) -> Duration {
+ deadline
+ .backstop()
+ .saturating_sub(deadline.elapsed_at(now))
+ .saturating_sub(CLOSE_RESERVE)
+ }
- /// Upper bound on the gap between the harness hard stop and the backstop.
- const HARD_STOP_MARGIN: Duration = Duration::from_secs(60);
++/// Default web-turn backstop, in seconds: the harness's own default turn
++/// ceiling (`DEFAULT_AGENT_TURN_TIMEOUT_SECS`). The harness default
++/// (`tinyagents_harness::turn_deadline::DEFAULT_TURN_BACKSTOP_SECS`, 900s)
++/// assumes the backstop is also the hang detector; on the web channel the idle
++/// guard is.
++pub const DEFAULT_WEB_TURN_BACKSTOP_SECS: u64 = 3_600;
+
+/// Pure core of [`configured_backstop`]: an absent or unparseable value falls
- /// back to [`DEFAULT_TURN_BACKSTOP_SECS`]. `0` disables the backstop (`None`).
- pub fn parse_backstop(env_value: Option<&str>) -> Option<Duration> {
++/// back to [`DEFAULT_WEB_TURN_BACKSTOP_SECS`]; `0` disables the backstop.
++pub fn parse_web_backstop(env_value: Option<&str>) -> Option<Duration> {
+ let secs = env_value
+ .and_then(|v| v.trim().parse::<u64>().ok())
- .unwrap_or(DEFAULT_TURN_BACKSTOP_SECS);
++ .unwrap_or(DEFAULT_WEB_TURN_BACKSTOP_SECS);
+ (secs > 0).then(|| Duration::from_secs(secs))
+}
+
/// The backstop in force for this process (env [`TURN_BACKSTOP_ENV`]).
pub fn configured_backstop() -> Option<Duration> {
-- parse_backstop(std::env::var(TURN_BACKSTOP_ENV).ok().as_deref())
- }
-
- /// One turn's backstop, anchored at the instant the backstop started counting.
- #[derive(Clone, Copy, Debug, PartialEq, Eq)]
- pub struct TurnDeadline {
- started: Instant,
- backstop: Duration,
- }
-
- impl TurnDeadline {
- /// A deadline whose backstop started at `started`.
- pub fn new(started: Instant, backstop: Duration) -> Self {
- Self { started, backstop }
- }
-
- /// A deadline whose backstop starts counting now.
- pub fn starting_now(backstop: Duration) -> Self {
- Self::new(Instant::now(), backstop)
- }
-
- /// The outer backstop, measured from [`Self::started`].
- pub fn backstop(&self) -> Duration {
- self.backstop
- }
-
- /// When the backstop started counting.
- pub fn started(&self) -> Instant {
- self.started
- }
-
- /// Elapsed budget after which the harness winds the turn down.
- pub fn wind_down_after(&self) -> Duration {
- self.backstop
- .saturating_sub(WIND_DOWN_MARGIN.min(self.backstop / 5))
- }
-
- /// Elapsed budget at which the harness stops the turn itself.
- pub fn hard_stop_after(&self) -> Duration {
- self.backstop
- .saturating_sub(HARD_STOP_MARGIN.min(self.backstop / 10))
- }
-
- /// Time spent since the backstop started, as of `now`.
- pub fn elapsed_at(&self, now: Instant) -> Duration {
- now.saturating_duration_since(self.started)
- }
-
- /// Whether the wind-down point has passed as of `now`.
- pub fn should_wind_down(&self, now: Instant) -> bool {
- self.elapsed_at(now) >= self.wind_down_after()
- }
-
- /// Time left until the hard stop as of `now` (zero once it has passed).
- pub fn hard_stop_remaining(&self, now: Instant) -> Duration {
- self.hard_stop_after().saturating_sub(self.elapsed_at(now))
- }
-
- /// Clamp a configured harness wall-clock ceiling (`None` means unbounded)
- /// so it ends at the hard stop, never later. Never returns `None`: a turn
- /// under a backstop is bounded whether or not the ceiling is configured.
- /// Floors at 1 ms because a zero ceiling would read as "no time at all".
- pub fn clamp_wall_clock_ms(&self, configured_ms: Option<u64>, now: Instant) -> Option<u64> {
- let remaining_ms = self
- .hard_stop_remaining(now)
- .as_millis()
- .min(u128::from(u64::MAX)) as u64;
- let remaining_ms = remaining_ms.max(1);
- Some(configured_ms.map_or(remaining_ms, |ms| ms.min(remaining_ms)))
- }
++ parse_web_backstop(std::env::var(TURN_BACKSTOP_ENV).ok().as_deref())
}
tokio::task_local! {
diff --cc crates/openhuman-core/src/agent/turn_deadline_tests.rs
index 9c0db06b8c,c8e25996e9..f69eaa26c1
--- a/crates/openhuman-core/src/agent/turn_deadline_tests.rs
+++ b/crates/openhuman-core/src/agent/turn_deadline_tests.rs
@@@ -1,101 -1,20 +1,39 @@@
use super::*;
++use tinyagents_harness::turn_deadline::parse_backstop;
+ use std::time::Instant;
#[test]
- fn default_deadlines_are_3480s_3540s_3600s() {
- let deadline = TurnDeadline::starting_now(Duration::from_secs(DEFAULT_TURN_BACKSTOP_SECS));
- assert_eq!(deadline.wind_down_after(), Duration::from_secs(3_480));
- assert_eq!(deadline.hard_stop_after(), Duration::from_secs(3_540));
- assert_eq!(deadline.backstop(), Duration::from_secs(3_600));
- }
-
- /// The ordering production was missing: the harness must stop (and before
- /// that wind down) strictly before the backstop drops the turn, for every
- /// backstop an operator can configure.
- #[test]
- fn wind_down_precedes_hard_stop_precedes_backstop_for_every_backstop() {
- for secs in [
- 1_u64, 2, 5, 10, 30, 60, 120, 300, 599, 600, 601, 900, 1_200, 3_600, 86_400,
- ] {
- let deadline = TurnDeadline::starting_now(Duration::from_secs(secs));
- assert!(
- deadline.wind_down_after() < deadline.hard_stop_after(),
- "backstop {secs}s: wind-down {:?} must precede hard stop {:?}",
- deadline.wind_down_after(),
- deadline.hard_stop_after()
- );
- assert!(
- deadline.hard_stop_after() < deadline.backstop(),
- "backstop {secs}s: hard stop {:?} must precede backstop",
- deadline.hard_stop_after()
- );
- }
- }
-
- /// The harness ceiling (default 3600s) is always clamped below the backstop,
- /// and so is an explicit opt-out (`None`).
- #[test]
- fn harness_wall_clock_is_always_clamped_below_the_backstop() {
- let backstop = Duration::from_secs(DEFAULT_TURN_BACKSTOP_SECS);
- let now = Instant::now();
- let deadline = TurnDeadline::new(now, backstop);
- let backstop_ms = backstop.as_millis() as u64;
- // The harness's default turn ceiling (`DEFAULT_AGENT_TURN_TIMEOUT_SECS`);
- // `deadline_wind_down_tests.rs` pins that constant against this module.
- let harness_default_ms = 3_600_000;
-
- let clamped = deadline
- .clamp_wall_clock_ms(Some(harness_default_ms), now)
- .expect("clamped ceiling");
- assert_eq!(clamped, 3_540_000);
- assert!(clamped < backstop_ms);
-
- let unbounded = deadline.clamp_wall_clock_ms(None, now).expect("bounded");
- assert_eq!(unbounded, 3_540_000);
-
- // A configured ceiling that is already tighter is kept.
+ fn parse_backstop_defaults_and_disables() {
+ assert_eq!(parse_backstop(None), Some(Duration::from_secs(900)));
assert_eq!(
- deadline.clamp_wall_clock_ms(Some(10_000), now),
- Some(10_000)
+ parse_backstop(Some("garbage")),
+ Some(Duration::from_secs(900))
);
- }
-
- #[test]
- fn clamp_measures_the_remaining_budget_from_the_backstop_start() {
- let now = Instant::now();
- let started = now - Duration::from_secs(800);
- let deadline = TurnDeadline::new(started, Duration::from_secs(900));
assert_eq!(
- deadline.clamp_wall_clock_ms(Some(3_600_000), now),
- Some(40_000)
+ parse_backstop(Some(" 120 ")),
+ Some(Duration::from_secs(120))
);
- // Past the hard stop the ceiling floors at 1 ms rather than 0.
- let late = TurnDeadline::new(now - Duration::from_secs(899), Duration::from_secs(900));
- assert_eq!(late.clamp_wall_clock_ms(Some(3_600_000), now), Some(1));
- }
-
- #[test]
- fn should_wind_down_flips_at_the_wind_down_point() {
- let now = Instant::now();
- let fresh = TurnDeadline::new(now - Duration::from_secs(779), Duration::from_secs(900));
- assert!(!fresh.should_wind_down(now));
- let due = TurnDeadline::new(now - Duration::from_secs(780), Duration::from_secs(900));
- assert!(due.should_wind_down(now));
+ assert_eq!(parse_backstop(Some("0")), None);
}
++/// The web backstop defaults to the harness turn ceiling, not the harness's
++/// 900s, and keeps the env override and the `0` opt-out.
+#[test]
- fn parse_backstop_defaults_and_disables() {
- assert_eq!(parse_backstop(None), Some(Duration::from_secs(3_600)));
- assert_eq!(
- parse_backstop(Some("garbage")),
- Some(Duration::from_secs(3_600))
- );
++fn web_backstop_defaults_to_an_hour_and_keeps_the_override() {
++ let hour = Some(Duration::from_secs(DEFAULT_WEB_TURN_BACKSTOP_SECS));
++ assert_eq!(DEFAULT_WEB_TURN_BACKSTOP_SECS, 3_600);
++ assert_eq!(parse_web_backstop(None), hour);
++ assert_eq!(parse_web_backstop(Some("garbage")), hour);
+ assert_eq!(
- parse_backstop(Some(" 120 ")),
++ parse_web_backstop(Some(" 120 ")),
+ Some(Duration::from_secs(120))
+ );
- assert_eq!(parse_backstop(Some("0")), None);
++ assert_eq!(parse_web_backstop(Some("0")), None);
++ let deadline = TurnDeadline::starting_now(hour.unwrap());
++ assert_eq!(deadline.wind_down_after(), Duration::from_secs(3_480));
++ assert_eq!(deadline.hard_stop_after(), Duration::from_secs(3_540));
+}
+
#[tokio::test]
async fn task_local_scope_is_visible_inside_and_absent_outside() {
assert!(current().is_none());
diff --cc crates/openhuman-core/src/media/generation/README.md
index c4e946cb35,c4e946cb35..0ec98e541b
--- a/crates/openhuman-core/src/media/generation/README.md
+++ b/crates/openhuman-core/src/media/generation/README.md
@@@ -23,7 -23,7 +23,7 @@@ split across three layers, each with a
| [`provider.rs`](./provider.rs) | `managed_generators`: builds `MediaGenerators { image, video }` against the managed backend, or returns `None` when no backend transport is installed. Wraps each generator in a `Guard` that enforces local-only privacy mode and the egress disclosure before a request leaves the device, and the managed-credit budget gate before a billed submit. |
| [`tools.rs`](./tools.rs) | `build_media_tools`: registers `media_generate_image`, `media_generate_video`, and `media_list_models` as `Tool` implementations over the generators from `provider.rs`. Also defines `reference_policy`, which restricts local reference files (for image edits or video first/last frames) to the action directory or workspace directory. |
| [`artifact_tool.rs`](./artifact_tool.rs) | `MediaArtifactTool`: wraps a generation tool so every file it saves is also tracked as an OpenHuman artifact, following the same `create_artifact` / `finalize_artifact` pattern the document and presentation tools use. Runs the inner tool unchanged, then files each reported output and stamps an `artifact_id` (or `artifact_error`) onto its entry. |
--| [`progress.rs`](./progress.rs) | Progress for a long generation call: a heartbeat every 15s through `ToolRunContext::report_progress` while the inner tool runs, carrying the video job state the `WaitPolicy::progress` observer records on each poll. The harness emits these as `AgentEvent::ToolProgressDetail`; the host does not yet project that event onto the web channel, so the chat UI does not show them yet. |
++| [`progress.rs`](./progress.rs) | Progress for a long generation call: a heartbeat every 15s through `ToolRunContext::report_progress` while the inner tool runs, carrying the video job state the `WaitPolicy::progress` observer records on each poll. The harness emits these as `AgentEvent::ToolProgressDetail`, which the host publishes on the web channel as `tool_progress`; the chat UI does not render it yet. |
| [`mod.rs`](./mod.rs) | Re-exports: `MediaArtifactTool`, `managed_generators`, `MediaGenerators`, `OPENROUTER_PROXY_PATH`, `build_media_tools`, `media_tools_from`, `MediaListModelsTool`, and the three tool-name constants. |
## Key types
diff --cc crates/openhuman-core/src/media/generation/progress.rs
index bece22f269,bece22f269..e6d929d52f
--- a/crates/openhuman-core/src/media/generation/progress.rs
+++ b/crates/openhuman-core/src/media/generation/progress.rs
@@@ -14,9 -14,9 +14,9 @@@
//! task-local [`with_progress_heartbeat`] scopes around the call (the poll
//! loop runs inline on the tool's task), and the next heartbeat includes it.
//!
--//! The host does not yet project `ToolProgressDetail` onto the web channel, so
--//! these updates reach the harness event stream and its subscribers but not the
--//! chat UI; see the module README.
++//! The host projects `ToolProgressDetail` onto the web channel as a
++//! `tool_progress` event for the parent call
++//! (`agent::tinyagents::observability`); the chat UI does not render it yet.
use std::sync::{Arc, Mutex};
use std::time::Duration;
diff --cc crates/openhuman-core/src/sandbox/shell_exec.rs
index dd89a770ec,554b4172d6..e2d27c37c4
--- a/crates/openhuman-core/src/sandbox/shell_exec.rs
+++ b/crates/openhuman-core/src/sandbox/shell_exec.rs
@@@ -110,9 -108,18 +110,18 @@@ pub(crate) async fn run(config: &Config
timeout_ms = run.timeout.as_millis() as u64,
"[sandbox:shell] starting native shell through TinyBox"
);
- tokio::spawn(async move { run_owned(&config, run, meter).await })
- .await
- .map_err(|_| anyhow::anyhow!("TinyBox shell worker did not finish"))?
+ // A cancelled turn drops this wait mid-command. The worker then cancels
+ // the command (`_caller` closes `abandoned`) and holds the turn's
+ // cleanup open until TinyBox has stopped it, so an awaited turn
+ // cancellation is acknowledged only after the command is gone.
+ let hold = tinytools_std::timeout::ProcessCleanup::hold();
+ let (_caller, abandoned) = tokio::sync::oneshot::channel::<std::convert::Infallible>();
+ crate::core::runtime::spawn_scoped(async move {
+ let _hold = hold;
- run_owned(&config, run, abandoned).await
++ run_owned(&config, run, abandoned, meter).await
+ })
+ .await
+ .map_err(|_| anyhow::anyhow!("TinyBox shell worker did not finish"))?
}
#[cfg(not(feature = "modules"))]
{
@@@ -125,7 -132,7 +134,8 @@@
async fn run_owned(
config: &Config,
run: NativeShellRun,
+ abandoned: tokio::sync::oneshot::Receiver<std::convert::Infallible>,
+ meter: Option<super::shell_progress::ShellOutputMeter>,
) -> anyhow::Result<SandboxExecResult> {
let resource = tinybox::reserve(config, contract::ReserveRequest::Resource)
.await
@@@ -161,7 -168,7 +171,7 @@@
let process = tinybox::start_native_shell_exec(config, request)
.await
.map_err(|_| anyhow::anyhow!("TinyBox could not start the command process"))?;
- collect_process(config, process, timeout, meter).await
- collect_process(config, process, timeout, abandoned).await
++ collect_process(config, process, timeout, abandoned, meter).await
}
.await;
let close = tinybox::close(config, resource).await;
@@@ -210,9 -217,10 +220,11 @@@ async fn collect_process
config: &Config,
process: contract::ProcessRef,
timeout: Duration,
+ mut abandoned: tokio::sync::oneshot::Receiver<std::convert::Infallible>,
+ meter: Option<super::shell_progress::ShellOutputMeter>,
) -> anyhow::Result<SandboxExecResult> {
use contract::{ExecutionFailure, ExecutionState, OutputStream};
+ use tokio::sync::oneshot::error::TryRecvError;
let deadline = tokio::time::Instant::now() + timeout;
let mut cursor = 0;
diff --cc crates/openhuman-core/src/web_chat/ops/turn_guards.rs
index d26614f74c,c194ec5d85..3ca45de4b1
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
@@@ -102,86 -75,34 +102,86 @@@ async fn drive_turn_with_deadline<F>
where
F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
{
- match deadline {
+ let activity = TurnActivity::new();
+ // The turn future is boxed: it is very large, and the scope wrappers would
+ // otherwise hold it inline again and overflow the worker stack.
+ let turn = turn_activity::with_turn_activity(activity.clone(), Box::pin(fut));
+ let bounded_turn = async move {
+ let Some(d) = deadline else {
+ return Ok(turn.await);
+ };
// Scope the deadline on the task so the session turn hands it to the
- // harness (`agent::turn_deadline`), which winds down before `d`. The
- // turn future is boxed: it is very large, and the scope wrapper would
- // otherwise hold it inline a second time and overflow the worker stack.
- Some(d) => match tokio::time::timeout(
- d,
- crate::agent::turn_deadline::with_turn_deadline(
- Some(tinyagents_harness::turn_deadline::TurnDeadline::starting_now(d)),
- Box::pin(fut),
- ),
- )
- .await
- {
- Ok(res) => res,
- Err(_elapsed) => {
- log::warn!(
- "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \
- (the harness wind-down did not close the turn in time); emitting graceful \
- turn_timeout chat_error (issue #4746)",
- d.as_secs()
- );
- Err(super::super::web_errors::turn_timeout_error_message(
- d.as_secs(),
- ))
- }
+ // harness (`agent::turn_deadline`), which winds down before `d`.
- let deadline = crate::agent::turn_deadline::TurnDeadline::starting_now(d);
++ let deadline = tinyagents_harness::turn_deadline::TurnDeadline::starting_now(d);
+ let scoped = crate::agent::turn_deadline::with_turn_deadline(Some(deadline), turn);
+ tokio::time::timeout(d, scoped)
+ .await
+ .map_err(|_elapsed| Stop::Ceiling(d))
+ };
+ let watched = activity.clone();
+ let watchdog = async move {
+ match idle_window {
+ Some(window) => turn_activity::idle_watchdog(watched, window).await,
+ None => std::future::pending().await,
+ }
+ };
+ let stop = tokio::select! {
+ biased;
+ res = bounded_turn => match res {
+ Ok(res) => return res,
+ Err(stop) => stop,
},
- None => fut.await,
+ idle = watchdog => Stop::Idle(idle),
+ };
+ let stuck = activity.stuck_point();
+ let (cause, fallback) = match stop {
+ Stop::Ceiling(d) => {
+ log::warn!(
+ "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \
+ (the harness wind-down did not close the turn in time); stuck={stuck:?} \
+ (issue #4746)",
+ d.as_secs()
+ );
+ (
+ StopCause::Ceiling(d),
+ super::super::web_errors::turn_timeout_error_message(d.as_secs()),
+ )
+ }
+ Stop::Idle(idle) => {
+ log::warn!(
+ "[web-channel] turn idle guard fired: no progress for {}s with no model or tool \
+ call in flight; stuck={stuck:?}",
+ idle.as_secs()
+ );
+ (
+ StopCause::Idle(idle),
+ super::super::web_errors::turn_idle_error_message(idle.as_secs()),
+ )
+ }
+ };
+ let Some(ids) = ids else {
+ return Err(fallback);
+ };
+ let (config, locale) = activity.turn_context();
+ let stopped = StoppedTurn {
+ thread_id: &ids.thread_id,
+ request_id: &ids.request_id,
+ cause,
+ stuck,
+ config,
+ locale,
+ };
+ let close = super::super::turn_close::close_reply(stopped);
+ match tokio::time::timeout(CLOSE_REPLY_BUDGET, close).await {
+ Ok(Some(reply)) => Ok(reply),
+ Ok(None) => Err(fallback),
+ Err(_) => {
+ log::warn!(
+ "[web-channel] closing the stopped turn took over {}s; reporting turn_timeout",
+ CLOSE_REPLY_BUDGET.as_secs()
+ );
+ Err(fallback)
+ }
}
}
@@@ -206,17 -127,11 +206,17 @@@ pub(crate) async fn run_turn_under_canc
where
F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
{
+ let ids = approval_ctx.request_id.clone().map(|request_id| TurnIds {
+ thread_id: approval_ctx.thread_id.clone(),
+ request_id,
+ });
- tokio::select! {
- biased;
- _ = cancel_token.cancelled() => None,
- res = drive_turn_with_deadline(
- resolve_web_turn_deadline().await,
+ let deadline = resolve_web_turn_deadline().await;
+ run_until_stopped(
+ cancel_token,
+ drive_turn_with_deadline(
+ deadline,
+ turn_activity::configured_idle_window(),
+ ids,
crate::agent::turn_origin::with_origin(
origin,
crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),
diff --cc crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
index b557c8755c,6dcc9c030c..c917cdd76a
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
@@@ -59,66 -59,53 +59,117 @@@ async fn backstop_firing_yields_a_class
assert!(!classified.message.trim().is_empty());
}
+fn text_delta() -> crate::agent::progress::AgentProgress {
+ crate::agent::progress::AgentProgress::TextDelta {
+ delta: "x".into(),
+ iteration: 1,
+ }
+}
+
+const IDLE: Option<Duration> = Some(Duration::from_secs(900));
+const CEILING: Option<Duration> = Some(Duration::from_secs(3_600));
+
+/// A turn that keeps emitting progress runs past the old 900s backstop: the
+/// idle guard restarts on every event and the backstop is now the 3600s
+/// ceiling.
+#[tokio::test(start_paused = true)]
+async fn a_turn_that_keeps_progressing_outlives_the_idle_window() {
+ let res = drive_turn_with_deadline(CEILING, IDLE, None, async {
+ let activity = super::super::super::turn_activity::current().expect("activity scoped");
+ for _ in 0..90 {
+ tokio::time::sleep(Duration::from_secs(17)).await;
+ activity.observe(&text_delta());
+ }
+ Ok(result("done after 25 minutes"))
+ })
+ .await
+ .expect("idle guard must not fire on a progressing turn");
+ assert_eq!(res.full_response, "done after 25 minutes");
+}
+
+/// A turn that goes silent with nothing in flight ends after the idle window,
+/// long before the ceiling, with the classified `turn_timeout` error.
+#[tokio::test(start_paused = true)]
+async fn a_silent_turn_ends_after_the_idle_window() {
+ let started = tokio::time::Instant::now();
+ let err = drive_turn_with_deadline(CEILING, IDLE, None, async {
+ std::future::pending::<()>().await;
+ Ok(result("never"))
+ })
+ .await
+ .expect_err("idle guard fires");
+ let waited = started.elapsed();
+ assert!(waited >= Duration::from_secs(900) && waited < Duration::from_secs(3_600));
+ assert!(err.contains("no progress for"), "{err}");
+ assert!(super::super::super::web_errors::is_outer_backstop_timeout(
+ &err
+ ));
+ let classified = super::super::super::web_errors::classify_inference_error(&err);
+ assert_eq!(classified.error_type, "turn_timeout");
+}
+
+/// A turn that stays busy forever is still bounded by the fixed ceiling.
+#[tokio::test(start_paused = true)]
+async fn a_turn_busy_past_the_ceiling_hits_the_backstop() {
+ let err = drive_turn_with_deadline(CEILING, IDLE, None, async {
+ let activity = super::super::super::turn_activity::current().expect("activity scoped");
+ loop {
+ tokio::time::sleep(Duration::from_secs(30)).await;
+ activity.observe(&text_delta());
+ }
+ })
+ .await
+ .expect_err("backstop fires");
+ assert!(err.contains("3600s wall-clock budget"), "{err}");
+}
++
+ /// A Stop fires the turn's own session cancellation and lets the turn finish,
+ /// so the session runtime can persist the stopped turn's rounds (#7715). The
+ /// turn's result is still discarded: the caller unwinds as a cancel.
+ #[tokio::test]
+ async fn stop_fires_the_session_cancellation_and_lets_the_turn_unwind() {
+ let cancel = CancellationToken::new();
+ let unwound = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
+ let unwound_in_turn = unwound.clone();
+ let turn = run_until_stopped(cancel.clone(), async move {
+ crate::agent::host_overrides::current_cancellation()
+ .cancelled()
+ .await;
+ unwound_in_turn.store(true, std::sync::atomic::Ordering::SeqCst);
+ Ok::<_, String>(result("persisted partial"))
+ });
+ let stop = async {
+ tokio::task::yield_now().await;
+ cancel.cancel();
+ // A double Stop is a no-op, not a second unwind.
+ cancel.cancel();
+ };
+ let (res, ()) = tokio::join!(turn, stop);
+ assert!(res.is_none(), "a stopped turn reports a cancel");
+ assert!(
+ unwound.load(std::sync::atomic::Ordering::SeqCst),
+ "the turn observed its session cancellation and ran to completion"
+ );
+ }
+
+ /// A turn that ignores its session cancellation is dropped once the grace
+ /// runs out, so a Stop can never hang on a stuck turn.
+ #[tokio::test(start_paused = true)]
+ async fn stop_drops_a_turn_that_ignores_cancellation_after_the_grace() {
+ let cancel = CancellationToken::new();
+ cancel.cancel();
+ let started = tokio::time::Instant::now();
+ let res = run_until_stopped(cancel, std::future::pending::<()>()).await;
+ assert!(res.is_none());
+ assert!(started.elapsed() >= STOPPED_TURN_PERSIST_GRACE);
+ }
+
+ /// Without a Stop the turn's own result comes back.
+ #[tokio::test]
+ async fn unstopped_turn_returns_its_result() {
+ let res = run_until_stopped(CancellationToken::new(), async {
+ Ok::<_, String>(result("answer"))
+ })
+ .await;
+ assert_eq!(res.expect("not stopped").unwrap().full_response, "answer");
+ }
diff --cc crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
index 17c1c83922,864a380cc4..919f352649
--- a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
@@@ -740,6 -746,3 +746,5 @@@ async fn hold_text_stream_suppresses_te
Some("Let me check the release notes for you first.")
);
}
-
+#[path = "progress_bridge_tool_progress_tests.rs"]
+mod tool_progress_tests;
diff --cc crates/openhuman-core/src/web_chat/run_task.rs
index f36d6972e0,6e3eea847f..a2bf48a1aa
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@@ -114,17 -113,12 +113,17 @@@ pub(crate) async fn run_chat_task
// `action_dir`. Applied before checkout so the session agent, its security
// policy (which grants `action_dir` as a trusted root) and its tools are
// all built on the thread's folder.
- if let Some(dir) =
- crate::threads::ops::thread_working_dir(config.workspace_dir.clone(), thread_id).await?
- {
+ let thread_dir =
+ crate::threads::ops::thread_working_dir(config.workspace_dir.clone(), thread_id).await?;
+ if let Some(dir) = &thread_dir {
log::debug!("[web-channel] thread working folder applied thread_id={thread_id}");
- config.action_dir = dir;
+ config.action_dir = dir.clone();
}
+ // A guard that stops this turn closes it from this turn's own config and
+ // reply language, not from whatever profile is active when it fires.
+ if let Some(activity) = super::turn_activity::current() {
+ activity.remember_turn(std::sync::Arc::new(config.clone()), locale.clone());
+ }
let model_override = normalize_model_override(model_override);
// The cached session (or a cold-boot resumed one) is the thread's single
// live history; every turn on the thread checks it out through this path.
diff --cc crates/openhuman-core/src/web_chat/turn_activity.rs
index ccfaea8b9c,0000000000..958e098836
mode 100644,000000..100644
--- a/crates/openhuman-core/src/web_chat/turn_activity.rs
+++ b/crates/openhuman-core/src/web_chat/turn_activity.rs
@@@ -1,294 -1,0 +1,294 @@@
+//! Inactivity tracking for one web-chat turn.
+//!
+//! The web-turn guard (`ops::turn_guards`) used to drop a turn a fixed 900s
+//! after it started, whether or not the turn was still working. A turn that
+//! streamed a model reply or a tool result every few seconds died exactly as a
+//! wedged one did. The guard exists to catch the wedged turn, so it now asks a
+//! narrower question: has the turn been **silent with nothing in flight** for
+//! the idle window?
+//!
+//! * Every [`AgentProgress`] event the turn emits restarts the idle clock.
+//! * 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 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.
+//! * A tool approval parks before `ToolCallStarted`, so it counts as silence.
+//! It is bounded by the approval TTL (600s by default), below the default
+//! idle window.
+//!
+//! What remains idle is time no other bound covers: session checkout before
+//! the run, the persistence plumbing after it, or a harness that went silent
+//! with no call open. The fixed total ceiling still exists (the backstop in
+//! `agent::turn_deadline`) and still anchors the harness wind-down; it no
+//! longer doubles as the hang detector.
+//!
+//! The clock is [`tokio::time::Instant`], so time the machine spends asleep is
+//! not counted as idle, and tests can drive it with a paused runtime.
+
+use std::borrow::Cow;
+use std::collections::HashSet;
+use std::future::Future;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use tokio::sync::mpsc;
+use tokio::time::Instant;
+
+use crate::agent::progress::AgentProgress;
+
+/// Default idle window for a web-chat turn, in seconds.
+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";
+
+/// 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.
+const IN_FLIGHT_RECHECK: Duration = Duration::from_secs(15);
+
+/// Pure core of [`configured_idle_window`]: an absent or unparseable value
+/// falls back to [`DEFAULT_TURN_IDLE_SECS`]; `0` disables the idle guard.
+pub(crate) fn parse_idle_window(env_value: Option<&str>) -> Option<Duration> {
+ let secs = env_value
+ .and_then(|v| v.trim().parse::<u64>().ok())
+ .unwrap_or(DEFAULT_TURN_IDLE_SECS);
+ (secs > 0).then(|| Duration::from_secs(secs))
+}
+
+/// The idle window in force for this process (env [`TURN_IDLE_ENV`]).
+pub(crate) fn configured_idle_window() -> Option<Duration> {
+ parse_idle_window(std::env::var(TURN_IDLE_ENV).ok().as_deref())
+}
+
+#[derive(Debug)]
+struct State {
+ last_event: Instant,
+ open_tool_calls: HashSet<String>,
+ model_call_open: bool,
+ /// What the last event said the turn did, for the stop reply.
+ last_step: Option<Cow<'static, str>>,
+ turn_completed: bool,
+ /// The config and reply locale the turn itself resolved, so a stop reply
+ /// is written to the turn's own workspace and in its language.
+ turn_config: Option<Arc<crate::config::Config>>,
+ locale: Option<String>,
+}
+
+/// Where a turn was when it went silent, for the reply that closes it.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum StuckPoint {
+ /// No progress event at all: the turn never got past session setup.
+ BeforeRun,
+ /// The agent loop was between steps; `after` names its last step.
+ BetweenSteps { after: String },
+ /// The agent loop had finished; the reply was being saved or delivered.
+ AfterRun,
+}
+
+impl StuckPoint {
+ /// One plain-language clause naming where the turn stopped.
+ pub(crate) fn describe(&self) -> String {
+ match self {
+ Self::BeforeRun => {
+ "before the agent started: the turn never got past setting up the chat \
+ session"
+ .to_string()
+ }
+ Self::BetweenSteps { after } => {
+ format!("between steps: {after}, and the agent's next step never started")
+ }
+ Self::AfterRun => {
+ "after the agent finished, while its reply was being saved".to_string()
+ }
+ }
+ }
+}
+
+/// The step an event reports, as a clause for [`StuckPoint::BetweenSteps`].
+/// `None` for bookkeeping (cost, usage, captured content) that says nothing
+/// about what the turn was doing.
+fn step_of(event: &AgentProgress) -> Option<Cow<'static, str>> {
+ Some(match event {
+ AgentProgress::TurnStarted => "the turn started".into(),
+ AgentProgress::IterationStarted { .. } => "a model call started".into(),
+ AgentProgress::ModelCallCompleted {
+ subagent_task_id: None,
+ ..
+ } => "the model replied".into(),
+ AgentProgress::ToolCallStarted { tool_name, .. } => {
+ format!("the `{tool_name}` tool started").into()
+ }
+ AgentProgress::ToolCallCompleted {
+ tool_name, success, ..
+ } => {
+ let outcome = if *success { "finished" } else { "failed" };
+ format!("the `{tool_name}` tool {outcome}").into()
+ }
+ AgentProgress::TextDelta { .. } | AgentProgress::ThinkingDelta { .. } => {
+ "the model was writing".into()
+ }
+ AgentProgress::ToolCallProgress { .. } => "a tool reported progress".into(),
+ AgentProgress::SubagentSpawned { .. }
+ | AgentProgress::SubagentCompleted { .. }
+ | AgentProgress::SubagentFailed { .. }
+ | AgentProgress::SubagentAwaitingUser { .. } => "a sub-agent reported progress".into(),
+ _ => return None,
+ })
+}
+
+/// Shared activity record for one turn. Cheap to clone; every clone sees the
+/// same state.
+#[derive(Clone, Debug)]
+pub(crate) struct TurnActivity {
+ state: Arc<Mutex<State>>,
+}
+
+impl TurnActivity {
+ /// A record whose idle clock starts now, with nothing in flight. The turn
+ /// emits no progress before its session is checked out, so that phase is
+ /// measured from here.
+ pub(crate) fn new() -> Self {
+ Self {
+ state: Arc::new(Mutex::new(State {
+ last_event: Instant::now(),
+ open_tool_calls: HashSet::new(),
+ model_call_open: false,
+ last_step: None,
+ turn_completed: false,
+ turn_config: None,
+ locale: None,
+ })),
+ }
+ }
+
+ fn lock(&self) -> std::sync::MutexGuard<'_, State> {
+ self.state.lock().unwrap_or_else(|p| p.into_inner())
+ }
+
+ /// Fold one progress event into the record.
+ pub(crate) fn observe(&self, event: &AgentProgress) {
+ let mut state = self.lock();
+ state.last_event = Instant::now();
+ if let Some(step) = step_of(event) {
+ state.last_step = Some(step);
+ }
+ match event {
+ AgentProgress::IterationStarted { .. } => state.model_call_open = true,
+ AgentProgress::ModelCallCompleted {
+ subagent_task_id: None,
+ ..
+ } => state.model_call_open = false,
+ AgentProgress::ToolCallStarted { call_id, .. } => {
+ state.open_tool_calls.insert(call_id.clone());
+ }
+ AgentProgress::ToolCallCompleted { call_id, .. } => {
+ state.open_tool_calls.remove(call_id);
+ }
+ AgentProgress::TurnCompleted { .. } => {
+ state.open_tool_calls.clear();
+ state.model_call_open = false;
+ state.turn_completed = true;
+ }
+ _ => {}
+ }
+ }
+
+ /// How long the turn has been idle as of `now`, or `None` while a model or
+ /// tool call is in flight.
+ 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() {
+ return None;
+ }
+ Some(now.saturating_duration_since(state.last_event))
+ }
+}
+
+impl TurnActivity {
+ /// Record the config and reply locale the turn resolved. A stop reply
+ /// uses these rather than whatever profile is active when it fires.
+ pub(crate) fn remember_turn(&self, config: Arc<crate::config::Config>, locale: Option<String>) {
+ let mut state = self.lock();
+ state.turn_config = Some(config);
+ state.locale = locale;
+ }
+
+ /// The config and locale recorded by [`Self::remember_turn`], if the turn
+ /// got that far.
+ pub(crate) fn turn_context(&self) -> (Option<Arc<crate::config::Config>>, Option<String>) {
+ let state = self.lock();
+ (state.turn_config.clone(), state.locale.clone())
+ }
+
+ /// Where the turn was when its last event arrived.
+ pub(crate) fn stuck_point(&self) -> StuckPoint {
+ let state = self.lock();
+ if state.turn_completed {
+ return StuckPoint::AfterRun;
+ }
+ match &state.last_step {
+ None => StuckPoint::BeforeRun,
+ Some(step) => StuckPoint::BetweenSteps {
+ after: step.to_string(),
+ },
+ }
+ }
+}
+
+/// Resolve once the turn has been idle for `window`, returning the idle time
+/// observed. Never resolves while the turn keeps emitting progress or keeps a
+/// call in flight.
+pub(crate) async fn idle_watchdog(activity: TurnActivity, window: Duration) -> Duration {
+ loop {
+ let wait = match activity.idle_for(Instant::now()) {
+ Some(idle) if idle >= window => return idle,
+ Some(idle) => window - idle,
+ None => IN_FLIGHT_RECHECK.min(window),
+ };
+ tokio::time::sleep(wait).await;
+ }
+}
+
+/// Interpose `activity` on a turn's progress stream: every event the agent
+/// sends is folded into the record, then forwarded in order to the returned
+/// receiver (the progress bridge). The forwarder only records and forwards, so
+/// it drains the agent-side channel faster than the bridge, which publishes.
+/// It ends when the agent's sender drops, closing the bridge's stream in turn.
+pub(crate) fn tap(
+ activity: TurnActivity,
+ mut agent_rx: mpsc::Receiver<AgentProgress>,
+ capacity: usize,
+) -> mpsc::Receiver<AgentProgress> {
+ let (bridge_tx, bridge_rx) = mpsc::channel(capacity);
- tokio::spawn(async move {
++ crate::core::runtime::spawn_scoped(async move {
+ while let Some(event) = agent_rx.recv().await {
+ activity.observe(&event);
+ if bridge_tx.send(event).await.is_err() {
+ break;
+ }
+ }
+ });
+ bridge_rx
+}
+
+tokio::task_local! {
+ static CURRENT_TURN_ACTIVITY: TurnActivity;
+}
+
+/// The activity record scoped on the current task, if any.
+pub(crate) fn current() -> Option<TurnActivity> {
+ CURRENT_TURN_ACTIVITY.try_with(Clone::clone).ok()
+}
+
+/// Run `future` with `activity` scoped on the task.
+pub(crate) async fn with_turn_activity<F: Future>(activity: TurnActivity, future: F) -> F::Output {
+ CURRENT_TURN_ACTIVITY.scope(activity, future).await
+}
+
+#[cfg(test)]
+#[path = "turn_activity_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/web_chat/turn_close.rs
index 55e9977840,0000000000..4305bb0e06
mode 100644,000000..100644
--- a/crates/openhuman-core/src/web_chat/turn_close.rs
+++ b/crates/openhuman-core/src/web_chat/turn_close.rs
@@@ -1,354 -1,0 +1,355 @@@
+//! The reply that closes a turn a web-turn guard stopped.
+//!
+//! When the idle guard or the wall-clock backstop drops a turn, the turn's own
+//! loop cannot write its close: it is stuck, or was never reached. Instead of
+//! a bare `turn_timeout` error, the guard closes the turn with a reply that
+//! says what the turn got done and where it got stuck. The evidence is what
+//! the turn recorded while it ran: the turn-state snapshot the progress
+//! bridge mirrors (tool timeline and narration), plus the [`StuckPoint`] the
+//! activity record saw.
+//!
+//! One tools-free `summarization` call writes the reply, bounded by
+//! [`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.
+
+use std::time::Duration;
+
+use tinyagents_session::turn_state::types::TranscriptItem;
- use tinyagents_session::turn_state::{ToolTimelineStatus, TurnState, TurnStateStore};
++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;
+use super::types::WebChatTaskResult;
+
+/// Upper bound on the closing model call.
+const CLOSE_TIMEOUT: Duration = Duration::from_secs(45);
+
+/// Most tool rows listed in the evidence (the latest ones are kept).
+const MAX_STEPS: usize = 40;
+
+/// Most characters of a tool row's detail carried in the evidence.
+const MAX_DETAIL_CHARS: usize = 160;
+
+/// Most characters of the agent's latest narration carried in the evidence.
+const MAX_NARRATION_CHARS: usize = 1_500;
+
+const LOG_PREFIX: &str = "[web-channel:turn-close]";
+
+const CLOSE_SYSTEM_PROMPT: &str = "You write the closing message of an AI assistant's turn \
+ that was stopped before it finished. Write to the user, in the assistant's voice, in \
+ plain language. Use only the evidence given; do not invent results. Keep it short, in \
+ three parts: what got done, where it got stuck and why the turn was stopped, and what \
+ the user can say to continue. Do not apologize at length.";
+
+/// Why a guard stopped the turn.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum StopCause {
+ /// No progress, and nothing in flight, for this long.
+ Idle(Duration),
+ /// The fixed wall-clock ceiling, which the harness wind-down did not beat.
+ Ceiling(Duration),
+}
+
+impl StopCause {
+ fn describe(self) -> String {
+ match self {
+ Self::Idle(idle) => format!("nothing happened for {}", minutes(idle)),
+ Self::Ceiling(limit) => format!("it hit its time limit of {}", minutes(limit)),
+ }
+ }
+}
+
+fn minutes(d: Duration) -> String {
+ let (n, unit) = match d.as_secs() {
+ secs @ 0..=59 => (secs, "second"),
+ secs => (secs / 60, "minute"),
+ };
+ if n == 1 {
+ format!("1 {unit}")
+ } else {
+ format!("{n} {unit}s")
+ }
+}
+
+/// A turn a guard stopped, and why.
+pub(crate) struct StoppedTurn<'a> {
+ pub(crate) thread_id: &'a str,
+ pub(crate) request_id: &'a str,
+ pub(crate) cause: StopCause,
+ pub(crate) stuck: StuckPoint,
+ /// The config the turn resolved, when it got that far. Its workspace is
+ /// where the turn's snapshot lives and where the reply is saved, even if
+ /// the active profile changed since.
+ pub(crate) config: Option<std::sync::Arc<crate::config::Config>>,
+ /// The turn's reply locale, so the close is written in its language.
+ pub(crate) locale: Option<String>,
+}
+
+impl StoppedTurn<'_> {
+ /// Whether the agent never received the user's request: the turn stopped
+ /// before its run began, so there is nothing to continue from.
+ fn request_unseen(&self) -> bool {
+ self.stuck == StuckPoint::BeforeRun
+ }
+}
+
+/// What the turn recorded while it ran, as evidence lines.
+#[derive(Debug, Default, PartialEq, Eq)]
+pub(crate) struct Evidence {
+ pub(crate) steps: Vec<String>,
+ pub(crate) narration: Option<String>,
+}
+
+fn truncate(text: &str, max: usize) -> String {
+ let text = text.trim();
+ if text.chars().count() <= max {
+ return text.to_string();
+ }
+ let kept: String = text.chars().take(max).collect();
+ format!("{kept}…")
+}
+
+impl Evidence {
+ pub(crate) fn from_snapshot(state: Option<&TurnState>) -> Self {
+ let Some(state) = state else {
+ return Self::default();
+ };
+ let skip = state.tool_timeline.len().saturating_sub(MAX_STEPS);
+ let steps = state
+ .tool_timeline
+ .iter()
+ .skip(skip)
+ .map(|entry| {
+ let name = entry.display_name.as_deref().unwrap_or(&entry.name);
+ let detail = entry
+ .detail
+ .as_deref()
+ .filter(|d| !d.trim().is_empty())
+ .map(|d| format!(" ({})", truncate(d, MAX_DETAIL_CHARS)))
+ .unwrap_or_default();
+ match entry.status {
+ ToolTimelineStatus::Success => format!("done: {name}{detail}"),
+ ToolTimelineStatus::Running => format!("still running: {name}{detail}"),
+ ToolTimelineStatus::Error => {
+ let cause = entry
+ .failure
+ .as_ref()
+ .map(|f| format!(" — {}", f.cause_plain))
+ .unwrap_or_default();
+ format!("failed: {name}{detail}{cause}")
+ }
+ }
+ })
+ .collect();
+ let narration = state
+ .transcript
+ .iter()
+ .rev()
+ .find_map(|item| match item {
+ TranscriptItem::Narration { text, .. } if !text.trim().is_empty() => {
+ Some(text.as_str())
+ }
+ _ => None,
+ })
+ .or_else(|| Some(state.streaming_text.as_str()).filter(|t| !t.trim().is_empty()))
+ .map(|text| truncate(text, MAX_NARRATION_CHARS));
+ Self { steps, narration }
+ }
+
+ fn render(&self) -> String {
+ let mut out = String::new();
+ if self.steps.is_empty() {
+ out.push_str("Steps taken: none recorded.\n");
+ } else {
+ out.push_str("Steps taken, oldest first:\n");
+ for step in &self.steps {
+ out.push_str("- ");
+ out.push_str(step);
+ out.push('\n');
+ }
+ }
+ if let Some(narration) = &self.narration {
+ out.push_str("\nThe assistant's last message before it stopped:\n");
+ out.push_str(narration);
+ out.push('\n');
+ }
+ out
+ }
+}
+
+/// The plain reply used when the closing model call is unavailable.
+pub(crate) fn plain_reply(turn: &StoppedTurn<'_>, evidence: &Evidence) -> String {
+ let mut out = format!(
+ "I stopped this turn because {}. It got stuck {}.\n\n",
+ turn.cause.describe(),
+ turn.stuck.describe()
+ );
+ if evidence.steps.is_empty() {
+ out.push_str("No steps had been recorded yet.\n");
+ } else {
+ out.push_str("What happened before it stopped:\n");
+ for step in &evidence.steps {
+ out.push_str("- ");
+ out.push_str(step);
+ out.push('\n');
+ }
+ }
+ if turn.request_unseen() {
+ out.push_str(
+ "\nYour message didn't reach me before the turn stopped. Please send it again.",
+ );
+ } else {
+ out.push_str("\nSay \"continue\" and I'll pick up from here.");
+ }
+ out
+}
+
+fn close_request(turn: &StoppedTurn<'_>, evidence: &Evidence) -> ModelRequest {
+ let next_step = if turn.request_unseen() {
+ "The assistant never received the user's request, so it cannot continue it. Ask the \
+ user to send the request again; do not suggest saying \"continue\"."
+ } else {
+ "The user can say \"continue\" to pick up from here."
+ };
+ let user_prompt = format!(
+ "The turn was stopped because {}.\nWhere it got stuck: {}.\n{next_step}\n\n{}",
+ turn.cause.describe(),
+ turn.stuck.describe(),
+ evidence.render()
+ );
+ let mut system = CLOSE_SYSTEM_PROMPT.to_string();
+ if let Some(directive) = turn
+ .locale
+ .as_deref()
+ .and_then(super::session::locale_reply_directive)
+ {
+ system.push_str("\n\n");
+ system.push_str(&directive);
+ }
+ provider::openhuman_backend_model::without_reasoning(
+ ModelRequest::new(vec![Message::system(system), Message::user(user_prompt)])
+ .with_temperature(0.2),
+ )
+}
+
+/// Tests run offline: the closing model call is skipped and the plain reply
+/// is used.
+#[cfg(test)]
+static PLAIN_ONLY: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(true);
+
+async fn model_reply(
+ config: &crate::config::Config,
+ turn: &StoppedTurn<'_>,
+ evidence: &Evidence,
+) -> Option<String> {
+ #[cfg(test)]
+ if PLAIN_ONLY.load(std::sync::atomic::Ordering::SeqCst) {
+ return None;
+ }
+ let request_id = turn.request_id;
+ let (chat_model, model) =
+ match provider::create_chat_model_with_model_id("summarization", config, 0.2) {
+ Ok(resolved) => resolved,
+ Err(error) => {
+ log::warn!("{LOG_PREFIX} provider init failed request_id={request_id}: {error}");
+ return None;
+ }
+ };
+ let call = chat_model.invoke(&(), close_request(turn, evidence));
+ match tokio::time::timeout(CLOSE_TIMEOUT, call).await {
+ Ok(Ok(response)) => Some(response.text()).filter(|text| !text.trim().is_empty()),
+ Ok(Err(error)) => {
+ log::warn!(
+ "{LOG_PREFIX} close call failed request_id={request_id} model={model}: {error}"
+ );
+ None
+ }
+ Err(_) => {
+ log::warn!(
+ "{LOG_PREFIX} close call timed out after {CLOSE_TIMEOUT:?} \
+ request_id={request_id} model={model}"
+ );
+ None
+ }
+ }
+}
+
- /// Read the turn's snapshot off the async worker: it is a synchronous disk
- /// read, and a stalled filesystem must not pin the runtime thread.
++/// Read the turn's snapshot off the async worker: it is a synchronous store
++/// read, and a stalled store must not pin the runtime thread. The scoped spawn
++/// carries the caller's tenant, which selects the store.
+async fn read_snapshot(
+ workspace: std::path::PathBuf,
+ thread_id: &str,
+ request_id: &str,
+) -> Option<TurnState> {
+ let (thread_id, request_id) = (thread_id.to_string(), request_id.to_string());
- let read = tokio::task::spawn_blocking(move || {
- TurnStateStore::new(workspace).get_turn(&thread_id, &request_id)
++ let read = crate::core::runtime::spawn_blocking_scoped(move || {
++ crate::agent::session_store::turn_states_for(&workspace).get_turn(&thread_id, &request_id)
+ })
+ .await;
+ match read {
+ Ok(Ok(snapshot)) => snapshot,
+ Ok(Err(error)) => {
+ log::warn!("{LOG_PREFIX} turn snapshot unreadable: {error}");
+ None
+ }
+ Err(error) => {
+ log::warn!("{LOG_PREFIX} turn snapshot read did not finish: {error}");
+ None
+ }
+ }
+}
+
+/// 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.
+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 snapshot = read_snapshot(
+ config.workspace_dir.clone(),
+ turn.thread_id,
+ turn.request_id,
+ )
+ .await;
+ let evidence = Evidence::from_snapshot(snapshot.as_ref());
+ let reply = match model_reply(&config, &turn, &evidence).await {
+ Some(reply) => reply,
+ None => plain_reply(&turn, &evidence),
+ };
+ log::info!(
+ "{LOG_PREFIX} closed stopped turn request_id={} steps={} stuck={:?}",
+ turn.request_id,
+ evidence.steps.len(),
+ turn.stuck
+ );
+ Some(WebChatTaskResult {
+ full_response: reply,
+ citations: Vec::new(),
+ usage: None,
+ workspace_dir: config.workspace_dir.clone(),
+ timing: None,
+ })
+}
+
+#[cfg(test)]
+#[path = "turn_close_tests.rs"]
+mod tests;
diff --cc scripts/ci/check-openhuman-rust-layout.mjs
index b9ba1f60de,f6adc435ac..dcc6e97d5f
--- a/scripts/ci/check-openhuman-rust-layout.mjs
+++ b/scripts/ci/check-openhuman-rust-layout.mjs
@@@ -34,10 -34,10 +34,10 @@@ const LEGACY_LIMIT_ENTRIES =
// provider, security, memory, tool and prompt policy. Generic session
// state moved to tinyagents-runtime; this remaining composition is split in
// a follow-up without reintroducing an old harness/session exception.
- ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 973],
+ ["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 975],
["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1247],
["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1046],
- ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1261],
+ ["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1209],
// These established external test modules grew with upstream coverage. Pin
// their current sizes while follow-up work separates their test concerns.
// `core/` was pruned from the line limit by name until these pins; its