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): persist a stopped turn's prompt and completed rounds
M3gA-Mind8ccbb9c3e2d9
diff --git a/crates/openhuman-core/src/agent/session_host/driver.rs b/crates/openhuman-core/src/agent/session_host/driver.rsindex 28ffe38ac0..3ea7e16da1 100644--- a/crates/openhuman-core/src/agent/session_host/driver.rs+++ b/crates/openhuman-core/src/agent/session_host/driver.rs@@ -189,7 +189,8 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {).harness_dispatcher(),);- let mut outcome = match graph::run_chat_turn_graph(ChatTurnGraph {+ let cancellation = request.run_context.cancellation.clone();+ let turn = graph::run_chat_turn_graph(ChatTurnGraph {turn_models,model: self.model_name.clone(),messages,@@ -208,9 +209,22 @@ impl SessionDriver<OpenHumanRunContext> for OpenHumanSessionDriver {run_context,hosted_base: self.hosted_base.clone(),agent_id: self.agent_id.clone(),- })- .await- {+ });+ // A Stop hands the runtime the rounds the provider already accepted,+ // so the stopped turn's prompt and work stay in the session (#7715).+ let result = tokio::select! {+ biased;+ _ = cancellation.cancelled() => {+ return Err(driver_cancelled_with_snapshot(+ &snapshot,+ &sidecar,+ started.elapsed(),+ std::mem::take(&mut request.history),+ ));+ }+ result = turn => result,+ };+ let mut outcome = match result {Ok(outcome) => outcome,Err(error) => {return Err(driver_error_with_snapshot(@@ -564,29 +578,7 @@ fn driver_error_with_snapshot(let guard = snapshot.lock().unwrap_or_else(|poisoned| poisoned.into_inner());- // A graph error drops the harness's `AgentRun`, but its snapshot has- // already observed provider-accepted usage and completed tool outcomes.- // Copy those into the per-turn sidecar *before* producing the partial so- // runtime's single atomic append carries the same usage/failure truth as a- // successful turn. The partial history below remains accepted-only.- {- let mut observed = sidecar- .lock()- .unwrap_or_else(|poisoned| poisoned.into_inner());- observed.model_calls = guard.model_calls as usize;- observed.tool_calls = guard.tool_outcomes.len();- observed.input_tokens = guard.input_tokens;- observed.output_tokens = guard.output_tokens;- observed.cached_input_tokens = guard.cached_input_tokens;- observed.last_call_input_tokens = guard.last_call_input_tokens;- observed.last_call_output_tokens = guard.last_call_output_tokens;- // Each answered call was priced as it arrived (reported charge, else- // catalog estimate, else unknown); nothing is re-estimated here.- observed.cost = guard.cost;- observed.duration = Some(elapsed);- observed.tool_outcomes = guard.tool_outcomes.clone();- observed.resolved_route = guard.resolved_route.clone();- }+ record_snapshot_usage(&guard, sidecar, elapsed);if guard.messages.is_empty() {let mut failure = driver_failure(error);failure.outcome = terminal;@@ -629,6 +621,73 @@ fn driver_error_with_snapshot(}}+/// A graph error or a Stop drops the harness's `AgentRun`, but its snapshot+/// has already observed provider-accepted usage and completed tool outcomes.+/// Copy those into the per-turn sidecar *before* producing the partial so+/// runtime's single atomic append carries the same usage/failure truth as a+/// successful turn. The partial history itself remains accepted-only.+fn record_snapshot_usage(+ guard: &crate::agent::tinyagents::TranscriptSnapshot,+ sidecar: &std::sync::Arc<+ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,+ >,+ elapsed: std::time::Duration,+) {+ let mut observed = sidecar+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ observed.model_calls = guard.model_calls as usize;+ observed.tool_calls = guard.tool_outcomes.len();+ observed.input_tokens = guard.input_tokens;+ observed.output_tokens = guard.output_tokens;+ observed.cached_input_tokens = guard.cached_input_tokens;+ observed.last_call_input_tokens = guard.last_call_input_tokens;+ observed.last_call_output_tokens = guard.last_call_output_tokens;+ // Each answered call was priced as it arrived (reported charge, else+ // catalog estimate, else unknown); nothing is re-estimated here.+ observed.cost = guard.cost;+ observed.duration = Some(elapsed);+ observed.tool_outcomes = guard.tool_outcomes.clone();+ observed.resolved_route = guard.resolved_route.clone();+}++/// The partial a stopped turn hands the runtime (#7715): the user's prompt and+/// every round the provider accepted, so the next turn sees the work and+/// edit/regenerate can find the turn. A stop before the first model call has+/// no snapshot yet and keeps just the request history (the prompt).+///+/// No display partial: the turn_state mirror already appends the streamed+/// text as the display-only record of an interrupted turn.+fn driver_cancelled_with_snapshot(+ snapshot: &crate::agent::tinyagents::TranscriptSnapshotSink,+ sidecar: &std::sync::Arc<+ std::sync::Mutex<crate::agent::tinyagents::host::run_context::SessionTurnSidecar>,+ >,+ elapsed: std::time::Duration,+ request_history: Vec<Message>,+) -> DriverFailure {+ let guard = snapshot+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ record_snapshot_usage(&guard, sidecar, elapsed);+ let history = if guard.messages.is_empty() {+ request_history+ } else {+ guard.messages[..guard.accepted_end()].to_vec()+ };+ DriverFailure {+ error: RuntimeError::Cancelled,+ partial: Some(DriverOutcome {+ history,+ output: None,+ partial: None,+ interrupted: true,+ outcome: None,+ }),+ outcome: None,+ }+}+#[cfg(test)]#[path = "driver_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/agent/session_host/driver_tests.rs b/crates/openhuman-core/src/agent/session_host/driver_tests.rsindex 5d08588eb7..da9b5b2b57 100644--- a/crates/openhuman-core/src/agent/session_host/driver_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/driver_tests.rs@@ -268,3 +268,61 @@ fn recorded_declarations_allow_missing_executors_without_authorizing_fresh_namesassert!(error.error.to_string().contains("invented_tool"));assert!(!error.error.to_string().contains("retired_tool"));}++/// A Stop keeps the user's prompt and every round the provider accepted+/// (#7715), so the next turn sees the work and edit/regenerate find the turn.+/// The streamed tail is left to the turn_state mirror's display record.+#[test]+fn stopped_turn_hands_back_its_accepted_rounds() {+ let snapshot = Arc::new(std::sync::Mutex::new(+ crate::agent::tinyagents::TranscriptSnapshot {+ messages: vec![+ Message::user("build the payment layer"),+ Message::tool("call-1", "committed 6b75a4c"),+ Message::assistant("streamed text the provider never accepted"),+ ],+ accepted_len: 2,+ request_base_len: 1,+ model_calls: 2,+ input_tokens: 40,+ ..Default::default()+ },+ ));+ let sidecar = sidecar();+ let failure = driver_cancelled_with_snapshot(+ &snapshot,+ &sidecar,+ std::time::Duration::from_millis(7),+ vec![Message::user(+ "unused: the snapshot already holds the request",+ )],+ );+ assert_eq!(failure.error, RuntimeError::Cancelled);+ let partial = failure.partial.expect("a stopped turn keeps its rounds");+ let texts: Vec<String> = partial.history.iter().map(|m| m.text()).collect();+ assert_eq!(texts, ["build the payment layer", "committed 6b75a4c"]);+ assert!(partial.interrupted);+ assert!(partial.partial.is_none(), "no second display record");+ let observed = sidecar.lock().unwrap();+ assert_eq!(observed.model_calls, 2);+ assert_eq!(observed.input_tokens, 40);+ assert_eq!(observed.duration, Some(std::time::Duration::from_millis(7)));+}++/// A Stop before the first model call has no snapshot yet; the prompt is still+/// kept so the stopped turn exists in the transcript.+#[test]+fn stop_before_the_first_model_call_keeps_the_prompt() {+ let snapshot = Arc::new(std::sync::Mutex::new(+ crate::agent::tinyagents::TranscriptSnapshot::default(),+ ));+ let failure = driver_cancelled_with_snapshot(+ &snapshot,+ &sidecar(),+ std::time::Duration::ZERO,+ vec![Message::user("earlier"), Message::user("stop me")],+ );+ let partial = failure.partial.expect("the prompt is kept");+ let texts: Vec<String> = partial.history.iter().map(|m| m.text()).collect();+ assert_eq!(texts, ["earlier", "stop me"]);+}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..d0ba4d3223 100644--- a/crates/openhuman-core/src/web_chat/ops/turn_guards.rs+++ b/crates/openhuman-core/src/web_chat/ops/turn_guards.rs@@ -113,7 +113,9 @@ where////// 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. Otherwise `Some(res)` carries the turn's+/// so the caller just unwinds quietly. A cancel also fires the turn's session+/// cancellation and waits up to [`STOPPED_TURN_PERSIST_GRACE`] for the turn to+/// persist the rounds it completed before it is dropped (#7715). 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@@ -127,19 +129,55 @@ pub(crate) async fn run_turn_under_cancel_and_deadline<F>(whereF: std::future::Future<Output = Result<WebChatTaskResult, String>>,{- tokio::select! {- biased;- _ = cancel_token.cancelled() => None,- res = drive_turn_with_deadline(- resolve_web_turn_deadline().await,+ let deadline = resolve_web_turn_deadline().await;+ run_until_stopped(+ cancel_token,+ drive_turn_with_deadline(+ deadline,crate::agent::turn_origin::with_origin(origin,crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),),- ) => Some(res),+ ),+ )+ .await+}++/// Drive `turn` until it finishes or `cancel_token` fires.+///+/// The turn runs under its own session cancellation, which its run tree reads+/// through `host_overrides::current_cancellation`. 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: impl std::future::Future<Output = T>,+) -> Option<T> {+ let turn_cancellation = tinyagents_harness::cancel::CancellationToken::new();+ let turn = crate::agent::host_overrides::with_cancellation(turn_cancellation.clone(), turn);+ tokio::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.///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..177328ae76 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@@ -58,3 +58,52 @@ async fn backstop_firing_yields_a_classified_turn_timeout_error() {assert_eq!(classified.error_type, "turn_timeout");assert!(!classified.message.trim().is_empty());}++/// A Stop fires the turn's own session cancellation and lets the turn finish,+/// so the session runtime can persist the stopped turn's rounds (#7715). The+/// turn's result is still discarded: the caller unwinds as a cancel.+#[tokio::test]+async fn stop_fires_the_session_cancellation_and_lets_the_turn_unwind() {+ let cancel = CancellationToken::new();+ let unwound = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));+ let unwound_in_turn = unwound.clone();+ let turn = run_until_stopped(cancel.clone(), async move {+ crate::agent::host_overrides::current_cancellation()+ .cancelled()+ .await;+ unwound_in_turn.store(true, std::sync::atomic::Ordering::SeqCst);+ Ok::<_, String>(result("persisted partial"))+ });+ let stop = async {+ tokio::task::yield_now().await;+ cancel.cancel();+ };+ let (res, ()) = tokio::join!(turn, stop);+ assert!(res.is_none(), "a stopped turn reports a cancel");+ assert!(+ unwound.load(std::sync::atomic::Ordering::SeqCst),+ "the turn observed its session cancellation and ran to completion"+ );+}++/// A turn that ignores its session cancellation is dropped once the grace+/// runs out, so a Stop can never hang on a stuck turn.+#[tokio::test(start_paused = true)]+async fn stop_drops_a_turn_that_ignores_cancellation_after_the_grace() {+ let cancel = CancellationToken::new();+ cancel.cancel();+ let started = tokio::time::Instant::now();+ let res = run_until_stopped(cancel, std::future::pending::<()>()).await;+ assert!(res.is_none());+ assert!(started.elapsed() >= STOPPED_TURN_PERSIST_GRACE);+}++/// Without a Stop the turn's own result comes back.+#[tokio::test]+async fn unstopped_turn_returns_its_result() {+ let res = run_until_stopped(CancellationToken::new(), async {+ Ok::<_, String>(result("answer"))+ })+ .await;+ assert_eq!(res.expect("not stopped").unwrap().full_response, "answer");+}