Skip to content

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

feat(web_chat): add followup and parallel turn handling

Steven Enamakelcf558932125c
diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rs
index 0ef8f58026..5c26cc46bb 100644
--- a/crates/openhuman-core/src/web_chat/ops.rs
+++ b/crates/openhuman-core/src/web_chat/ops.rs
@@ -1,18 +1,16 @@
-//! Web-channel chat dispatch: turn lifecycle (start/cancel/queue), the
-//! primary and parallel turn bodies, the shared in-flight/session state they
-//! coordinate over, and the guards (wall-clock backstop, budget correlation,
-//! Sentry suppression) applied around every turn.
+//! Web-channel chat dispatch: the entry points over the turn runner
+//! (start/cancel/queue), the per-thread session state they share, and the
+//! budget correlation applied to every turn. The turn lifecycle itself is
+//! TinyAgents' runner (`runner.rs`); the system turn is a host-authored turn
+//! on the thread's own session.
mod budget_correlation;
mod channel_ops;
-mod followups;
-mod parallel_turn;
mod start_chat;
mod state;
mod system_turn;
#[cfg(any(test, debug_assertions))]
mod test_hooks;
-mod turn_guards;
pub(super) use budget_correlation::{
classify_budget_correlation, clear_budget_signal, has_fresh_budget_signal,
@@ -29,8 +27,6 @@ pub use system_turn::{run_system_turn_on_thread, SESSION_CHECKOUT_FAILURE, SYSTE
#[cfg(test)]
pub use state::drain_queued_turns_for_test;
-#[cfg(test)]
-pub(crate) use state::in_flight;
pub(crate) use state::invalidate_thread_sessions_for_tenant;
#[cfg(test)]
pub(crate) use state::lock_thread_sessions_for_test;
@@ -38,9 +34,7 @@ pub(crate) use state::lock_thread_sessions_for_test;
pub use state::parallel_in_flight_entries_for_test;
#[cfg(test)]
pub(crate) use state::scoped_key;
-pub(super) use state::thread_sessions;
-#[cfg(test)]
-pub(crate) use state::track_parallel_turn_for_test;
+pub(super) use state::{tenant_of, thread_sessions};
pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};
pub(crate) use state::{event_session_id_for, key_for};
#[cfg(test)]
@@ -53,10 +47,6 @@ pub use test_hooks::RUN_CHAT_TASK_TEST_LOCK;
#[cfg(any(test, debug_assertions))]
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_PARK_AFTER_RUN, TEST_RUN_CHAT_TASK_BLOCK,
-};
-
-pub(crate) use turn_guards::sentry_suppression_reason;
+pub(super) use test_hooks::{run_test_hooks, test_hooks_active, TEST_PARK_AFTER_RUN};
#[cfg(test)]
-pub(crate) use turn_guards::timeout_bound_tag;
+pub(crate) use test_hooks::track_parallel_turn_for_test;
diff --git a/crates/openhuman-core/src/web_chat/ops/followups.rs b/crates/openhuman-core/src/web_chat/ops/followups.rs
deleted file mode 100644
index 9edc44086f..0000000000
--- a/crates/openhuman-core/src/web_chat/ops/followups.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-//! Queued follow-up turns: once a turn finishes, the items its run queue
-//! drained are started as fresh turns under the context the finished turn ran in.
-
-use crate::web_chat::ops::start_chat;
-use crate::web_chat::ChatRequestMetadata;
-
-pub(super) fn dispatch_followups(
- ctx: &crate::core::runtime::DispatchCtx,
- followups: Vec<crate::agent::queued_turn::QueuedTurn>,
-) {
- for fup in followups {
- let ctx = ctx.clone();
- tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
- async move {
- if let Err(err) = start_chat(
- &ctx,
- &fup.client_id,
- &fup.thread_id,
- &fup.text,
- fup.model_override,
- fup.temperature,
- fup.locale,
- Some("followup".to_string()),
- ChatRequestMetadata::default(),
- )
- .await
- {
- log::warn!(
- "[web-channel] failed to dispatch followup thread_id={} err={}",
- fup.thread_id,
- err
- );
- }
- },
- ));
- }
-}
diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
deleted file mode 100644
index e6a17ea869..0000000000
--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs
+++ /dev/null
@@ -1,301 +0,0 @@
-//! Forked (`QueueMode::Parallel`) turns: spawning one alongside whatever is
-//! already in flight on a thread, and the request- or thread-scoped
-//! cancellation paths that tear them down.
-
-use std::sync::Arc;
-use std::time::Duration;
-
-use tinyagents_harness::run_queue::RunQueue;
-use tokio_util::sync::CancellationToken;
-
-use crate::web_chat::WebChannelEvent;
-
-use super::super::event_bus::publish_web_channel_event_in;
-use super::super::run_task::run_chat_task;
-use super::super::types::{ChatRequestMetadata, ParallelEntry};
-use super::super::web_errors::classify_inference_error;
-use super::state::{key_for, parallel_in_flight, unscope};
-use super::turn_guards::{
- run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,
-};
-
-/// Spawn an independent, forked (`QueueMode::Parallel`) turn. It snapshots the
-/// thread's history-at-start (inside `run_chat_task` with `fork = true`), runs
-/// concurrently with any other turn on the thread, and on completion delivers
-/// its response (append-only) and removes itself from [`parallel_in_flight`].
-/// Emits the same per-`request_id` stream events as a primary turn, so the UI
-/// can render it as an interleaved branch.
-#[allow(clippy::too_many_arguments)]
-pub(crate) async fn spawn_parallel_turn(
- ctx: &crate::core::runtime::DispatchCtx,
- client_id: &str,
- thread_id: &str,
- request_id: String,
- message: &str,
- model_override: Option<String>,
- temperature: Option<f64>,
- locale: Option<String>,
- metadata: ChatRequestMetadata,
-) {
- let cancel_token = CancellationToken::new();
- let task_cancel_token = cancel_token.clone();
-
- let client_id_task = client_id.to_string();
- let thread_id_task = thread_id.to_string();
- let request_id_task = request_id.clone();
- // Request and thread ids are caller-chosen and only unique per agent, so
- // the table is keyed in the caller's scope (see `key_for`).
- let map_key = key_for(ctx, &request_id);
- let map_key_task = map_key.clone();
- let user_message = message.to_string();
- let ctx_task = ctx.clone();
- // Forked turns don't participate in the steer/followup/collect queue, but
- // `run_chat_task` requires a queue handle — give each its own.
- let run_queue = Arc::new(RunQueue::new());
-
- let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(
- async move {
- let approval_ctx = crate::security::approval::ApprovalChatContext {
- thread_id: thread_id_task.clone(),
- client_id: client_id_task.clone(),
- request_id: Some(request_id_task.clone()),
- };
- let origin = crate::agent::turn_origin::AgentTurnOrigin::WebChat {
- thread_id: thread_id_task.clone(),
- client_id: client_id_task.clone(),
- request_id: Some(request_id_task.clone()),
- };
- let result = run_turn_under_cancel_and_deadline(
- &ctx_task,
- task_cancel_token,
- origin.clone(),
- approval_ctx,
- |host_env, activity, approval| {
- run_chat_task(
- &ctx_task,
- &client_id_task,
- &thread_id_task,
- &request_id_task,
- &user_message,
- model_override,
- temperature,
- locale,
- run_queue,
- metadata,
- origin.clone(),
- /* fork */ true,
- host_env,
- activity,
- approval,
- )
- },
- )
- .await;
-
- match result {
- Some(Ok(chat_result)) => {
- crate::web_chat::presentation::deliver_response(
- &ctx_task,
- &client_id_task,
- &thread_id_task,
- &request_id_task,
- &chat_result.full_response,
- &user_message,
- &chat_result.citations,
- chat_result.usage.as_ref(),
- // The workspace the turn ran in, so the reply is stored
- // there before it is announced (#6034).
- Some(chat_result.workspace_dir.as_path()),
- chat_result.timing,
- // Parallel-fork delivery has no single human waiting
- // on a next-message suggestion for this reply (C5).
- false,
- )
- .await;
- }
- Some(Err(err)) => {
- log::warn!(
- "[web-channel] parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
- client_id_task,
- thread_id_task,
- request_id_task,
- err
- );
- let detailed = format!(
- "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",
- client_id_task, thread_id_task, request_id_task, err
- );
- let classified = classify_inference_error(&err);
- let classified_type = classified.error_type;
-
- // A parallel turn runs under the same deadline wrapper as the
- // serial one and dies the same way, but this branch reported
- // NOTHING to Sentry — not merely the timeouts this PR
- // un-suppresses, but every error type, since the parallel path
- // was added. So a discarded turn was invisible here even
- // before the suppression arm existed, and fixing only
- // `start_chat` would have left `QueueMode::Parallel` exactly
- // as blind as it was (#5804 review).
- //
- // Same policy as the serial site, deliberately sharing
- // `sentry_suppression_reason` rather than restating it: the
- // outer backstop stays suppressed, a harness `Timeout` reports
- // with the ceiling that fired.
- if let Some(reason) = sentry_suppression_reason(&detailed) {
- log::info!(
- target: "web_channel",
- "[web_channel.spawn_parallel_turn] suppressed Sentry emission for {} \
- client_id={} thread_id={} request_id={} error_type={} message={}",
- reason,
- client_id_task,
- thread_id_task,
- request_id_task,
- classified_type,
- detailed
- );
- } else {
- crate::core::observability::report_error_or_expected(
- detailed.as_str(),
- "web_channel",
- "spawn_parallel_turn",
- &[
- ("channel", "web"),
- ("error_type", classified_type),
- ("thread_id", thread_id_task.as_str()),
- ("request_id", request_id_task.as_str()),
- ("queue_mode", "parallel"),
- ("timeout_bound", timeout_bound_tag(&detailed)),
- ],
- );
- }
-
- publish_web_channel_event_in(
- &ctx_task,
- WebChannelEvent {
- event: "chat_error".to_string(),
- client_id: client_id_task.clone(),
- thread_id: thread_id_task.clone(),
- request_id: request_id_task.clone(),
- message: Some(classified.message),
- error_type: Some(classified.error_type.to_string()),
- error_source: Some(classified.source.to_string()),
- error_retryable: Some(classified.retryable),
- error_retry_after_ms: classified.retry_after_ms,
- error_provider: classified.provider,
- error_fallback_available: classified.fallback_available,
- copy_key: Some(classified.copy_key.to_string()),
- copy_params: classified.copy_params,
- ..Default::default()
- },
- );
- }
- None => {
- log::info!(
- "[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}",
- thread_id_task,
- request_id_task
- );
- // Cooperative cancel (deadline/cancel token) publishes no
- // `chat_error` on this path today — leaving a client
- // waiting on this request_id with no terminal event.
- // `chat_cancelled` closes it out.
- publish_web_channel_event_in(
- &ctx_task,
- WebChannelEvent {
- event: "chat_cancelled".to_string(),
- client_id: client_id_task.clone(),
- thread_id: thread_id_task.clone(),
- request_id: request_id_task.clone(),
- cancel_reason: Some("user_stop".to_string()),
- ..Default::default()
- },
- );
- }
- }
-
- parallel_in_flight(&ctx_task)
- .lock_owned()
- .await
- .remove(&map_key_task);
- },
- ));
-
- parallel_in_flight(ctx).lock_owned().await.insert(
- map_key,
- ParallelEntry {
- thread_id: key_for(ctx, thread_id),
- client_id: client_id.to_string(),
- handle,
- cancel_token,
- },
- );
-}
-
-/// Cooperatively cancel every parallel turn on a thread. Returns the cancelled
-/// `(request_id, client_id)` pairs. Used by the thread-level cancel paths so a cancel/stop also
-/// tears down any concurrent forked turns, not just the primary turn.
-pub(crate) async fn cancel_parallel_turns_for_thread(
- ctx: &crate::core::runtime::DispatchCtx,
- thread_id: &str,
-) -> Vec<(String, String)> {
- let mut cancelled = Vec::new();
- let scoped_thread = key_for(ctx, thread_id);
- let mut parallel = parallel_in_flight(ctx).lock_owned().await;
- let request_ids: Vec<String> = parallel
- .iter()
- .filter(|(_, entry)| entry.thread_id == scoped_thread)
- .map(|(request_id, _)| request_id.clone())
- .collect();
- for request_id in request_ids {
- if let Some(entry) = parallel.remove(&request_id) {
- entry.cancel_token.cancel();
- let mut handle = entry.handle;
- tokio::spawn(async move {
- tokio::select! {
- _ = &mut handle => {}
- _ = tokio::time::sleep(Duration::from_secs(5)) => {
- handle.abort();
- }
- }
- });
- cancelled.push((unscope(ctx, &request_id), entry.client_id));
- }
- }
- cancelled
-}
-
-/// Cancel a single parallel (forked) turn identified by `request_id`, but only
-/// when it belongs to `thread_id`. Returns the cancelled id (as a one-element
-/// vec of `(request_id, client_id)`, mirroring [`cancel_parallel_turns_for_thread`]) or empty when no such
-/// parallel turn exists. Request-scoped cancel path (#4760).
-pub(crate) async fn cancel_parallel_turn_by_request_id(
- ctx: &crate::core::runtime::DispatchCtx,
- thread_id: &str,
- request_id: &str,
-) -> Vec<(String, String)> {
- let map_key = key_for(ctx, request_id);
- let scoped_thread = key_for(ctx, thread_id);
- let mut parallel = parallel_in_flight(ctx).lock_owned().await;
- let matches = parallel
- .get(&map_key)
- .map(|entry| entry.thread_id == scoped_thread)
- .unwrap_or(false);
- if !matches {
- return Vec::new();
- }
- if let Some(entry) = parallel.remove(&map_key) {
- entry.cancel_token.cancel();
- let client_id = entry.client_id.clone();
- let mut handle = entry.handle;
- tokio::spawn(async move {
- tokio::select! {
- _ = &mut handle => {}
- _ = tokio::time::sleep(Duration::from_secs(5)) => {
- handle.abort();
- }
- }
- });
- return vec![(request_id.to_string(), client_id)];
- }
- Vec::new()
-}
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
deleted file mode 100644
index 88e03b89bf..0000000000
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs
+++ /dev/null
@@ -1,374 +0,0 @@
-//! 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;
-use crate::agent::turn_env::HostTurnEnv;
-
-/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled
-/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).
-///
-/// This is the turn's fixed total ceiling (issue #4746), and the single source
-/// of truth for the turn's deadlines (`agent::session_host::turn_backstop`, 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)`, 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`.
-///
-/// 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::session_host::turn_backstop::configured_backstop()
-}
-
-/// 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
-/// backstop, which sits below the local harness ceilings and would pre-empt them.
-async fn resolve_web_turn_deadline(ctx: &crate::core::runtime::DispatchCtx) -> Option<Duration> {
- if std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS").is_ok() {
- return web_turn_deadline();
- }
- let local = match ctx.load_config().await {
- Ok(config) => crate::agent::tinyagents::chat_provider_is_local(&config),
- Err(error) => {
- log::debug!("[web-channel] backstop locality probe skipped: {error}");
- false
- }
- };
- if local {
- let secs = crate::agent::tinyagents::local_web_turn_backstop_secs();
- log::debug!("[web-channel] local provider: turn backstop {secs:?}s (#6042)");
- return secs.map(Duration::from_secs);
- }
- web_turn_deadline()
-}
-
-/// 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,
-}
-
-/// Upper bound on closing a stopped turn: config, snapshot read and the
-/// closing model call (itself bounded at 45s). Past it the stop is reported as
-/// a `turn_timeout` error, so closing can never be what hangs the turn.
-const CLOSE_REPLY_BUDGET: Duration = Duration::from_secs(60);
-
-/// 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.
-///
-/// 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`] built here and handed to the turn.
-async fn drive_turn_with_deadline<B, F>(
- ctx: &crate::core::runtime::DispatchCtx,
- deadline: Option<Duration>,
- idle_window: Option<Duration>,
- ids: Option<TurnIds>,
- build: B,
-) -> Result<WebChatTaskResult, String>
-where
- B: FnOnce(TurnActivity) -> F,
- F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
-{
- 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. It receives
- // the activity record explicitly.
- let turn = Box::pin(build(activity.clone()));
- let bounded_turn = async move {
- let Some(d) = deadline else {
- return Ok(turn.await);
- };
- // The session turn carries the matching `TurnDeadline` on its explicit
- // host environment (`run_turn_under_cancel_and_deadline`), so the
- // harness (`agent::session_host::turn_backstop`) winds down before `d`.
- tokio::time::timeout(d, turn)
- .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,
- },
- idle = watchdog => Stop::Idle(idle),
- };
- let stuck = activity.stuck_point();
- let (cause, fallback) = match stop {
- Stop::Ceiling(d) => {
- log::warn!(
- "[web-channel] turn wall-clock backstop fired after {}s with no terminal event \
- (the harness wind-down did not close the turn in time); stuck={stuck:?} \
- (issue #4746)",
- d.as_secs()
- );
- (
- StopCause::Ceiling(d),
- super::super::web_errors::turn_timeout_error_message(d.as_secs()),
- )
- }
- Stop::Idle(idle) => {
- log::warn!(
- "[web-channel] turn idle guard fired: no progress for {}s with no model or tool \
- call in flight; stuck={stuck:?}",
- idle.as_secs()
- );
- (
- StopCause::Idle(idle),
- super::super::web_errors::turn_idle_error_message(idle.as_secs()),
- )
- }
- };
- let Some(ids) = ids else {
- return Err(fallback);
- };
- let (config, locale) = activity.turn_context();
- let stopped = StoppedTurn {
- thread_id: &ids.thread_id,
- request_id: &ids.request_id,
- cause,
- stuck,
- config,
- locale,
- ctx: ctx.clone(),
- };
- let close = super::super::turn_close::close_reply(stopped);
- match tokio::time::timeout(CLOSE_REPLY_BUDGET, close).await {
- Ok(Some(reply)) => Ok(reply),
- Ok(None) => Err(fallback),
- Err(_) => {
- log::warn!(
- "[web-channel] closing the stopped turn took over {}s; reporting turn_timeout",
- CLOSE_REPLY_BUDGET.as_secs()
- );
- Err(fallback)
- }
- }
-}
-
-/// The host environment a guarded turn runs with: its own session cancellation
-/// (returned too, so a Stop can fire it) and the `TurnDeadline` derived from the
-/// backstop, `None` when the backstop is disabled.
-fn turn_host_env(
- backstop: Option<Duration>,
-) -> (HostTurnEnv, tinyagents_harness::cancel::CancellationToken) {
- let turn_cancellation = tinyagents_harness::cancel::CancellationToken::new();
- let env = HostTurnEnv {
- cancellation: Some(turn_cancellation.clone()),
- turn_deadline: backstop.map(tinyagents_harness::turn_deadline::TurnDeadline::starting_now),
- ..HostTurnEnv::default()
- };
- (env, turn_cancellation)
-}
-
-/// 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), 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`,
-/// so the caller just unwinds quietly (see [`run_until_stopped`]). Otherwise `Some(res)` carries the turn's
-/// `Result`. Extracted so `start_chat` and `spawn_parallel_turn` share one copy
-/// of this wiring and can't drift apart (issue #4746 review); the only per-site
-/// differences are the `fork` flag and run-queue handle passed to
-/// `run_chat_task` when building `fut`.
-///
-/// `build_turn` receives the turn's [`HostTurnEnv`] -- its own cancellation
-/// token (fired by a Stop) and the backstop's [`TurnDeadline`] -- the guard's
-/// [`TurnActivity`] record and the turn's [`ApprovalTurnContext`], and returns
-/// the turn future, which hands the env to the session it runs. The env is an
-/// explicit value, so it reaches the turn's whole run tree without any ambient
-/// scope.
-///
-/// [`TurnDeadline`]: tinyagents_harness::turn_deadline::TurnDeadline
-pub(crate) async fn run_turn_under_cancel_and_deadline<B, F>(
- ctx: &crate::core::runtime::DispatchCtx,
- cancel_token: CancellationToken,
- origin: crate::agent::turn_origin::AgentTurnOrigin,
- approval_ctx: crate::security::approval::ApprovalChatContext,
- build_turn: B,
-) -> Option<Result<WebChatTaskResult, String>>
-where
- B: FnOnce(HostTurnEnv, TurnActivity, crate::security::approval::ApprovalTurnContext) -> F,
- F: std::future::Future<Output = Result<WebChatTaskResult, String>>,
-{
- let ids = approval_ctx.request_id.clone().map(|request_id| TurnIds {
- thread_id: approval_ctx.thread_id.clone(),
- request_id,
- });
- let deadline = resolve_web_turn_deadline(ctx).await;
- let (env, turn_cancellation) = turn_host_env(deadline);
- run_until_stopped(
- cancel_token,
- turn_cancellation,
- drive_turn_with_deadline(
- ctx,
- deadline,
- turn_activity::configured_idle_window(),
- ids,
- |activity| {
- crate::agent::turn_origin::with_origin(
- origin,
- build_turn(
- env,
- activity,
- crate::security::approval::ApprovalTurnContext::chat(approval_ctx),
- ),
- )
- },
- ),
- )
- .await
-}
-
-/// Drive `turn` until it finishes or `cancel_token` fires.
-///
-/// The turn runs under its own session cancellation (`turn_cancellation`,
-/// which the turn's host environment hands to its run tree). A Stop fires it rather than
-/// only dropping the turn, so the session driver can hand back the rounds it
-/// already completed and the runtime persists them (#7715). The turn then gets
-/// [`STOPPED_TURN_PERSIST_GRACE`] to finish before it is dropped; its result is
-/// discarded either way.
-async fn run_until_stopped<T>(
- cancel_token: CancellationToken,
- turn_cancellation: tinyagents_harness::cancel::CancellationToken,
- turn: impl std::future::Future<Output = T>,
-) -> Option<T> {
- // Boxed rather than stack-pinned: a chat turn's future is very large.
- let mut turn = Box::pin(turn);
- tokio::select! {
- biased;
- _ = cancel_token.cancelled() => {
- turn_cancellation.cancel();
- let persisted = tokio::time::timeout(STOPPED_TURN_PERSIST_GRACE, &mut turn).await;
- log::debug!(
- "[web-channel] stopped turn unwound within grace={}",
- persisted.is_ok()
- );
- None
- }
- res = &mut turn => Some(res),
- }
-}
-
-/// How long a cancelled turn may keep running so the session runtime can
-/// persist its completed rounds. Just above the runtime's own 2 s driver
-/// grace; the user-facing `chat_cancelled` has already been sent.
-const STOPPED_TURN_PERSIST_GRACE: Duration = Duration::from_secs(3);
-
-/// Reason a terminal `run_chat_task` error should be kept OUT of Sentry, or
-/// `None` when it is a genuine defect that must page.
-///
-/// A suppressed case is a deterministic, user-surfaced, retryable agent-loop
-/// outcome — a terminal `chat_error` already reaches the client, so a Sentry
-/// event is pure noise (same tier as `MaxIterationsExceeded` /
-/// `EmptyProviderResponse`, which are demoted the same way):
-///
-/// - the max-iteration cap (`is_max_iterations_error`), and
-/// - the **outer** web-turn wall-clock backstop (`is_outer_backstop_timeout`,
-/// issue #4746) — the turn wedged outside the harness and produced no
-/// terminal event, so without this arm every such turn would emit a spurious
-/// Sentry event, contradicting the graceful `turn_timeout` framing.
-///
-/// **Not suppressed: the harness's own `Timeout` (#5804).** This arm used to
-/// cover both, via `is_turn_timeout_error`, because the two are hard to tell
-/// apart once stringified. They are not the same event. The outer backstop
-/// fires with *nothing in flight*; the harness `Timeout` fires while bounding
-/// a real model or tool call, which means the run spent its budget doing work
-/// — and every result that work produced is discarded along with the turn. A
-/// turn that lost eighteen sub-agents' worth of accumulated work was reported
-/// here as `suppressed Sentry emission for turn wall-clock backstop` and
-/// reached telemetry as nothing at all, which is why the defect survived. See
-/// [`is_outer_backstop_timeout`](super::super::web_errors::is_outer_backstop_timeout)
-/// for the structural argument.
-///
-/// The user-facing classification is deliberately untouched: both still render
-/// the graceful `turn_timeout` copy via `is_turn_timeout_error`. Only the
-/// telemetry decision splits.
-///
-/// Kept as a pure predicate over the already-formatted error string so the
-/// suppression policy is unit-testable without a Sentry harness.
-pub(crate) fn sentry_suppression_reason(detailed: &str) -> Option<&'static str> {
- if tinyagents_harness::agent_error::is_max_iterations_error(detailed) {
- Some("max-iteration cap")
- } else if super::super::web_errors::is_outer_backstop_timeout(detailed) {
- Some("turn wall-clock backstop (no terminal event)")
- } else {
- None
- }
-}
-
-/// Which wall-clock bound a reported timeout hit, as a Sentry tag value.
-///
-/// Only meaningful once [`sentry_suppression_reason`] has decided to report —
-/// i.e. for a harness `Timeout`, never for the suppressed outer backstop. The
-/// crate names the bound in the message (`RUN_BOUND_LABEL` vs
-/// `PER_CALL_BOUND_LABEL`), and the two are different triage paths: a run that
-/// spent its whole budget doing real work is a capacity/planning problem, while
-/// one call that blew a per-call ceiling is a wedged provider. Emitting them
-/// under one tag would rebuild, in the dashboard, exactly the conflation this
-/// change removed from the code (#5804).
-///
-/// The bound is a typed field on the harness's hosted error
-/// (`HostedError::timeout_bound`); the turn runner turns it into a
-/// [`TurnTimeoutBound`](tinyagents_harness::agent_error::TurnTimeoutBound) phrase in the
-/// flattened error, and this function reads that phrase back through the same
-/// type rather than a second spelling. Pure over the formatted error string,
-/// for the same reason its neighbour is.
-pub(crate) fn timeout_bound_tag(detailed: &str) -> &'static str {
- if let Some(bound) = tinyagents_harness::agent_error::TurnTimeoutBound::from_message(detailed) {
- bound.tag()
- } else if super::super::web_errors::is_turn_timeout_error(detailed) {
- "unclassified_timeout"
- } else {
- "none"
- }
-}
-
-#[cfg(test)]
-#[path = "turn_guards_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs b/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
deleted file mode 100644
index fa33d95e27..0000000000
--- a/crates/openhuman-core/src/web_chat/ops/turn_guards_tests.rs
+++ /dev/null
@@ -1,202 +0,0 @@
-use super::*;
-
-fn result(text: &str) -> WebChatTaskResult {
- WebChatTaskResult {
- full_response: text.to_string(),
- citations: Vec::new(),
- usage: None,
- workspace_dir: std::path::PathBuf::from("/tmp/turn-guards"),
- timing: None,
- }
-}
-
-/// The guarded turn's host environment carries the backstop it runs under, so
-/// the session turn can hand the harness the deadline it must wind down before.
-#[test]
-fn guarded_turn_env_carries_the_backstop_deadline() {
- let backstop = Duration::from_secs(900);
- let (env, _) = turn_host_env(Some(backstop));
- let deadline = env.turn_deadline.expect("deadline on the turn's env");
- assert_eq!(deadline.backstop(), backstop);
- assert_eq!(deadline.wind_down_after(), Duration::from_secs(780));
- assert!(deadline.wind_down_after() < deadline.hard_stop_after());
- assert!(deadline.hard_stop_after() < backstop);
-}
-
-#[test]
-fn disabled_backstop_carries_no_deadline() {
- let (env, _) = turn_host_env(None);
- assert!(env.turn_deadline.is_none());
-}
-
-/// The env's cancellation is the very token a Stop fires.
-#[test]
-fn guarded_turn_env_shares_its_cancellation_with_the_stop_handle() {
- let (env, stop) = turn_host_env(None);
- let observed = env.cancellation.expect("cancellation on the turn's env");
- assert!(!observed.is_cancelled());
- stop.cancel();
- assert!(observed.is_cancelled());
-}
-
-/// If the backstop fires anyway, the caller gets the typed `turn_timeout`
-/// 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(
- &crate::core::runtime::DispatchCtx::host_default(),
- Some(Duration::from_secs(900)),
- None,
- None,
- |_| async {
- std::future::pending::<()>().await;
- Ok(result("never"))
- },
- )
- .await
- .expect_err("backstop fires");
- 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");
- 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(
- &crate::core::runtime::DispatchCtx::host_default(),
- CEILING,
- IDLE,
- None,
- |activity| async move {
- 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(
- &crate::core::runtime::DispatchCtx::host_default(),
- 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(
- &crate::core::runtime::DispatchCtx::host_default(),
- CEILING,
- IDLE,
- None,
- |activity| async move {
- loop {
- tokio::time::sleep(Duration::from_secs(30)).await;
- activity.observe(&text_delta());
- }
- },
- )
- .await
- .expect_err("backstop fires");
- assert!(err.contains("3600s wall-clock budget"), "{err}");
-}
-
-/// A Stop fires the turn's own session cancellation and lets the turn finish,
-/// so the session runtime can persist the stopped turn's rounds (#7715). The
-/// turn's result is still discarded: the caller unwinds as a cancel.
-#[tokio::test]
-async fn stop_fires_the_session_cancellation_and_lets_the_turn_unwind() {
- let cancel = CancellationToken::new();
- let unwound = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
- let unwound_in_turn = unwound.clone();
- let (env, session_cancellation) = turn_host_env(None);
- let observed = env.cancellation.expect("session cancellation");
- let turn = run_until_stopped(cancel.clone(), session_cancellation, async move {
- observed.cancelled().await;
- unwound_in_turn.store(true, std::sync::atomic::Ordering::SeqCst);
- Ok::<_, String>(result("persisted partial"))
- });
- let stop = async {
- tokio::task::yield_now().await;
- cancel.cancel();
- // A double Stop is a no-op, not a second unwind.
- cancel.cancel();
- };
- let (res, ()) = tokio::join!(turn, stop);
- assert!(res.is_none(), "a stopped turn reports a cancel");
- assert!(
- unwound.load(std::sync::atomic::Ordering::SeqCst),
- "the turn observed its session cancellation and ran to completion"
- );
-}
-
-/// A turn that ignores its session cancellation is dropped once the grace
-/// runs out, so a Stop can never hang on a stuck turn.
-#[tokio::test(start_paused = true)]
-async fn stop_drops_a_turn_that_ignores_cancellation_after_the_grace() {
- let cancel = CancellationToken::new();
- cancel.cancel();
- let started = tokio::time::Instant::now();
- let res = run_until_stopped(
- cancel,
- tinyagents_harness::cancel::CancellationToken::new(),
- std::future::pending::<()>(),
- )
- .await;
- assert!(res.is_none());
- assert!(started.elapsed() >= STOPPED_TURN_PERSIST_GRACE);
-}
-
-/// Without a Stop the turn's own result comes back.
-#[tokio::test]
-async fn unstopped_turn_returns_its_result() {
- let res = run_until_stopped(
- CancellationToken::new(),
- tinyagents_harness::cancel::CancellationToken::new(),
- async { Ok::<_, String>(result("answer")) },
- )
- .await;
- assert_eq!(res.expect("not stopped").unwrap().full_response, "answer");
-}