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): stop only inactive turns and close them with a summary
killbillb1372288d2cb
diff --git a/crates/openhuman-core/src/agent/progress.rs b/crates/openhuman-core/src/agent/progress.rsindex d78de74d5c..b38c9b083d 100644--- a/crates/openhuman-core/src/agent/progress.rs+++ b/crates/openhuman-core/src/agent/progress.rs@@ -91,6 +91,18 @@ pub enum AgentProgress {structured: Option<serde_json::Value>,},+ /// A running tool reported progress through+ /// `ToolRunContext::report_progress` (a shell call's elapsed time and+ /// output, a media job's state). Falls between the call's+ /// [`Self::ToolCallStarted`] and [`Self::ToolCallCompleted`]. Parent-scope+ /// calls only.+ ToolCallProgress {+ /// Correlation id of the running call.+ call_id: String,+ /// Human-readable status line.+ message: String,+ },+/// A sub-agent was spawned during tool execution.SubagentSpawned {agent_id: String,diff --git a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs b/crates/openhuman-core/src/agent/progress_tracing/collector/events.rsindex 89c8fbceaa..44d4b74c83 100644--- a/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs+++ b/crates/openhuman-core/src/agent/progress_tracing/collector/events.rs@@ -517,6 +517,9 @@ impl SpanCollector {}}AgentProgress::SubagentAwaitingUser { .. } => {}+ // A running tool's status line can quote its output (a shell+ // call's last line), so it is content and never exported.+ AgentProgress::ToolCallProgress { .. } => {}}}}diff --git a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rsindex 1c00f45eac..c9de2a099f 100644--- a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs+++ b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down.rs@@ -1,6 +1,6 @@//! Wind a top-level turn down before the outer backstop drops it.//!-//! [`TurnDeadline`] puts the wind-down point at 780s under the default 900s+//! [`TurnDeadline`] puts the wind-down point at 3480s under the default 3600s//! web backstop. Once that point has passed, [`DeadlineWindDownMiddleware`]//! sends [`SteeringCommand::Pause`] at the next safe checkpoint: after a model//! call (that call's tool round still runs) or after a tool result (so a longdiff --git a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rsindex 6763598166..1a91a8a7fd 100644--- a/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/deadline_wind_down_tests.rs@@ -32,16 +32,18 @@ fn pauses_once_after_the_wind_down_point() {);}-/// The harness's own default turn ceiling is later than the web backstop.-/// That ordering is what dropped long turns. The clamp must therefore always-/// bring it below the backstop.+/// The web backstop defaults to the harness's own default turn ceiling, so+/// the unclamped ceiling ends no earlier than the backstop. Letting the+/// backstop drop a turn before the harness stops it is what lost long turns.+/// The clamp must therefore always bring the ceiling below the backstop.#[test]fn the_default_harness_ceiling_is_clamped_below_the_backstop() {let backstop = Duration::from_secs(crate::agent::turn_deadline::DEFAULT_TURN_BACKSTOP_SECS);let default_ms = crate::agent::tinyagents::DEFAULT_AGENT_TURN_TIMEOUT_SECS * 1_000;- assert!(- default_ms > backstop.as_millis() as u64,- "precondition: the unclamped ceiling is later than the backstop"+ assert_eq!(+ default_ms,+ backstop.as_millis() as u64,+ "the default backstop is the harness's default turn ceiling");let now = Instant::now();let clamped = TurnDeadline::new(now, backstop)diff --git a/crates/openhuman-core/src/agent/tinyagents/observability.rs b/crates/openhuman-core/src/agent/tinyagents/observability.rsindex 2314baa5bc..623be5488d 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability.rs@@ -13,6 +13,7 @@ mod compaction_log;mod event_bridge;mod event_projection;mod graph_tracing;+mod tool_progress_projection;#[cfg(test)]use std::sync::Arc;diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rsindex 6a8f4d5dba..bafdb592ac 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability/event_projection.rs@@ -637,6 +637,9 @@ impl EventListener for OpenhumanEventBridge {// without invoking the provider (deterministic internal runs only —// interactive chat never attaches a cache). Counters are additive; the// cost-footer DTO wiring is a follow-up (workstream 06).+ AgentEvent::ToolProgressDetail {+ call_id, message, ..+ } => self.forward_tool_progress(call_id.as_str(), message),AgentEvent::CacheHit { call_id, key } => {{let mut s = self.state.lock().unwrap();diff --git a/crates/openhuman-core/src/agent/tinyagents/observability/tool_progress_projection.rs b/crates/openhuman-core/src/agent/tinyagents/observability/tool_progress_projection.rsnew file mode 100644index 0000000000..5d5f242630--- /dev/null+++ b/crates/openhuman-core/src/agent/tinyagents/observability/tool_progress_projection.rs@@ -0,0 +1,24 @@+//! Projection of `AgentEvent::ToolProgressDetail` onto+//! [`AgentProgress::ToolCallProgress`].++use crate::agent::progress::AgentProgress;++use super::event_bridge::OpenhumanEventBridge;++impl OpenhumanEventBridge {+ /// Forward a running tool's progress report for a parent-scope call.+ ///+ /// A sub-agent's tool progress stays inside its own run: on the parent+ /// turn, the delegation call that runs the sub-agent is the open call. An+ /// update that carries no message (a bare fraction or partial output) has+ /// nothing to show and is not forwarded.+ pub(super) fn forward_tool_progress(&self, call_id: &str, message: &str) {+ if self.scope.is_some() || message.trim().is_empty() {+ return;+ }+ self.send(AgentProgress::ToolCallProgress {+ call_id: call_id.to_string(),+ message: message.to_string(),+ });+ }+}diff --git a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rsindex 9e4e46eb7c..e0fe809f37 100644--- a/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/observability_tests.rs@@ -569,3 +569,40 @@ async fn tool_call_events_use_the_tool_s_own_display_label_and_detail() {"the completed detail is recomputed from the real call arguments");}++/// A running tool's progress report reaches the web channel as+/// `ToolCallProgress` for the same call; an update with no message does not.+#[tokio::test]+async fn bridge_forwards_tool_progress_with_a_message() {+ let (tx, mut rx) = tokio::sync::mpsc::channel(64);+ let bridge = OpenhumanEventBridge::new(Some(tx), "mock-model", 10);+ let sink = EventSink::new();+ sink.subscribe(bridge.clone());++ sink.emit(AgentEvent::ToolProgressDetail {+ call_id: "c1".into(),+ message: "running 4m 12s · 38.2 KB output".to_string(),+ fraction: None,+ partial: None,+ });+ sink.emit(AgentEvent::ToolProgressDetail {+ call_id: "c1".into(),+ message: String::new(),+ fraction: Some(0.5),+ partial: None,+ });++ let mut progress = Vec::new();+ while let Ok(p) = rx.try_recv() {+ if let AgentProgress::ToolCallProgress { call_id, message } = p {+ progress.push((call_id, message));+ }+ }+ assert_eq!(+ progress,+ vec![(+ "c1".to_string(),+ "running 4m 12s · 38.2 KB output".to_string()+ )]+ );+}diff --git a/crates/openhuman-core/src/agent/turn_deadline.rs b/crates/openhuman-core/src/agent/turn_deadline.rsindex e75e45f081..3ebbdf0993 100644--- a/crates/openhuman-core/src/agent/turn_deadline.rs+++ b/crates/openhuman-core/src/agent/turn_deadline.rs@@ -11,11 +11,11 @@//! This module is the single source of truth for the backstop and for the two//! points the harness derives from it://!-//! * **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.-//! * **hard stop** (`backstop - min(60s, backstop/10)`, 840s by default): the+//! * **hard stop** (`backstop - min(60s, backstop/10)`, 3540s by default): the//! harness `max_wall_clock_ms` is clamped to this. A single tool call that//! runs across the wind-down point is then interrupted by the harness's own//! typed `Timeout` before the backstop drops the turn.@@ -23,6 +23,13 @@//! For every positive backstop, `wind_down < hard_stop < backstop`//! (see `turn_deadline_tests.rs`).//!+//! The backstop defaults to the harness turn ceiling (3600s). 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.+//!//! The web-turn guard scopes the deadline on a task-local//! ([`with_turn_deadline`]). The top-level session turn//! (`OpenHumanSessionHost::turn_with_origin`) copies it onto its explicit run@@ -32,8 +39,9 @@use std::future::Future;use std::time::{Duration, Instant};-/// Default outer wall-clock backstop for one web-chat turn, in seconds.-pub const DEFAULT_TURN_BACKSTOP_SECS: u64 = 900;+/// 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;/// Environment override for the backstop, in seconds; `0` disables it.pub const TURN_BACKSTOP_ENV: &str = "OPENHUMAN_WEB_TURN_TIMEOUT_SECS";diff --git a/crates/openhuman-core/src/agent/turn_deadline_tests.rs b/crates/openhuman-core/src/agent/turn_deadline_tests.rsindex 7c81f40ecd..9c0db06b8c 100644--- a/crates/openhuman-core/src/agent/turn_deadline_tests.rs+++ b/crates/openhuman-core/src/agent/turn_deadline_tests.rs@@ -1,11 +1,11 @@use super::*;#[test]-fn default_deadlines_are_780s_840s_900s() {+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(780));- assert_eq!(deadline.hard_stop_after(), Duration::from_secs(840));- assert_eq!(deadline.backstop(), Duration::from_secs(900));+ 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@@ -46,11 +46,11 @@ fn harness_wall_clock_is_always_clamped_below_the_backstop() {let clamped = deadline.clamp_wall_clock_ms(Some(harness_default_ms), now).expect("clamped ceiling");- assert_eq!(clamped, 840_000);+ assert_eq!(clamped, 3_540_000);assert!(clamped < backstop_ms);let unbounded = deadline.clamp_wall_clock_ms(None, now).expect("bounded");- assert_eq!(unbounded, 840_000);+ assert_eq!(unbounded, 3_540_000);// A configured ceiling that is already tighter is kept.assert_eq!(@@ -84,10 +84,10 @@ fn should_wind_down_flips_at_the_wind_down_point() {#[test]fn parse_backstop_defaults_and_disables() {- assert_eq!(parse_backstop(None), Some(Duration::from_secs(900)));+ assert_eq!(parse_backstop(None), Some(Duration::from_secs(3_600)));assert_eq!(parse_backstop(Some("garbage")),- Some(Duration::from_secs(900))+ Some(Duration::from_secs(3_600)));assert_eq!(parse_backstop(Some(" 120 ")),diff --git a/crates/openhuman-core/src/sandbox/mod.rs b/crates/openhuman-core/src/sandbox/mod.rsindex a7f5ab7e14..ab0d107335 100644--- a/crates/openhuman-core/src/sandbox/mod.rs+++ b/crates/openhuman-core/src/sandbox/mod.rs@@ -16,6 +16,7 @@ pub(crate) mod native_jail;pub mod ops;pub mod schemas;pub(crate) mod shell_exec;+pub(crate) mod shell_progress;pub mod types;pub use ops::{diff --git a/crates/openhuman-core/src/sandbox/shell_exec.rs b/crates/openhuman-core/src/sandbox/shell_exec.rsindex 88ecbeb95b..dd89a770ec 100644--- a/crates/openhuman-core/src/sandbox/shell_exec.rs+++ b/crates/openhuman-core/src/sandbox/shell_exec.rs@@ -103,12 +103,14 @@ pub(crate) async fn run(config: &Config, run: NativeShellRun) -> anyhow::Result<#[cfg(feature = "modules")]{let config = config.clone();+ // Read before the spawn: the caller's progress meter is task-local.+ let meter = super::shell_progress::current_meter();tracing::debug!(jailed = run.jail.is_some(),timeout_ms = run.timeout.as_millis() as u64,"[sandbox:shell] starting native shell through TinyBox");- tokio::spawn(async move { run_owned(&config, run).await })+ tokio::spawn(async move { run_owned(&config, run, meter).await }).await.map_err(|_| anyhow::anyhow!("TinyBox shell worker did not finish"))?}@@ -120,7 +122,11 @@ pub(crate) async fn run(config: &Config, run: NativeShellRun) -> anyhow::Result<}#[cfg(feature = "modules")]-async fn run_owned(config: &Config, run: NativeShellRun) -> anyhow::Result<SandboxExecResult> {+async fn run_owned(+ config: &Config,+ run: NativeShellRun,+ meter: Option<super::shell_progress::ShellOutputMeter>,+) -> anyhow::Result<SandboxExecResult> {let resource = tinybox::reserve(config, contract::ReserveRequest::Resource).await.map_err(|_| anyhow::anyhow!("TinyBox could not reserve a command resource"))?;@@ -155,7 +161,7 @@ async fn run_owned(config: &Config, run: NativeShellRun) -> anyhow::Result<Sandblet 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).await+ collect_process(config, process, timeout, meter).await}.await;let close = tinybox::close(config, resource).await;@@ -204,6 +210,7 @@ async fn collect_process(config: &Config,process: contract::ProcessRef,timeout: Duration,+ meter: Option<super::shell_progress::ShellOutputMeter>,) -> anyhow::Result<SandboxExecResult> {use contract::{ExecutionFailure, ExecutionState, OutputStream};@@ -230,6 +237,9 @@ async fn collect_process(let has_chunks = !batch.chunks.is_empty();let state = batch.state;for chunk in batch.chunks {+ if let Some(meter) = &meter {+ meter.record(&chunk.bytes);+ }match chunk.stream {OutputStream::Stdout => stdout.extend_from_slice(&chunk.bytes),OutputStream::Stderr => stderr.extend_from_slice(&chunk.bytes),diff --git a/crates/openhuman-core/src/sandbox/shell_progress.rs b/crates/openhuman-core/src/sandbox/shell_progress.rsnew file mode 100644index 0000000000..838e65624f--- /dev/null+++ b/crates/openhuman-core/src/sandbox/shell_progress.rs@@ -0,0 +1,122 @@+//! Progress for a running shell call.+//!+//! A shell call can legitimately run for many minutes (a build, a test suite,+//! a download), and until it exits the turn shows nothing. While it runs,+//! [`with_shell_progress`] reports a status line through the harness's+//! [`ToolRunContext::report_progress`] seam every [`HEARTBEAT_INTERVAL`]: the+//! elapsed time, how much output the command has written, and its last output+//! line. The agent loop turns each report into `AgentEvent::ToolProgressDetail`+//! for the call, which the web channel projects as `tool_progress`.+//!+//! The output figures come from [`ShellOutputMeter`], which+//! `shell_exec::collect_process` feeds with every chunk it reads from the+//! process. Paths that do not stream output (the Docker backend) still report+//! the elapsed time.++use std::sync::{Arc, Mutex};+use std::time::Duration;++use tinytools::{ToolProgress, ToolRunContext};++/// How often a running shell call reports that it is still working.+pub(crate) const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);++/// Longest last-output line carried in a status line, in characters.+const LAST_LINE_CHARS: usize = 120;++#[derive(Debug, Default)]+struct Meter {+ bytes: u64,+ last_line: Option<String>,+}++/// Output written so far by the shell call running on this task. Cheap to+/// clone; every clone sees the same figures.+#[derive(Clone, Debug, Default)]+pub(crate) struct ShellOutputMeter(Arc<Mutex<Meter>>);++impl ShellOutputMeter {+ /// Fold one chunk of stdout or stderr into the figures.+ pub(crate) fn record(&self, chunk: &[u8]) {+ let mut meter = self.0.lock().unwrap_or_else(|p| p.into_inner());+ meter.bytes = meter.bytes.saturating_add(chunk.len() as u64);+ let text = String::from_utf8_lossy(chunk);+ if let Some(line) = text.lines().map(str::trim).rfind(|line| !line.is_empty()) {+ meter.last_line = Some(line.chars().take(LAST_LINE_CHARS).collect());+ }+ }++ fn snapshot(&self) -> (u64, Option<String>) {+ let meter = self.0.lock().unwrap_or_else(|p| p.into_inner());+ (meter.bytes, meter.last_line.clone())+ }+}++tokio::task_local! {+ static CURRENT_METER: ShellOutputMeter;+}++/// The meter of the shell call running on this task, if it reports progress.+/// Read it before spawning a worker task: a task-local does not follow+/// `tokio::spawn`.+pub(crate) fn current_meter() -> Option<ShellOutputMeter> {+ CURRENT_METER.try_with(Clone::clone).ok()+}++/// The status line for a call `elapsed` into its run.+pub(crate) fn progress_message(elapsed: Duration, bytes: u64, last_line: Option<&str>) -> String {+ let secs = elapsed.as_secs();+ let elapsed = if secs >= 60 {+ format!("{}m {:02}s", secs / 60, secs % 60)+ } else {+ format!("{secs}s")+ };+ if bytes == 0 {+ return format!("running {elapsed} · no output yet");+ }+ let size = if bytes >= 1024 * 1024 {+ format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))+ } else if bytes >= 1024 {+ format!("{:.1} KB", bytes as f64 / 1024.0)+ } else {+ format!("{bytes} B")+ };+ match last_line {+ Some(line) => format!("running {elapsed} · {size} output · last line: {line}"),+ None => format!("running {elapsed} · {size} output"),+ }+}++/// Run the shell call `fut`, reporting its progress through `context` every+/// `interval` until it finishes. Without a context there is nowhere to report,+/// so `fut` runs as is.+pub(crate) async fn with_shell_progress<F: std::future::Future>(+ context: Option<&dyn ToolRunContext>,+ interval: Duration,+ fut: F,+) -> F::Output {+ let Some(context) = context else {+ return fut.await;+ };+ let meter = ShellOutputMeter::default();+ let started = tokio::time::Instant::now();+ // Boxed: the shell call's future is large, and this wrapper would+ // otherwise hold it inline a second time on the tool's stack.+ let mut work = Box::pin(CURRENT_METER.scope(meter.clone(), fut));+ let mut ticker = tokio::time::interval_at(tokio::time::Instant::now() + interval, interval);+ loop {+ tokio::select! {+ output = &mut work => return output,+ _ = ticker.tick() => {+ let (bytes, last_line) = meter.snapshot();+ let message = progress_message(started.elapsed(), bytes, last_line.as_deref());+ tracing::debug!(%message, "[shell] reporting progress");+ context.report_progress(ToolProgress::message(message));+ }+ }+ }+}++#[cfg(test)]+#[path = "shell_progress_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/sandbox/shell_progress_tests.rs b/crates/openhuman-core/src/sandbox/shell_progress_tests.rsnew file mode 100644index 0000000000..10b5169ee3--- /dev/null+++ b/crates/openhuman-core/src/sandbox/shell_progress_tests.rs@@ -0,0 +1,92 @@+use super::*;++/// A context that records what the tool reported.+#[derive(Default)]+struct Recorder {+ updates: Mutex<Vec<String>>,+}++impl ToolRunContext for Recorder {+ fn report_progress(&self, update: ToolProgress) {+ self.updates+ .lock()+ .unwrap()+ .push(update.message.unwrap_or_default());+ }+}++#[test]+fn message_names_elapsed_time_output_size_and_last_line() {+ assert_eq!(+ progress_message(Duration::from_secs(45), 0, None),+ "running 45s · no output yet"+ );+ assert_eq!(+ progress_message(+ Duration::from_secs(252),+ 39_117,+ Some("Compiling serde v1.0")+ ),+ "running 4m 12s · 38.2 KB output · last line: Compiling serde v1.0"+ );+ assert_eq!(+ progress_message(Duration::from_secs(61), 3 * 1024 * 1024, None),+ "running 1m 01s · 3.0 MB output"+ );+}++#[test]+fn meter_counts_bytes_and_keeps_the_last_non_empty_line() {+ let meter = ShellOutputMeter::default();+ meter.record(b"one\ntwo\n\n");+ meter.record(b" three \n");+ meter.record(b"\n");+ assert_eq!(meter.snapshot(), (20, Some("three".to_string())));+}++#[test]+fn meter_truncates_a_long_last_line() {+ let meter = ShellOutputMeter::default();+ meter.record("x".repeat(500).as_bytes());+ let (_, line) = meter.snapshot();+ assert_eq!(line.unwrap().chars().count(), LAST_LINE_CHARS);+}++/// A 40s command that writes output reports twice, with the output it has+/// written so far, through the meter scoped on its task.+#[tokio::test(start_paused = true)]+async fn a_long_call_reports_its_output_as_it_runs() {+ let recorder = Recorder::default();+ let work = async {+ let meter = current_meter().expect("meter scoped on the call");+ meter.record(b"Compiling a\n");+ tokio::time::sleep(Duration::from_secs(20)).await;+ meter.record(b"Compiling b\n");+ tokio::time::sleep(Duration::from_secs(20)).await;+ "done"+ };+ let output = with_shell_progress(Some(&recorder), HEARTBEAT_INTERVAL, work).await;+ assert_eq!(output, "done");+ let updates = recorder.updates.lock().unwrap().clone();+ assert_eq!(+ updates,+ vec![+ "running 15s · 12 B output · last line: Compiling a".to_string(),+ "running 30s · 24 B output · last line: Compiling b".to_string(),+ ]+ );+}++#[tokio::test(start_paused = true)]+async fn a_short_call_reports_nothing() {+ let recorder = Recorder::default();+ let output = with_shell_progress(Some(&recorder), HEARTBEAT_INTERVAL, async { 7 }).await;+ assert_eq!(output, 7);+ assert!(recorder.updates.lock().unwrap().is_empty());+}++#[tokio::test]+async fn without_a_context_no_meter_is_scoped() {+ let seen = with_shell_progress(None, HEARTBEAT_INTERVAL, async { current_meter() }).await;+ assert!(seen.is_none());+}diff --git a/crates/openhuman-core/src/skills/run_log.rs b/crates/openhuman-core/src/skills/run_log.rsindex 7a2525969b..52793eb664 100644--- a/crates/openhuman-core/src/skills/run_log.rs+++ b/crates/openhuman-core/src/skills/run_log.rs@@ -186,6 +186,7 @@ pub fn format_event(ev: &AgentProgress) -> Option<String> {AgentProgress::TextDelta { .. }| AgentProgress::ThinkingDelta { .. }| AgentProgress::ToolCallArgsDelta { .. }+ | AgentProgress::ToolCallProgress { .. }| AgentProgress::TurnCostUpdated { .. }| AgentProgress::ModelCallCompleted { .. }| AgentProgress::SubagentTextDelta { .. }diff --git a/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs b/crates/openhuman-core/src/threads/turn_state/mirror/observe.rsindex 507eb516cb..ee0481400f 100644--- a/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs+++ b/crates/openhuman-core/src/threads/turn_state/mirror/observe.rs@@ -464,6 +464,12 @@ impl ObserveProgress for TurnStateMirror {// the turn-state snapshot; nothing to mirror, no flush.false}+ AgentProgress::ToolCallProgress { .. } => {+ // A running tool's status line is live-only (`tool_progress`+ // on the socket); the snapshot already shows the call as+ // running, so a flush per beat would buy nothing.+ false+ }}}}diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex 5897f0765a..586304ce2b 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -294,9 +294,12 @@ impl ShellTool {let requested_timeout = args.get("timeout_secs").and_then(|v| v.as_u64());let start = Instant::now();- let (allowed, result) = self- .run_with_security_in_context(command, requested_timeout, context)- .await;+ let (allowed, result) = crate::sandbox::shell_progress::with_shell_progress(+ context,+ crate::sandbox::shell_progress::HEARTBEAT_INTERVAL,+ self.run_with_security_in_context(command, requested_timeout, context),+ )+ .await;let duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);// `allowed` = passed the in-tool security checks. `approved` = the command// is Prompt-class (required human approval) and thus went through thediff --git a/crates/openhuman-core/src/web_chat/README.md b/crates/openhuman-core/src/web_chat/README.mdindex deb6aba4da..493a490c05 100644--- a/crates/openhuman-core/src/web_chat/README.md+++ b/crates/openhuman-core/src/web_chat/README.md@@ -187,13 +187,27 @@ background sub-agents. `state::cancel_in_flight_gracefully` cancels the tokenfirst and only hard-aborts the task if it has not unwound after a short graceperiod.-The wall-clock backstop defaults to 900 s (`DEFAULT_WEB_TURN_TIMEOUT_SECS`)-and is set with `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` (`0` disables it). It is an-outer safety net. The primary guard is the harness policy's-`max_wall_clock_ms` (600 s by default), which interrupts a hung model or tool-call and returns a proper timeout. The backstop only fires when a turn wedges-outside the harness run, for example in session assembly, so the client still-gets a terminal event instead of an endless heartbeat stream (#4746).+Two guards make sure a turn always ends in a terminal event instead of an+endless heartbeat stream (#4746):++- The **idle guard** ([`turn_activity.rs`](./turn_activity.rs)) ends a turn+ that has emitted no progress event, with no model or tool call in flight, for+ 900 s (`OPENHUMAN_WEB_TURN_IDLE_SECS`, `0` disables it). `run_chat_task` taps+ the turn's progress stream into a per-turn activity record on its way to the+ bridge. Every event restarts the clock, and an open model call+ (`IterationStarted` → `ModelCallCompleted`) or tool call (`ToolCallStarted`+ → `ToolCallCompleted`) holds it, so a silent provider retry or a long shell+ build is never idle. What it catches is silence nothing else bounds: session+ checkout, the persistence plumbing, or a harness that stopped with no call+ open.+- The **wall-clock backstop** is the fixed total ceiling, 3600 s by default+ (`agent::turn_deadline`, `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`, `0` disables it+ and the derived deadlines). The harness winds the turn down at 3480 s and+ writes the grounded close, and its own `max_wall_clock_ms` is clamped to+ 3540 s, so a busy turn still delivers an answer before the backstop drops it.++The backstop used to be 900 s and did both jobs, so a turn that was working+steadily was wound down at 780 s like a wedged one.### The event busdiff --git a/crates/openhuman-core/src/web_chat/mod.rs b/crates/openhuman-core/src/web_chat/mod.rsindex 169c912fd9..1ba366b60a 100644--- a/crates/openhuman-core/src/web_chat/mod.rs+++ b/crates/openhuman-core/src/web_chat/mod.rs@@ -5,7 +5,7 @@//! durably-persisted reply: `start_chat` (`ops/start_chat.rs`) validates and//! preprocesses the message, applies the queue mode against the thread's//! in-flight state, and spawns `run_task::run_chat_task` under the cancel-//! token / wall-clock backstop / `APPROVAL_CHAT_CONTEXT` scope+//! token / idle guard / wall-clock backstop / `APPROVAL_CHAT_CONTEXT` scope//! (`run_turn_under_cancel_and_deadline`, `ops/turn_guards.rs`). `run_chat_task`//! resolves or builds the cached session `Agent` (`session.rs`), spawns//! `spawn_progress_bridge` alongside the run, and returns the result; the@@ -19,7 +19,8 @@//!//! Submodules: `ops*.rs` (request surface, session/in-flight state),//! `run_task.rs` (turn execution), `session.rs` (agent build/fingerprint),-//! `progress_bridge.rs` (progress → socket event bridge), `presentation.rs`+//! `progress_bridge.rs` (progress → socket event bridge), `turn_activity.rs`+//! (per-turn inactivity record behind the idle guard), `presentation.rs`//! (reply delivery), `reply_persistence.rs` (durable reply write),//! `event_bus.rs` (broadcast + `DomainEvent` surface subscribers),//! `web_errors*.rs` (provider error classification), `schemas.rs` (RPC@@ -40,6 +41,8 @@ mod run_task;mod schemas;mod session;mod suggestions;+mod turn_activity;+mod turn_close;mod turn_timing;mod types;@@ -134,7 +137,7 @@ pub use ops::set_test_forced_run_chat_task_error;#[cfg(any(test, debug_assertions))]pub use ops::RUN_CHAT_TASK_TEST_LOCK;#[cfg(any(test, debug_assertions))]-pub use ops::{set_test_run_chat_task_block, TestRunChatTaskBlock};+pub use ops::{set_test_park_after_run, set_test_run_chat_task_block, TestRunChatTaskBlock};#[cfg(any(test, debug_assertions))]#[path = "mod_test_support_tests.rs"]diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rsindex 265248cf3c..ba2f0e50ec 100644--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@ -50,9 +50,11 @@ pub use test_hooks::set_test_forced_run_chat_task_error;#[cfg(any(test, debug_assertions))]pub use test_hooks::RUN_CHAT_TASK_TEST_LOCK;#[cfg(any(test, debug_assertions))]-pub use test_hooks::{set_test_run_chat_task_block, TestRunChatTaskBlock};+pub use test_hooks::{set_test_park_after_run, set_test_run_chat_task_block, TestRunChatTaskBlock};#[cfg(any(test, debug_assertions))]-pub(super) use test_hooks::{TEST_FORCED_RUN_CHAT_TASK_ERROR, TEST_RUN_CHAT_TASK_BLOCK};+pub(super) use test_hooks::{+ TEST_FORCED_RUN_CHAT_TASK_ERROR, TEST_PARK_AFTER_RUN, TEST_RUN_CHAT_TASK_BLOCK,+};pub(crate) use turn_guards::sentry_suppression_reason;#[cfg(test)]diff --git a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs b/crates/openhuman-core/src/web_chat/ops/test_hooks.rsindex cd2f71bd33..96da772a99 100644--- a/crates/openhuman-core/src/web_chat/ops/test_hooks.rs+++ b/crates/openhuman-core/src/web_chat/ops/test_hooks.rs@@ -61,3 +61,16 @@ pub async fn set_test_run_chat_task_block(block: Option<TestRunChatTaskBlock>) {let mut slot = TEST_RUN_CHAT_TASK_BLOCK.lock().await;*slot = block;}++/// Test hook: when set, `run_chat_task` parks after the agent run has+/// finished (its `TurnCompleted` already emitted) instead of saving and+/// returning the reply, like a turn wedged in its persistence plumbing. The+/// web-turn idle guard is what ends such a turn.+#[cfg(any(test, debug_assertions))]+pub(crate) static TEST_PARK_AFTER_RUN: std::sync::atomic::AtomicBool =+ std::sync::atomic::AtomicBool::new(false);++#[cfg(any(test, debug_assertions))]+pub fn set_test_park_after_run(park: bool) {+ TEST_PARK_AFTER_RUN.store(park, std::sync::atomic::Ordering::SeqCst);+}diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rsindex cc1fd3a8ed..73b8f3b46b 100644--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs@@ -1,37 +1,37 @@-//! The two standard web-channel turn guards — the wall-clock backstop and-//! cooperative cancellation — plus the Sentry-suppression / timeout-tagging-//! policy applied to whatever error a guarded turn produces.+//! The standard web-channel turn guards — the idle guard, the wall-clock+//! backstop and cooperative cancellation — plus the Sentry-suppression /+//! timeout-tagging policy applied to whatever error a guarded turn produces.use std::time::Duration;use tokio_util::sync::CancellationToken;+use super::super::turn_activity::{self, TurnActivity};+use super::super::turn_close::{StopCause, StoppedTurn};use super::super::types::WebChatTaskResult;/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).///-/// This is the OUTER safety net (issue #4746), and the single source of truth-/// for the turn's deadlines (`agent::turn_deadline`, default 900s). The-/// harness derives two earlier points from it:+/// This is the turn's fixed total ceiling (issue #4746), and the single source+/// of truth for the turn's deadlines (`agent::turn_deadline`, default 3600s,+/// the harness's own turn ceiling). The harness derives two earlier points+/// from it:///-/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 780s by default.-/// The harness pauses the run at its next safe point, and the session driver-/// writes the grounded close from the work already done, so a long turn-/// still delivers an answer.-/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 840s by default.-/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,-/// 3600s on its own) is clamped to it, so a tool or sub-agent call that runs-/// across the wind-down point ends in the harness's own typed `Timeout` →-/// `chat_error`.+/// * **wind-down** at backstop minus `min(120s, backstop/5)`, 3480s by+/// default. The harness pauses the run at its next safe point, and the+/// session driver writes the grounded close from the work already done, so a+/// long turn still delivers an answer.+/// * **hard stop** at backstop minus `min(60s, backstop/10)`, 3540s by default.+/// The harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`)+/// is clamped to it, so a tool or sub-agent call that runs across the+/// wind-down point ends in the harness's own typed `Timeout` → `chat_error`.///-/// So this backstop only fires if a turn wedges OUTSIDE the harness run, e.g.-/// in session assembly, the grounded close or the persistence plumbing. The-/// client then still gets a terminal `turn_timeout` event instead of an empty-/// reply or an endless `inference_heartbeat` stream. Before the derived-/// deadlines existed, the harness ceiling sat at 3600s, *after* this 900s-/// backstop. Long orchestrator turns were then dropped here, mid-work, with-/// nothing delivered. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to+/// It is not the hang detector. That is the idle guard+/// ([`turn_activity`](super::super::turn_activity)), which ends a turn that has+/// been silent with no model or tool call in flight. The backstop used to be+/// both, at 900s: a turn working steadily for 15 minutes was dropped exactly+/// like a wedged one. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`; set it to/// `0` to disable the backstop and the derived deadlines with it.fn web_turn_deadline() -> Option<Duration> {crate::agent::turn_deadline::configured_backstop()@@ -40,8 +40,8 @@ fn web_turn_deadline() -> Option<Duration> {/// The backstop for a turn that has to be allowed to run long: one on a local //// self-hosted provider (#6042), whose prefill alone can take many minutes. The/// explicit `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` override still wins; otherwise the-/// default is the local turn ceiling plus a grace period, never the hosted 900s,-/// which sat below the harness's own ceilings and pre-empted them.+/// default is the local turn ceiling plus a grace period, never the hosted+/// backstop, which sits below the local harness ceilings and would pre-empt them.async fn resolve_web_turn_deadline() -> Option<Duration> {if std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS").is_ok() {return web_turn_deadline();@@ -61,55 +61,118 @@ async fn resolve_web_turn_deadline() -> Option<Duration> {web_turn_deadline()}-/// Drive a chat-turn future under the wall-clock backstop.+/// The turn a guard may have to close: its thread and request ids.+pub(super) struct TurnIds {+ pub(super) thread_id: String,+ pub(super) request_id: String,+}++/// Which guard stopped the turn.+enum Stop {+ Ceiling(Duration),+ Idle(Duration),+}++/// Drive a chat-turn future under the idle guard and the wall-clock backstop.///-/// On elapse the inner future is dropped (cooperative teardown at its next-/// await point) and a synthetic `turn_timeout` error is returned, so the-/// caller's existing `chat_error` emission path fires. This is the outermost-/// guarantee that a wedged turn always ends in a terminal event rather than an-/// empty reply / an endless `inference_heartbeat` stream (issue #4746).+/// Either guard drops the inner future (cooperative teardown at its next+/// await point). The turn is then closed with a reply that says what it got+/// done and where it got stuck ([`turn_close`](super::super::turn_close)),+/// delivered like any other reply. Without `ids`, or when that reply cannot be+/// built, a synthetic `turn_timeout` error is returned instead, so the+/// caller's existing `chat_error` emission path fires. Either way a wedged+/// turn always ends in a terminal event rather than an empty reply / an+/// endless `inference_heartbeat` stream (issue #4746).+///+/// The idle guard fires first for a turn that stopped emitting progress with+/// nothing in flight; the backstop bounds a turn that stays busy past the+/// harness wind-down. `run_chat_task` taps the turn's progress stream into the+/// [`TurnActivity`] scoped here.async fn drive_turn_with_deadline<F>(deadline: Option<Duration>,+ idle_window: Option<Duration>,+ ids: Option<TurnIds>,fut: F,) -> Result<WebChatTaskResult, String>whereF: 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(crate::agent::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 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 stopped = StoppedTurn {+ thread_id: &ids.thread_id,+ request_id: &ids.request_id,+ cause,+ stuck,+ };+ match super::super::turn_close::close_reply(stopped).await {+ Some(reply) => Ok(reply),+ None => Err(fallback),}}-/// Run a chat-turn future under the two standard web-channel guards, inside the+/// Run a chat-turn future under the standard web-channel guards, inside the/// shared origin + approval-context scope: the cooperative cancel token-/// (interrupt/cancel paths tear the turn down at its next await point) and the-/// wall-clock backstop ([`drive_turn_with_deadline`]).+/// (interrupt/cancel paths tear the turn down at its next await point), the+/// idle guard and the wall-clock backstop ([`drive_turn_with_deadline`]).////// Returns `None` when the turn was cancelled cooperatively before producing a/// result — the cancelling side already emitted the user-facing `chat_error`,@@ -127,11 +190,17 @@ pub(crate) async fn run_turn_under_cancel_and_deadline<F>(whereF: 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,+ turn_activity::configured_idle_window(),+ ids,crate::agent::turn_origin::with_origin(origin,crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),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.rsindex 6ff95da15b..b557c8755c 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@@ -17,7 +17,7 @@ async fn guarded_turn_sees_the_backstop_deadline() {let backstop = Duration::from_secs(900);let seen = std::sync::Arc::new(std::sync::Mutex::new(None));let seen_in_turn = seen.clone();- let res = drive_turn_with_deadline(Some(backstop), async move {+ let res = drive_turn_with_deadline(Some(backstop), None, None, async move {*seen_in_turn.lock().unwrap() = crate::agent::turn_deadline::current();Ok(result("answer"))})@@ -33,7 +33,7 @@ async fn guarded_turn_sees_the_backstop_deadline() {#[tokio::test]async fn disabled_backstop_scopes_no_deadline() {- let res = drive_turn_with_deadline(None, async {+ let res = drive_turn_with_deadline(None, None, None, async {assert!(crate::agent::turn_deadline::current().is_none());Ok(result("ok"))})@@ -45,7 +45,7 @@ async fn disabled_backstop_scopes_no_deadline() {/// error, which is classified to user-facing copy, not silence.#[tokio::test(start_paused = true)]async fn backstop_firing_yields_a_classified_turn_timeout_error() {- let err = drive_turn_with_deadline(Some(Duration::from_secs(900)), async {+ let err = drive_turn_with_deadline(Some(Duration::from_secs(900)), None, None, async {std::future::pending::<()>().await;Ok(result("never"))})@@ -58,3 +58,67 @@ async fn backstop_firing_yields_a_classified_turn_timeout_error() {assert_eq!(classified.error_type, "turn_timeout");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}");+}diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rsindex 4fbdf78a2f..7a8760c722 100644--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs@@ -16,6 +16,10 @@ use super::types::ChatRequestMetadata;mod subagent_events;#[path = "progress_bridge_text_events.rs"]mod text_events;+#[path = "progress_bridge_tool_progress.rs"]+mod tool_progress;+#[path = "progress_bridge_trace.rs"]+mod trace;use subagent_events::BridgeCtx;/// Cadence of the `inference_heartbeat` liveness beat the bridge emits while a@@ -325,69 +329,9 @@ pub(crate) fn spawn_progress_bridge(let mut turn_state =TurnStateMirror::new(turn_state_store, thread_id.clone(), request_id.clone());- // #3886: structured tracing export. When enabled, fold the same- // progress stream into OTel/Langfuse-style spans correlated by session- // id (falling back to the thread id for headless/autonomous runs).- // `None` (both remote and local exporters disabled) is zero-cost.- let mut journal_trace_ctx = None;- let mut span_collector = if config.observability.share_usage_data- || config.observability.agent_tracing.enabled- {- use crate::agent::progress_tracing::SpanCollector;- use tinyagents_harness::observability::trace_export as te;- // One trace per turn: the trace id is unique per request, while the- // thread id rides along as the Langfuse `sessionId` so a- // conversation's per-turn traces still group under one session.- let base = te::trace_session_id(metadata.session_id, &thread_id);- let trace_id = format!("{base}:{request_id}");- // Attribute the trace to the *real* authenticated user (cached- // stored credential identity: id, else email) — the transport client- // id (socket client / "system") is NOT a user; it rides along as- // the separate `client.id` metadata attribute. The backend stamps- // the authenticated JWT user on every accepted trace.- let identity = crate::security::credentials::identity::peek_credential_user_identity();- let user_id = identity- .and_then(|i| i.id.or(i.email))- .or_else(|| session_profile_user_attribution(&config));- let user_attributed = user_id.is_some();- // Run origin for trace metadata: the request's source tag- // ("ptt"/"dictation"/"type"/"autonomous"/…), else a- // plain interactive chat turn.- let run_type = te::RunType::from_source(metadata.source.as_deref());- let channel_source = metadata- .source- .clone()- .unwrap_or_else(|| "chat".to_string());- // Storage-level privacy gate (#4454): capture_content (off by- // default) rides on the TraceContext so the collector only attaches- // prompt/reply content to spans when the operator opted in — no- // exporter can serialize prompt/reply text otherwise.- let capture_content = config.observability.agent_tracing.capture_content;- log::debug!(- "[web_channel][bridge] trace context trace_id={} user_attributed={} \- agent_id={:?} channel_source={} run_type={} capture_content={} request_id={}",- trace_id,- user_attributed,- metadata.agent_id,- channel_source,- run_type.as_str(),- capture_content,- request_id,- );- let mut trace_ctx = te::TraceContext::new(trace_id, user_id)- .with_session_group(thread_id.clone())- .with_client_id(client_id.clone())- .with_channel_source(channel_source)- .with_run_type(run_type)- .with_capture_content(capture_content);- if let Some(agent_id) = metadata.agent_id.clone() {- trace_ctx = trace_ctx.with_agent_id(agent_id);- }- journal_trace_ctx = Some(trace_ctx.clone());- Some(SpanCollector::new(trace_ctx))- } else {- None- };+ // #3886: structured tracing export (`progress_bridge_trace.rs`).+ let (mut span_collector, mut journal_trace_ctx) =+ trace::span_collector(&config, &metadata, &client_id, &thread_id, &request_id).unzip();// #4270: emit a periodic liveness beat for the whole in-flight turn so// the frontend silence timer never false-fires during a long prefill or@@ -1151,6 +1095,10 @@ pub(crate) fn spawn_progress_bridge();}}+ AgentProgress::ToolCallProgress { call_id, message } => {+ let ids = (client_id.as_str(), thread_id.as_str(), request_id.as_str());+ tool_progress::publish(&mut emit_seq, ids, call_id, message);+ }AgentProgress::TurnContent { .. } => {// Prompt/reply content is attached to the trace span by the// span collector above; the ledger/telemetry bridge ignores it.diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_tool_progress.rs b/crates/openhuman-core/src/web_chat/progress_bridge_tool_progress.rsnew file mode 100644index 0000000000..d5c5fbca27--- /dev/null+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tool_progress.rs@@ -0,0 +1,31 @@+//! A running tool's status line, as `tool_progress` socket events.+//!+//! Carries the call id of the open `tool_call` row and a human-readable+//! `message` (for a shell call: elapsed time, output written, last output+//! line). Rendering is the client's choice; the event also proves the call is+//! alive between its `tool_call` and `tool_result`.++use crate::web_chat::WebChannelEvent;++/// Publish one status line for the running call `call_id`. `ids` is+/// `(client_id, thread_id, request_id)`.+pub(super) fn publish(+ emit_seq: &mut u64,+ (client_id, thread_id, request_id): (&str, &str, &str),+ call_id: String,+ message: String,+) {+ log::trace!("[web_channel][bridge] tool_progress call_id={call_id} request_id={request_id}");+ super::publish_seq_stamped(+ emit_seq,+ WebChannelEvent {+ event: "tool_progress".to_string(),+ client_id: client_id.to_string(),+ thread_id: thread_id.to_string(),+ request_id: request_id.to_string(),+ tool_call_id: Some(call_id),+ message: Some(message),+ ..Default::default()+ },+ );+}diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_trace.rs b/crates/openhuman-core/src/web_chat/progress_bridge_trace.rsnew file mode 100644index 0000000000..3836d5b74b--- /dev/null+++ b/crates/openhuman-core/src/web_chat/progress_bridge_trace.rs@@ -0,0 +1,74 @@+//! Structured tracing export for one bridged turn (#3886).+//!+//! When enabled, the bridge folds the turn's progress stream into+//! OTel/Langfuse-style spans correlated by session id (falling back to the+//! thread id for headless/autonomous runs). Disabled (both the remote and the+//! local exporter off), it costs nothing.++use crate::agent::progress_tracing::SpanCollector;+use tinyagents_harness::observability::trace_export as te;++use super::super::types::ChatRequestMetadata;++/// The span collector for the turn, and the trace context the journal export+/// reuses after the turn ends. `None` when tracing is disabled.+pub(super) fn span_collector(+ config: &crate::config::Config,+ metadata: &ChatRequestMetadata,+ client_id: &str,+ thread_id: &str,+ request_id: &str,+) -> Option<(SpanCollector, te::TraceContext)> {+ if !(config.observability.share_usage_data || config.observability.agent_tracing.enabled) {+ return None;+ }+ // One trace per turn: the trace id is unique per request, while the+ // thread id rides along as the Langfuse `sessionId` so a+ // conversation's per-turn traces still group under one session.+ let base = te::trace_session_id(metadata.session_id, thread_id);+ let trace_id = format!("{base}:{request_id}");+ // Attribute the trace to the *real* authenticated user (cached+ // stored credential identity: id, else email) — the transport client+ // id (socket client / "system") is NOT a user; it rides along as+ // the separate `client.id` metadata attribute. The backend stamps+ // the authenticated JWT user on every accepted trace.+ let identity = crate::security::credentials::identity::peek_credential_user_identity();+ let user_id = identity+ .and_then(|i| i.id.or(i.email))+ .or_else(|| super::session_profile_user_attribution(config));+ let user_attributed = user_id.is_some();+ // Run origin for trace metadata: the request's source tag+ // ("ptt"/"dictation"/"type"/"autonomous"/…), else a+ // plain interactive chat turn.+ let run_type = te::RunType::from_source(metadata.source.as_deref());+ let channel_source = metadata+ .source+ .clone()+ .unwrap_or_else(|| "chat".to_string());+ // Storage-level privacy gate (#4454): capture_content (off by+ // default) rides on the TraceContext so the collector only attaches+ // prompt/reply content to spans when the operator opted in — no+ // exporter can serialize prompt/reply text otherwise.+ let capture_content = config.observability.agent_tracing.capture_content;+ log::debug!(+ "[web_channel][bridge] trace context trace_id={} user_attributed={} \+ agent_id={:?} channel_source={} run_type={} capture_content={} request_id={}",+ trace_id,+ user_attributed,+ metadata.agent_id,+ channel_source,+ run_type.as_str(),+ capture_content,+ request_id,+ );+ let mut trace_ctx = te::TraceContext::new(trace_id, user_id)+ .with_session_group(thread_id.to_string())+ .with_client_id(client_id.to_string())+ .with_channel_source(channel_source)+ .with_run_type(run_type)+ .with_capture_content(capture_content);+ if let Some(agent_id) = metadata.agent_id.clone() {+ trace_ctx = trace_ctx.with_agent_id(agent_id);+ }+ Some((SpanCollector::new(trace_ctx.clone()), trace_ctx))+}diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsindex f3c8051754..3aefab78e1 100644--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ b/crates/openhuman-core/src/web_chat/run_task.rs@@ -149,6 +149,12 @@ pub(crate) async fn run_chat_task(// defense-in-depth; extraction of durable state (like a workflow// proposal) must not depend on any single progress event surviving.let (progress_tx, progress_rx) = tokio::sync::mpsc::channel(256);+ // Under the web-turn guard, fold every event into the turn's activity+ // record (the idle guard's input) on its way to the bridge.+ let progress_rx = match super::turn_activity::current() {+ Some(activity) => super::turn_activity::tap(activity, progress_rx, 256),+ None => progress_rx,+ };// The channel is fresh here. Record the user input even if the turn fails// before a committed reply can emit its final TurnContent event.let _ = progress_tx.try_send(AgentProgress::TurnContent {@@ -320,6 +326,15 @@ pub(crate) async fn run_chat_task(.await;}+ // Test hook: wedge the turn after its run, as a stuck save would.+ #[cfg(any(test, debug_assertions))]+ if super::ops::TEST_PARK_AFTER_RUN.load(std::sync::atomic::Ordering::SeqCst) {+ log::debug!(+ "[web-channel][test] parking run_chat_task after the run request_id={request_id}"+ );+ std::future::pending::<()>().await;+ }+agent.set_on_progress(None);// The caller publishes the terminal `chat_done`/`chat_error` as soon asdiff --git a/crates/openhuman-core/src/web_chat/turn_activity.rs b/crates/openhuman-core/src/web_chat/turn_activity.rsnew file mode 100644index 0000000000..bac7b6e639--- /dev/null+++ b/crates/openhuman-core/src/web_chat/turn_activity.rs@@ -0,0 +1,273 @@+//! 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,+}++/// 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,+ })),+ }+ }++ 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 {+ /// 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 {+ 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 --git a/crates/openhuman-core/src/web_chat/turn_activity_tests.rs b/crates/openhuman-core/src/web_chat/turn_activity_tests.rsnew file mode 100644index 0000000000..670ef257ed--- /dev/null+++ b/crates/openhuman-core/src/web_chat/turn_activity_tests.rs@@ -0,0 +1,246 @@+use super::*;++fn iteration_started() -> AgentProgress {+ AgentProgress::IterationStarted {+ iteration: 1,+ max_iterations: 50,+ }+}++fn model_call_completed(subagent_task_id: Option<&str>) -> AgentProgress {+ AgentProgress::ModelCallCompleted {+ model: "m".into(),+ provider_id: "managed".into(),+ subagent_task_id: subagent_task_id.map(str::to_string),+ input: None,+ output: None,+ iteration: 1,+ input_tokens: 0,+ output_tokens: 0,+ cached_input_tokens: 0,+ cache_creation_tokens: 0,+ reasoning_tokens: 0,+ cost_usd: None,+ }+}++fn tool_started(call_id: &str) -> AgentProgress {+ AgentProgress::ToolCallStarted {+ call_id: call_id.into(),+ tool_name: "shell".into(),+ arguments: serde_json::json!({}),+ iteration: 1,+ display_label: None,+ display_detail: None,+ }+}++fn tool_completed(call_id: &str) -> AgentProgress {+ AgentProgress::ToolCallCompleted {+ call_id: call_id.into(),+ tool_name: "shell".into(),+ success: true,+ output_chars: 0,+ output: String::new(),+ arguments: None,+ elapsed_ms: 0,+ iteration: 1,+ failure: None,+ display_label: None,+ display_detail: None,+ structured: None,+ }+}++fn text(delta: &str) -> AgentProgress {+ AgentProgress::TextDelta {+ delta: delta.into(),+ iteration: 1,+ }+}++const WINDOW: Duration = Duration::from_secs(900);++#[test]+fn parse_idle_window_defaults_and_disables() {+ assert_eq!(parse_idle_window(None), Some(Duration::from_secs(900)));+ assert_eq!(parse_idle_window(Some("x")), Some(Duration::from_secs(900)));+ assert_eq!(+ parse_idle_window(Some(" 60 ")),+ Some(Duration::from_secs(60))+ );+ assert_eq!(parse_idle_window(Some("0")), None);+}++#[tokio::test(start_paused = true)]+async fn every_event_restarts_the_idle_clock() {+ let activity = TurnActivity::new();+ tokio::time::advance(Duration::from_secs(300)).await;+ assert_eq!(+ activity.idle_for(Instant::now()),+ Some(Duration::from_secs(300))+ );+ activity.observe(&text("hi"));+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++/// A provider retrying a failed call is silent for minutes (289s observed)+/// while the turn is healthy: an open model call is never idle.+#[tokio::test(start_paused = true)]+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;+ assert_eq!(activity.idle_for(Instant::now()), None);+ activity.observe(&model_call_completed(None));+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++#[tokio::test(start_paused = true)]+async fn a_subagent_model_call_does_not_close_the_parent_call() {+ let activity = TurnActivity::new();+ activity.observe(&iteration_started());+ activity.observe(&model_call_completed(Some("task-1")));+ assert_eq!(activity.idle_for(Instant::now()), None);+}++/// A long, silent shell call is in flight, not idle, and parallel calls stay+/// open until the last one completes.+#[tokio::test(start_paused = true)]+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;+ activity.observe(&tool_completed("a"));+ assert_eq!(activity.idle_for(Instant::now()), None);+ activity.observe(&tool_completed("b"));+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++#[tokio::test(start_paused = true)]+async fn turn_completed_closes_everything_still_open() {+ let activity = TurnActivity::new();+ activity.observe(&iteration_started());+ activity.observe(&tool_started("a"));+ activity.observe(&AgentProgress::TurnCompleted {+ iterations: 1,+ stop: None,+ });+ assert_eq!(activity.idle_for(Instant::now()), Some(Duration::ZERO));+}++#[tokio::test(start_paused = true)]+async fn watchdog_fires_after_the_window_of_silence() {+ let activity = TurnActivity::new();+ let idle = idle_watchdog(activity, WINDOW).await;+ assert!(idle >= WINDOW);+}++/// The turn that motivated this: 53 model rounds over 15 minutes, one every+/// ~17s, each with a tool call. It must outlive the old 900s backstop.+#[tokio::test(start_paused = true)]+async fn a_busy_turn_outlives_the_window() {+ let activity = TurnActivity::new();+ let watchdog = tokio::spawn(idle_watchdog(activity.clone(), WINDOW));+ for round in 0..120 {+ let call = format!("call-{round}");+ activity.observe(&iteration_started());+ tokio::time::sleep(Duration::from_secs(10)).await;+ activity.observe(&model_call_completed(None));+ activity.observe(&tool_started(&call));+ tokio::time::sleep(Duration::from_secs(7)).await;+ activity.observe(&tool_completed(&call));+ }+ // 120 rounds × 17s = 34 minutes.+ assert!(!watchdog.is_finished());+ watchdog.abort();+}++#[tokio::test(start_paused = true)]+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;+ assert!(!watchdog.is_finished());+ activity.observe(&tool_completed("build"));+ let idle = watchdog.await.expect("watchdog task");+ assert!(idle >= WINDOW);+}++#[tokio::test]+async fn tap_records_and_forwards_in_order() {+ let activity = TurnActivity::new();+ let (tx, rx) = mpsc::channel(4);+ let mut bridge_rx = tap(activity.clone(), rx, 4);+ tx.send(tool_started("a")).await.unwrap();+ tx.send(text("x")).await.unwrap();+ drop(tx);+ assert!(matches!(+ bridge_rx.recv().await,+ Some(AgentProgress::ToolCallStarted { .. })+ ));+ assert!(matches!(+ bridge_rx.recv().await,+ Some(AgentProgress::TextDelta { .. })+ ));+ assert!(+ bridge_rx.recv().await.is_none(),+ "closes with the agent side"+ );+ assert_eq!(activity.idle_for(Instant::now()), None, "call a still open");+}++#[tokio::test]+async fn task_local_scope_is_visible_inside_only() {+ assert!(current().is_none());+ let activity = TurnActivity::new();+ assert!(with_turn_activity(activity, async { current() })+ .await+ .is_some());+ assert!(current().is_none());+}++#[tokio::test]+async fn stuck_point_names_where_the_turn_went_quiet() {+ let activity = TurnActivity::new();+ activity.observe(&AgentProgress::TurnContent {+ input: Some("hi".into()),+ output: None,+ });+ assert_eq!(activity.stuck_point(), StuckPoint::BeforeRun);++ activity.observe(&iteration_started());+ activity.observe(&model_call_completed(None));+ activity.observe(&AgentProgress::TurnCostUpdated {+ model: "m".into(),+ iteration: 1,+ input_tokens: 0,+ output_tokens: 0,+ cached_input_tokens: 0,+ total_usd: 0.0,+ });+ assert_eq!(+ activity.stuck_point(),+ StuckPoint::BetweenSteps {+ after: "the model replied".into()+ },+ "a cost tick is bookkeeping, not a step"+ );++ activity.observe(&tool_started("a"));+ activity.observe(&tool_completed("a"));+ assert_eq!(+ activity.stuck_point(),+ StuckPoint::BetweenSteps {+ after: "the `shell` tool finished".into()+ }+ );++ activity.observe(&AgentProgress::TurnCompleted {+ iterations: 1,+ stop: None,+ });+ assert_eq!(activity.stuck_point(), StuckPoint::AfterRun);+}diff --git a/crates/openhuman-core/src/web_chat/turn_close.rs b/crates/openhuman-core/src/web_chat/turn_close.rsnew file mode 100644index 0000000000..222f22889d--- /dev/null+++ b/crates/openhuman-core/src/web_chat/turn_close.rs@@ -0,0 +1,295 @@+//! 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 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,+}++/// 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');+ }+ }+ out.push_str("\nSay \"continue\" and I'll pick up from here.");+ out+}++fn close_request(turn: &StoppedTurn<'_>, evidence: &Evidence) -> ModelRequest {+ let user_prompt = format!(+ "The turn was stopped because {}.\nWhere it got stuck: {}.\n\n{}",+ turn.cause.describe(),+ turn.stuck.describe(),+ evidence.render()+ );+ provider::openhuman_backend_model::without_reasoning(+ ModelRequest::new(vec![+ Message::system(CLOSE_SYSTEM_PROMPT),+ 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+ }+ }+}++/// The reply that closes `turn`, or `None` when even the configuration+/// cannot be read (the caller then reports the stop as an error).+pub(crate) async fn close_reply(turn: StoppedTurn<'_>) -> Option<WebChatTaskResult> {+ let config = match config_rpc::load_config_with_timeout().await {+ Ok(config) => config,+ Err(error) => {+ log::warn!(+ "{LOG_PREFIX} config load failed request_id={}: {error}",+ turn.request_id+ );+ return None;+ }+ };+ let snapshot = TurnStateStore::new(config.workspace_dir.clone())+ .get_turn(turn.thread_id, turn.request_id)+ .unwrap_or_else(|error| {+ log::warn!(+ "{LOG_PREFIX} turn snapshot unreadable request_id={}: {error}",+ turn.request_id+ );+ None+ });+ 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 --git a/crates/openhuman-core/src/web_chat/turn_close_tests.rs b/crates/openhuman-core/src/web_chat/turn_close_tests.rsnew file mode 100644index 0000000000..a2a19d900a--- /dev/null+++ b/crates/openhuman-core/src/web_chat/turn_close_tests.rs@@ -0,0 +1,138 @@+use super::*;+use tinyagents_session::turn_state::ToolTimelineEntry;++fn entry(value: serde_json::Value) -> ToolTimelineEntry {+ serde_json::from_value(value).expect("tool timeline entry")+}++fn snapshot() -> TurnState {+ let mut state = TurnState::started("thread-1", "req-1", 50, "2026-10-13T21:28:58Z");+ state.tool_timeline = vec![+ entry(serde_json::json!({+ "id": "c1", "name": "file_write", "round": 1, "status": "success",+ "displayName": "Write file", "detail": "crates/tiny-artifacts/Cargo.toml"+ })),+ entry(serde_json::json!({+ "id": "c2", "name": "shell", "round": 2, "status": "error",+ "detail": "cargo build",+ "failure": {+ "class": "CommandFailed", "category": "Recoverable", "recoverable": true,+ "causePlain": "the build failed", "nextAction": "fix the error"+ }+ })),+ entry(serde_json::json!({+ "id": "c3", "name": "shell", "round": 3, "status": "running",+ "detail": "git worktree add"+ })),+ ];+ state.transcript = vec![+ TranscriptItem::Narration {+ round: 1,+ seq: 0,+ text: "Creating the crate first.".into(),+ },+ TranscriptItem::Narration {+ round: 3,+ seq: 4,+ text: "Now setting up the worktree.".into(),+ },+ ];+ state+}++fn stopped(cause: StopCause, stuck: StuckPoint) -> StoppedTurn<'static> {+ StoppedTurn {+ thread_id: "thread-1",+ request_id: "req-1",+ cause,+ stuck,+ }+}++#[test]+fn evidence_lists_every_step_with_its_outcome_and_the_last_narration() {+ let evidence = Evidence::from_snapshot(Some(&snapshot()));+ assert_eq!(+ evidence.steps,+ vec![+ "done: Write file (crates/tiny-artifacts/Cargo.toml)".to_string(),+ "failed: shell (cargo build) — the build failed".to_string(),+ "still running: shell (git worktree add)".to_string(),+ ]+ );+ assert_eq!(+ evidence.narration.as_deref(),+ Some("Now setting up the worktree.")+ );+}++#[test]+fn evidence_keeps_only_the_latest_steps() {+ let mut state = snapshot();+ let row = state.tool_timeline[0].clone();+ state.tool_timeline = vec![row; MAX_STEPS + 5];+ assert_eq!(Evidence::from_snapshot(Some(&state)).steps.len(), MAX_STEPS);+}++#[test]+fn no_snapshot_is_no_evidence() {+ assert_eq!(Evidence::from_snapshot(None), Evidence::default());+}++#[test]+fn plain_reply_says_why_where_and_what_got_done() {+ let turn = stopped(+ StopCause::Idle(Duration::from_secs(900)),+ StuckPoint::BetweenSteps {+ after: "the `shell` tool finished".into(),+ },+ );+ let reply = plain_reply(&turn, &Evidence::from_snapshot(Some(&snapshot())));+ assert!(+ reply.starts_with(+ "I stopped this turn because nothing happened for 15 minutes. It got stuck \+ between steps: the `shell` tool finished, and the agent's next step never \+ started."+ ),+ "{reply}"+ );+ assert!(reply.contains("- failed: shell (cargo build) — the build failed"));+ assert!(reply.ends_with("Say \"continue\" and I'll pick up from here."));+}++#[test]+fn plain_reply_with_nothing_recorded() {+ let turn = stopped(+ StopCause::Ceiling(Duration::from_secs(3_600)),+ StuckPoint::AfterRun,+ );+ let reply = plain_reply(&turn, &Evidence::default());+ assert!(+ reply.contains("it hit its time limit of 60 minutes"),+ "{reply}"+ );+ assert!(reply.contains("while its reply was being saved"), "{reply}");+ assert!(reply.contains("No steps had been recorded yet."), "{reply}");+}++#[test]+fn durations_read_naturally() {+ assert_eq!(minutes(Duration::from_secs(1)), "1 second");+ assert_eq!(minutes(Duration::from_secs(45)), "45 seconds");+ assert_eq!(minutes(Duration::from_secs(60)), "1 minute");+ assert_eq!(minutes(Duration::from_secs(900)), "15 minutes");+}++#[test]+fn the_close_request_carries_the_cause_the_stuck_point_and_the_evidence() {+ let turn = stopped(+ StopCause::Idle(Duration::from_secs(900)),+ StuckPoint::BeforeRun,+ );+ let request = close_request(&turn, &Evidence::from_snapshot(Some(&snapshot())));+ let prompt = format!("{:?}", request.messages);+ assert!(prompt.contains("nothing happened for 15 minutes"));+ assert!(prompt.contains("before the agent started"));+ assert!(prompt.contains("still running: shell (git worktree add)"));+ assert!(request.tools.is_empty(), "the close call has no tools");+}diff --git a/crates/openhuman-core/src/web_chat/web_errors.rs b/crates/openhuman-core/src/web_chat/web_errors.rsindex 47b9fef5c9..65cb39d2d2 100644--- a/crates/openhuman-core/src/web_chat/web_errors.rs+++ b/crates/openhuman-core/src/web_chat/web_errors.rs@@ -16,5 +16,6 @@ pub(crate) use budget::{pub(crate) use classify::{classify_inference_error, ClassifiedError};pub(crate) use retry::{is_non_retryable_rate_limit_text, retry_after_hint};pub(crate) use timeout::{- is_outer_backstop_timeout, is_turn_timeout_error, turn_timeout_error_message,+ is_outer_backstop_timeout, is_turn_timeout_error, turn_idle_error_message,+ turn_timeout_error_message,};diff --git a/crates/openhuman-core/src/web_chat/web_errors/timeout.rs b/crates/openhuman-core/src/web_chat/web_errors/timeout.rsindex 52e3e9d13e..7a0e56ae5f 100644--- a/crates/openhuman-core/src/web_chat/web_errors/timeout.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/timeout.rs@@ -20,6 +20,18 @@ pub(crate) fn turn_timeout_error_message(secs: u64) -> String {)}+/// Build the synthetic error string a web turn raises when its idle guard+/// (`web_chat::turn_activity`) fires: no progress event, and no model or tool+/// call in flight, for `secs`. Carries [`TURN_TIMEOUT_MARKER`], so it gets the+/// same `turn_timeout` copy and the same Sentry treatment as the backstop.+/// Nothing was in flight when it fired, by construction.+pub(crate) fn turn_idle_error_message(secs: u64) -> String {+ format!(+ "{TURN_TIMEOUT_MARKER}: agent turn made no progress for {secs}s with no model or \+ tool call in flight (it wedged outside a model or tool call)"+ )+}+/// True when `err` is a turn wall-clock timeout — either the synthetic marker/// raised by the web turn driver's outer backstop ([`TURN_TIMEOUT_MARKER`]), or/// the tinyagents harness's own `TinyAgentsError::Timeout` (issue #4746). Thediff --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 a7c86a3425..40db0932cf 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@@ -303,13 +303,13 @@ async fn cancel_chat_cooperatively_stops_in_flight_turn() {/// Issue #4746: a turn that never produces a terminal event on its own — a/// 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 `chat_error`, never an empty reply / an endless `inference_heartbeat`-/// stream until the socket dies. The web turn driver's wall-clock backstop fires-/// and emits a graceful, retryable `turn_timeout` chat_error, and tears the-/// wedged future down cooperatively (its `Drop` guard flips well before the 30s-/// test sleep would elapse).+/// 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.#[tokio::test]-async fn wedged_turn_hits_wall_clock_backstop_and_emits_turn_timeout_chat_error() {+async fn wedged_turn_hits_wall_clock_backstop_and_is_closed_with_a_reply() {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,31 +336,20 @@ async fn wedged_turn_hits_wall_clock_backstop_and_emits_turn_timeout_chat_error(.await.expect("turn should start");- let recv = timeout(Duration::from_secs(20), async move {- loop {- let event = rx.recv().await.expect("event stream should stay open");- if event.event == "chat_error" && event.request_id == request_id {- return event;- }- }- })+ let reply = timeout(+ Duration::from_secs(20),+ terminal_reply(&mut rx, &request_id),+ ).await- .expect("a wedged turn must still emit a terminal chat_error (issue #4746)");-- assert_eq!(- recv.error_type.as_deref(),- Some("turn_timeout"),- "the backstop must surface a graceful turn_timeout, not a generic error"- );- assert_eq!(- recv.error_retryable,- Some(true),- "a turn_timeout is safe to retry in the same thread"+ .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}");- let message = recv.message.unwrap_or_default();+ assert!(reply.contains("before the agent started"), "{reply}");assert!(- !message.contains("openhuman_turn_wall_clock_timeout"),- "internal marker must not leak into user copy: {message}"+ !reply.contains("openhuman_turn_wall_clock_timeout"),+ "internal marker must not leak into user copy: {reply}");// The wedged future is torn down cooperatively when the backstop drops it@@ -371,6 +360,52 @@ async fn wedged_turn_hits_wall_clock_backstop_and_emits_turn_timeout_chat_error(// `OPENHUMAN_WEB_TURN_TIMEOUT_SECS` is cleared by `_env_guard`'s Drop.}+/// 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.+#[tokio::test]+async fn silent_turn_hits_idle_guard_and_is_closed_with_a_reply() {+ 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")+ .await;+ let block = make_block();+ set_test_run_chat_task_block(Some(block.clone())).await;++ let mut rx = subscribe_web_channel_events();+ let request_id = start_chat(+ "idle-client",+ "idle-thread",+ "park me until the idle guard fires",+ None,+ None,+ None,+ None,+ ChatRequestMetadata::default(),+ )+ .await+ .expect("turn should start");++ let reply = timeout(+ Duration::from_secs(20),+ terminal_reply(&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}"+ );+ wait_for_flag(&block.dropped, "silent turn future dropped by idle guard").await;++ set_test_run_chat_task_block(None).await;+}+/// A `parallel`-mode turn runs CONCURRENTLY with the primary turn on the SAME/// thread (it does not interrupt it), and a thread-level cancel tears down both.#[tokio::test]@@ -606,3 +641,23 @@ async fn unscoped_cancel_stops_the_threads_detached_subagents() {.expect("aborted child finishes promptly");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(+ rx: &mut tokio::sync::broadcast::Receiver<crate::web_chat::WebChannelEvent>,+ request_id: &str,+) -> String {+ 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),+ _ => {}+ }+ }+}diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjsindex 68d6852bbf..b9ba1f60de 100644--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@ -37,7 +37,7 @@ const LEGACY_LIMIT_ENTRIES = [["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 973],["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; itsdiff --git a/tests/agent_harness_e2e.rs b/tests/agent_harness_e2e.rsindex 40e8e1da6a..6daf33cfc6 100644--- a/tests/agent_harness_e2e.rs+++ b/tests/agent_harness_e2e.rs@@ -13,6 +13,8 @@#[path = "support/env_guard.rs"]mod env_guard;+#[path = "support/linked_modules.rs"]+mod linked_modules;#[path = "support/scripted_stack.rs"]mod scripted_stack;use env_guard::EnvVarGuard;@@ -3104,9 +3106,11 @@ async fn model_call_ceiling_bounds_a_wedged_call_below_the_turn_deadline_inner()// `Timeout` onto the same generic `turn_timeout` copy — so an inherited// value below the 8s bound asserted here would fire first, produce an// identical terminal, and let the whole test pass with the per-call ceiling- // unwired. Cleared, not set, so it falls back to its 900s default and can- // play no part in the outcome.+ // unwired. Cleared, not set, so it falls back to its 3600s default and can+ // play no part in the outcome. The web idle guard reads its own variable;+ // it is cleared for the same reason.let _web_backstop = EnvVarGuard::unset("OPENHUMAN_WEB_TURN_TIMEOUT_SECS");+ let _web_idle = EnvVarGuard::unset("OPENHUMAN_WEB_TURN_IDLE_SECS");// Every upstream reply is held for 25s — comfortably past the 2s per-call// ceiling and comfortably short of the 600s turn deadline. Armed globally@@ -5216,3 +5220,246 @@ async fn a_wrong_tool_guess_is_retried_not_treated_as_an_auth_blocker_inner() {stack.shutdown();}++// ─── Web-turn idle guard ─────────────────────────────────────────────────────+//+// Both tests shrink the idle window (`OPENHUMAN_WEB_TURN_IDLE_SECS`) to 30s so+// the guard's logic runs in seconds instead of the 900s default. Not smaller:+// checking out a cold session on this stack emits no progress and takes+// 6-15 seconds here, which a smaller window rightly counts as a stall.+//+// Local only: the shell steps need TinyBox built in, so the section is+// compiled only with `--features linked-modules` (which CI never enables).+// Run with `OPENHUMAN_MODULE_SOURCE=linked RUST_MIN_STACK=67108864 cargo test+// -p openhuman-cli --features linked-modules --test agent_harness_e2e --+// long_shell_call_outlives stalled_turn_is_stopped --test-threads=1`.+//+// Shell runs without the native jail (`OPENHUMAN_SANDBOX=off`), which reports+// itself unsuitable on a macOS test host; the unjailed path uses the same+// TinyBox output loop and keeps TinyBox's command analysis.+#[cfg(feature = "linked-modules")]+mod idle_guard_local {+ use super::*;++ /// Wait for `event_name` for this request, failing fast if the turn ends+ /// first: the idle guard must not have stopped it.+ async fn wait_for_event_before_terminal(+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<Value>,+ event_name: &str,+ request_id: &str,+ timeout: Duration,+ ) -> Value {+ let deadline = tokio::time::Instant::now() + timeout;+ loop {+ let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());+ let event = match tokio::time::timeout(remaining, rx.recv()).await {+ Ok(Some(event)) => event,+ Ok(None) => panic!("SSE channel closed waiting for {event_name}"),+ Err(_) => panic!("timed out waiting for {event_name}"),+ };+ if event.get("request_id").and_then(Value::as_str) != Some(request_id) {+ continue;+ }+ match event.get("event").and_then(Value::as_str) {+ Some(name) if name == event_name => return event,+ Some("chat_done") | Some("chat_error") => {+ panic!("turn ended before {event_name}: {event}")+ }+ _ => {}+ }+ }+ }++ /// A shell call that runs well past the idle window keeps the turn alive: an+ /// open tool call is never idle, and the call reports progress while it runs.+ /// Killing its process from outside the stack ends the call with a failed+ /// result, and the turn carries on to the model's next reply. One killed+ /// command does not wedge the turn, so the idle guard never fires.+ #[test]+ fn long_shell_call_outlives_the_idle_window_and_survives_an_external_kill() {+ run_on_agent_stack(+ "long_shell_call_outlives_the_idle_window_and_survives_an_external_kill",+ long_shell_call_outlives_the_idle_window_and_survives_an_external_kill_inner,+ );+ }++ async fn long_shell_call_outlives_the_idle_window_and_survives_an_external_kill_inner() {+ let _lock = env_lock();+ super::linked_modules::install_if_requested();+ let _idle = EnvVarGuard::set("OPENHUMAN_WEB_TURN_IDLE_SECS", "30");+ let _unjailed = EnvVarGuard::set("OPENHUMAN_SANDBOX", "off");+ // A sleep length no other process uses, so the kill below hits only this+ // command.+ let command = format!("sleep {}.{}", 7_000 + std::process::id() % 1_000, 37);+ reset_script(vec![+ tool_call_completion("shell", json!({ "command": command })),+ text_completion("The long command was stopped. KILLED_SHELL_CANARY"),+ ]);+ let stack = boot_stack().await;+ let mut events = spawn_sse_collector(format!(+ "{}/events?client_id=harness-idle-shell",+ stack.rpc_base+ ))+ .await;+ let request_id = send_web_chat(+ &stack.rpc_base,+ 610,+ "harness-idle-shell",+ "thread-idle-shell",+ "run the long command",+ )+ .await;++ let call = wait_for_event_before_terminal(+ &mut events,+ "tool_call",+ &request_id,+ Duration::from_secs(60),+ )+ .await;+ assert_eq!(call.get("tool_name").and_then(Value::as_str), Some("shell"));++ // Inside the 30s idle window the call reports progress (every 15s); it+ // stays open past the window below, which the guard counts as active.+ let progress = wait_for_event_before_terminal(+ &mut events,+ "tool_progress",+ &request_id,+ Duration::from_secs(30),+ )+ .await;+ let message = progress+ .get("message")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(+ message.starts_with("running "),+ "progress message: {progress}"+ );+ assert_eq!(+ progress.get("tool_call_id"),+ call.get("tool_call_id"),+ "progress belongs to the running call"+ );++ // Kill the command from outside the stack.+ let killed = std::process::Command::new("pkill")+ .args(["-f", &command])+ .status()+ .expect("run pkill");+ assert!(killed.success(), "pkill found no `{command}` process");++ let result = wait_for_event_before_terminal(+ &mut events,+ "tool_result",+ &request_id,+ Duration::from_secs(30),+ )+ .await;+ assert_eq!(+ result.get("success"),+ Some(&json!(false)),+ "a killed command is a failed call: {result}"+ );+ let done =+ wait_for_terminal_request(&mut events, Duration::from_secs(60), Some(&request_id))+ .await;+ assert_eq!(+ done.get("event").and_then(Value::as_str),+ Some("chat_done"),+ "{done}"+ );+ let reply = done+ .get("full_response")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(reply.contains("KILLED_SHELL_CANARY"), "{reply}");++ stack.shutdown();+ }++ /// Clears the park-after-run test hook even when an assertion unwinds.+ struct ParkAfterRunGuard;++ impl Drop for ParkAfterRunGuard {+ fn drop(&mut self) {+ openhuman_core::web_chat::set_test_park_after_run(false);+ }+ }++ /// A turn that goes quiet with nothing in flight is stopped by the idle guard+ /// and closed with a reply saying what it did and where it got stuck. The turn+ /// runs a real shell step and finishes its run, then is parked before its+ /// reply is saved (`set_test_park_after_run`), like a stuck save. The closing+ /// reply comes from one more model call, which sees the stop reason, the stuck+ /// point and the shell step.+ #[test]+ fn stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary() {+ run_on_agent_stack(+ "stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary",+ stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary_inner,+ );+ }++ async fn stalled_turn_is_stopped_by_the_idle_guard_and_closed_with_a_summary_inner() {+ let _lock = env_lock();+ super::linked_modules::install_if_requested();+ let _idle = EnvVarGuard::set("OPENHUMAN_WEB_TURN_IDLE_SECS", "30");+ let _unjailed = EnvVarGuard::set("OPENHUMAN_SANDBOX", "off");+ openhuman_core::web_chat::set_test_park_after_run(true);+ let _park = ParkAfterRunGuard;+ reset_script(vec![+ // request[0]: the turn runs one shell step.+ tool_call_completion("shell", json!({ "command": "echo STEP_ONE_CANARY" })),+ // request[1]: its final answer, which is never saved (the turn parks).+ text_completion("All done. UNSAVED_REPLY_CANARY"),+ // request[2]: the idle guard's closing call.+ text_completion("I ran one command, then the turn stalled while saving. CLOSE_CANARY"),+ ]);+ let stack = boot_stack().await;+ let mut events = spawn_sse_collector(format!(+ "{}/events?client_id=harness-idle-stall",+ stack.rpc_base+ ))+ .await;+ let request_id = send_web_chat(+ &stack.rpc_base,+ 611,+ "harness-idle-stall",+ "thread-idle-stall",+ "run one step",+ )+ .await;++ let done =+ wait_for_terminal_request(&mut events, Duration::from_secs(60), Some(&request_id))+ .await;+ assert_eq!(+ done.get("event").and_then(Value::as_str),+ Some("chat_done"),+ "a stopped turn is closed with a reply, not an error: {done}"+ );+ let reply = done+ .get("full_response")+ .and_then(Value::as_str)+ .unwrap_or_default();+ assert!(reply.contains("CLOSE_CANARY"), "{reply}");+ assert!(!reply.contains("UNSAVED_REPLY_CANARY"), "{reply}");++ let captured = with_captured(|c| c.clone());+ assert_eq!(captured.len(), 3, "turn calls plus one closing call");+ let close_prompt = captured[2].to_string();+ for expected in [+ "nothing happened for 30 seconds",+ "after the agent finished, while its reply was being saved",+ "done: Shell (echo STEP_ONE_CANARY)",+ ] {+ assert!(+ close_prompt.contains(expected),+ "closing call missing {expected:?}: {close_prompt}"+ );+ }++ stack.shutdown();+ }+}