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
feat(web_chat): add per-turn timing instrumentation
Steven Enamakel157a59f4db8f
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rsdeleted file mode 100644index 74a0c6349d..0000000000--- a/crates/openhuman-core/src/web_chat/run_task.rs+++ /dev/null@@ -1,478 +0,0 @@-//! `run_chat_task` — resolves or builds the cached session agent-//! (`session.rs`), spawns the progress bridge alongside the turn, runs it-//! through the agent harness, and applies the per-thread budget correlation-//! to a failed turn. Called from `start_chat` and `spawn_parallel_turn`-//! (`ops/start_chat.rs`/`ops/parallel_turn.rs`) once the message has been validated.--use std::sync::Arc;-use tinyagents_harness::run_queue::RunQueue;--use crate::agent::progress::AgentProgress;--use super::ops::BudgetCorrelation;-use super::progress_bridge::spawn_progress_bridge;-use super::session::{- checkin_session_agent, checkout_session_agent, normalize_model_override, CheckedOutSession,- CheckoutPolicy,-};-use super::types::{ChatRequestMetadata, WebChatTaskResult};-use super::web_errors::{- inference_budget_exceeded_user_message, is_inference_budget_exceeded_error,-};-use tinyinference_llm::failure::is_empty_provider_response_text;--#[cfg(any(test, debug_assertions))]-use super::ops::TEST_FORCED_RUN_CHAT_TASK_ERROR;--pub(crate) async fn run_chat_task(- ctx: &crate::core::runtime::DispatchCtx,- client_id: &str,- thread_id: &str,- request_id: &str,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- locale: Option<String>,- run_queue: Arc<RunQueue<crate::agent::queued_turn::QueuedTurn>>,- metadata: ChatRequestMetadata,- origin: crate::agent::turn_origin::AgentTurnOrigin,- // When true, run as an isolated fork: build a fresh agent seeded from the- // thread's history-at-start and never touch the shared `THREAD_SESSIONS`- // cache, so a concurrent same-thread (parallel) turn cannot clobber — or be- // clobbered by — the primary turn's cached agent. See `QueueMode::Parallel`.- fork: bool,- // This turn's host environment (its Stop cancellation, the wall-clock- // backstop's deadline), handed to the session so the whole run tree sees it.- host_env: crate::agent::turn_env::HostTurnEnv,- // The web-turn guard's activity record for this turn, passed explicitly by- // `run_turn_under_cancel_and_deadline`.- activity: super::turn_activity::TurnActivity,- // Where this turn's parked approvals surface, handed to the turn itself.- approval: crate::security::approval::ApprovalTurnContext,-) -> Result<WebChatTaskResult, String> {- // One turn at a time per profile: wait behind its relay and cron turns.- let _turn = crate::profiles::turn_gate::acquire(ctx).await;-- #[cfg(any(test, debug_assertions))]- {- let mut slot = TEST_FORCED_RUN_CHAT_TASK_ERROR.lock().await;- if let Some(forced) = slot.take() {- log::debug!(- "[web-channel][test] forced run_chat_task failure client_id={} thread_id={} request_id={}",- client_id,- thread_id,- request_id- );- return Err(forced);- }- }-- // Test hook: park the turn in-flight so concurrency / cooperative- // cancellation can be observed. A `Drop` guard flips the supplied flag if- // this future is dropped (i.e. cancelled) before the sleep elapses, proving- // the turn was torn down cooperatively rather than left running.- #[cfg(any(test, debug_assertions))]- {- let block = {- let slot = super::ops::TEST_RUN_CHAT_TASK_BLOCK.lock().await;- slot.clone()- };- if let Some(block) = block {- struct DropGuard(std::sync::Arc<std::sync::atomic::AtomicBool>);- impl Drop for DropGuard {- fn drop(&mut self) {- self.0.store(true, std::sync::atomic::Ordering::SeqCst);- }- }- let _guard = DropGuard(block.dropped.clone());- log::debug!(- "[web-channel][test] parking run_chat_task thread_id={} request_id={}",- thread_id,- request_id- );- // Signal that the turn future is live and parked, so a test can- // cancel only after the guard exists (otherwise a `biased` cancel- // could short-circuit before this future is ever polled).- block- .started- .store(true, std::sync::atomic::Ordering::SeqCst);- tokio::select! {- _ = block.release.notified() => {- return match block.succeed_in.clone() {- Some(workspace_dir) => Ok(WebChatTaskResult {- full_response: "parked reply".to_string(),- citations: Vec::new(),- usage: None,- workspace_dir,- timing: None,- }),- None => Err("test block released".to_string()),- };- }- _ = tokio::time::sleep(std::time::Duration::from_secs(30)) => {- return Err("test block elapsed".to_string());- }- }- }- }-- let mut config = ctx.load_config().await?;- // A thread started in a chosen folder acts there, not in the global- // `action_dir`. Applied before checkout so the session agent, its security- // policy (which grants `action_dir` as a trusted root) and its tools are- // all built on the thread's folder.- let thread_dir =- crate::threads::ops::thread_working_dir(ctx, config.workspace_dir.clone(), thread_id)- .await?;- if let Some(dir) = &thread_dir {- log::debug!("[web-channel] thread working folder applied thread_id={thread_id}");- config.action_dir = dir.clone();- }- // A guard that stops this turn closes it from this turn's own config and- // reply language, not from whatever profile is active when it fires.- activity.remember_turn(std::sync::Arc::new(config.clone()), locale.clone());- let model_override = normalize_model_override(model_override);- // The cached session (or a cold-boot resumed one) is the thread's single- // live history; every turn on the thread checks it out through this path.- let CheckedOutSession {- mut agent,- fingerprint: current_fp,- } = checkout_session_agent(- ctx,- &config,- client_id,- thread_id,- model_override,- temperature,- locale.as_deref(),- if fork {- CheckoutPolicy::Fork- } else {- CheckoutPolicy::Exact- },- )- .await?;-- // Bounded to 256 (was 64): a heavy-event subagent (e.g. `workflow_builder`,- // 50+ progress events per run) can overflow a smaller buffer, and the- // sender side uses `try_send` — an overflow silently drops progress- // events (including the ones that create a subagent's timeline row),- // which can in turn hide UI state derived from those events. This is- // 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 = super::turn_activity::tap(ctx, activity, progress_rx, 256);- // 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 {- input: Some(message.to_string()),- output: None,- });- agent.set_on_progress(Some(progress_tx));- agent.set_run_queue(Some(run_queue));- agent.set_thread_id(Some(thread_id));- agent.set_host_env(host_env);- // Also the turn's workspace, so attachment reads and delegated sub-agents- // (which load a fresh config) use the folder its uploads were staged in- // (#7714). Same pattern as `agent_chat`'s per-turn cwd.- if let Some(dir) = thread_dir {- agent.set_workspace_descriptor(Some(tinytools::WorkspaceDescriptor::new(dir)));- }- let turn_state_store = crate::agent::session_store::turn_states_for(&config.workspace_dir);- // Stamp the resolved agent onto the bridge metadata so the trace exporter- // can attribute the run (`agent.id` attr / `agent.turn:<id>` trace name).- let mut bridge_metadata = metadata.clone();- bridge_metadata.agent_id = Some(current_fp.target_agent_id.clone());- // A TinyMemes treatment thread surfaces only the remixed reply, so the- // original answer text is not streamed ahead of it.- #[cfg(feature = "tinymemes")]- {- bridge_metadata.hold_text_stream = crate::tinymemes::holds_text_stream(&config, thread_id);- }- let bridge = spawn_progress_bridge(- progress_rx,- client_id.to_string(),- thread_id.to_string(),- request_id.to_string(),- turn_state_store,- bridge_metadata,- config.clone(),- ctx.clone(),- );-- // `run_single`'s future is very large; box it so the two ambient-scope- // wrappers below hold a pointer rather than inlining the whole future into- // this already-large `run_chat_task` frame (which otherwise overflows the- // default test-thread stack — see the channels web-turn coverage tests).- #[cfg(feature = "tinymemes")]- let turn_started = std::time::Instant::now();- let turn = Box::pin(agent.run_single_with_approval(message, Some(origin), approval));- let mut result = match turn.await {- Ok(response) => {- // A successful turn proves the thread's balance is usable, so drop- // any stale budget-exhausted signal before it could mislabel a- // later genuine empty response. See #3386.- super::ops::clear_budget_signal(ctx, thread_id).await;- let citations = crate::memory::tools::take_turn_citations(ctx, thread_id);- let usage = agent.take_last_turn_usage_totals();- Ok(WebChatTaskResult {- full_response: response,- citations,- usage,- workspace_dir: config.workspace_dir.clone(),- timing: None,- })- }- Err(err) => {- let err_message = err.to_string();- let is_budget = is_inference_budget_exceeded_error(&err_message);- let is_empty = is_empty_provider_response_text(&err_message.to_lowercase());- // Only consult the cross-turn signal for an empty response that is- // not already a budget error — avoids taking the lock on every turn.- let has_fresh_signal = if !is_budget && is_empty {- super::ops::has_fresh_budget_signal(ctx, thread_id, ¤t_fp.provider_binding)- .await- } else {- false- };- match super::ops::classify_budget_correlation(is_budget, is_empty, has_fresh_signal) {- BudgetCorrelation::BudgetExhausted => {- // Remember the exhaustion (scoped to this provider binding)- // so a follow-up empty 200 on this thread+provider (managed- // route closes the SSE clean under credit exhaustion, no- // inline marker) reclassifies as budget. #3386.- super::ops::record_budget_signal(ctx, thread_id, ¤t_fp.provider_binding)- .await;- log::warn!(- "[web-channel] inference budget exhausted for client={} thread={} request_id={} error_category=budget_exhausted",- client_id,- thread_id,- request_id- );- Ok(WebChatTaskResult {- full_response: inference_budget_exceeded_user_message().to_string(),- citations: Vec::new(),- usage: None,- workspace_dir: config.workspace_dir.clone(),- timing: None,- })- }- BudgetCorrelation::UpgradeEmptyToBudget => {- // Empty provider response within the budget-signal window:- // the turn most likely failed for the same out-of-credits- // reason but arrived as a clean empty 200 with no budget- // marker. Surface the actionable budget copy. #3386.- log::warn!(- "[web-channel] reclassifying empty provider response as budget-exhausted \- from recent same-thread signal client={} thread={} request_id={} error_category=budget_exhausted_correlated",- client_id,- thread_id,- request_id- );- Ok(WebChatTaskResult {- full_response: inference_budget_exceeded_user_message().to_string(),- citations: Vec::new(),- usage: None,- workspace_dir: config.workspace_dir.clone(),- timing: None,- })- }- BudgetCorrelation::PassThrough => Err(err_message),- }- }- };- // The agent turn's own duration for the TinyMemes A/B log, taken before- // reply speech so synthesis time is not counted as turn time.- #[cfg(feature = "tinymemes")]- let turn_elapsed = turn_started.elapsed();-- if let Ok(ref task_result) = result {- let speak_reply = super::voice_notes::should_speak_reply(- &config,- thread_id,- metadata.speak_reply,- metadata.source.as_deref(),- );- let trimmed_response = task_result.full_response.trim();- if speak_reply && !trimmed_response.is_empty() {- let opts = crate::voice::reply_speech::ReplySpeechOptions {- voice_id: config- .channel_voice- .resolve_voice("web")- .map(str::to_string),- ..Default::default()- };- match crate::voice::reply_speech::synthesize_reply(- &config,- &task_result.full_response,- &opts,- )- .await- {- Ok(outcome) => {- let stored = super::voice_notes::store_synthesized_reply(- &config.workspace_dir,- request_id,- &outcome.value.audio_base64,- &outcome.value.audio_mime,- );- log::debug!(- "[web_channel] reply_speech dispatched chars={} stored={} client_id={} thread_id={} request_id={}",- task_result.full_response.len(),- stored,- client_id,- thread_id,- request_id,- );- }- Err(err) => log::warn!(- "[web_channel] reply_speech failed: {err} client_id={} thread_id={} request_id={}",- client_id,- thread_id,- request_id,- ),- }- }- if metadata.source.as_deref() == Some("ptt") {- if let Some(session_id) = metadata.session_id {- crate::voice::publish_ptt_transcript_committed(- thread_id.to_string(),- session_id,- task_result.full_response.chars().count(),- 0,- false,- );- }- }- }-- // TinyMemes: remix the final reply (slang + memes) when the flag puts this- // thread in the treatment arm. Runs after reply speech so TTS reads the- // original wording, and skips the budget-exhausted placeholder. Fails open.- #[cfg(feature = "tinymemes")]- if let Ok(ref mut task_result) = result {- crate::tinymemes::remix_task_reply(- ctx,- &config,- thread_id,- request_id,- message,- &mut task_result.full_response,- inference_budget_exceeded_user_message(),- turn_elapsed,- )- .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 as- // this returns. Let the bridge forward everything the turn queued first,- // so the terminal event cannot overtake the turn's own last tool results- // and narration on the socket. Bounded (see `BRIDGE_DRAIN_TIMEOUT`).- if !bridge- .wait_drained(super::progress_bridge::BRIDGE_DRAIN_TIMEOUT)- .await- {- log::warn!(- "[web-channel] progress bridge did not drain within {:?}; delivering anyway \- client={} thread={} request_id={}",- super::progress_bridge::BRIDGE_DRAIN_TIMEOUT,- client_id,- thread_id,- request_id- );- }-- // Settle the turn's own snapshot now the turn is over.- //- // The bridge marks the snapshot terminal on its way out, but it only exits- // once every clone of its progress sender drops. The cached session no- // longer keeps the turn's commit receipt (which held two), yet a detached- // sub-agent may still hold one past the turn, and an exit the bridge never- // reaches would leave `Streaming` on disk: re-entering the thread then- // hydrates that snapshot and paints a live "Thinking..." indicator under a- // reply that was already delivered. The turn has ended here by- // construction, so record that. A bridge that later observes- // `TurnCompleted` overwrites this with `Completed`, terminal either way.- {- let lifecycle = if result.is_ok() {- tinyagents_session::turn_state::TurnLifecycle::Completed- } else {- tinyagents_session::turn_state::TurnLifecycle::Interrupted- };- let now = chrono::Utc::now().to_rfc3339();- if let Err(err) = crate::agent::session_store::turn_states_for(&config.workspace_dir)- .settle_turn(thread_id, request_id, lifecycle, &now)- {- log::warn!(- "[web-channel] failed to settle turn snapshot client={client_id} \- thread={thread_id} request_id={request_id}: {err}"- );- }- }-- // The bridge only stamps its `TurnTimingSnapshot` once it has seen the- // parent's `TurnCompleted`, which `wait_drained` above waits for — read- // it now so `chat_done.timing` reports the same first-token/first-tool/- // total numbers as the bridge's own `time-to-first-visible` log line.- // `None` on a synthetic (budget-exhausted) result, an `Err`, or a bridge- // that never drained in time.- if let Ok(ref mut task_result) = result {- task_result.timing = bridge.timing_snapshot();- }-- // Only the primary (non-fork) turn writes its agent back to the shared- // cache; a fork is fully isolated and lets its agent drop here.- if !fork {- // A harness error can leave its session prefix committed even when the- // turn itself did not complete (for example an in-stream credential- // failure after partial text). Re-caching that host makes the next- // request fail with "cannot change a session prefix after a committed- // turn". The durable transcript remains authoritative, so discard an- // agent after every failed turn and cold-boot it on the next request.- if turn_result_poisoned_session(&result) {- log::warn!(- "[web-channel] dropping session agent after failed turn — \- next turn cold-boots from the durable transcript \- client={} thread={} request_id={}",- client_id,- thread_id,- request_id- );- } else {- checkin_session_agent(ctx, thread_id, agent, current_fp).await;- }- }-- result-}--/// Whether a completed turn's checked-out agent must be dropped instead of-/// returned to the warm-session cache. Any `Err` can leave the underlying host-/// session partially advanced, so only completed task results are reusable.-fn turn_result_poisoned_session(result: &Result<WebChatTaskResult, String>) -> bool {- result.is_err()-}--/// The error-string half of [`turn_result_poisoned_session`], shared with the-/// host-authored turn path (`ops/system_turn.rs`) whose result carries no-/// `WebChatTaskResult`.-pub(super) fn turn_error_discards_session(_err: &str) -> bool {- true-}--#[cfg(test)]-#[path = "run_task_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web_chat/turn_timing.rs b/crates/openhuman-core/src/web_chat/turn_timing.rsdeleted file mode 100644index 69fff9c3b8..0000000000--- a/crates/openhuman-core/src/web_chat/turn_timing.rs+++ /dev/null@@ -1,146 +0,0 @@-//! Time-to-first-visible instrumentation for a web-chat turn.-//!-//! A turn that shows nothing for 40 s looks the same in the logs as one that-//! streams a lead-in at 5 s unless the first text delta and the first tool-//! call are stamped against the turn start. `progress_bridge` feeds this from-//! the progress stream; grep `time-to-first-visible` to read it back.--use std::time::Instant;--pub(super) struct TurnTiming {- started: Instant,- first_text_ms: Option<u128>,- first_tool_ms: Option<u128>,- round_one_narration_chars: usize,-}--impl TurnTiming {- pub(super) fn start() -> Self {- Self {- started: Instant::now(),- first_text_ms: None,- first_tool_ms: None,- round_one_narration_chars: 0,- }- }-- /// A text delta arrived; the first non-blank one is the first visible byte.- pub(super) fn text_delta(&mut self, delta: &str, round: u32, request_id: &str) {- if self.first_text_ms.is_none() && !delta.trim().is_empty() {- let elapsed = self.started.elapsed().as_millis();- self.first_text_ms = Some(elapsed);- log::info!(- "[web_channel][bridge] time-to-first-visible kind=text first_text_ms={elapsed} round={round} request_id={request_id}"- );- }- if round <= 1 {- self.round_one_narration_chars += delta.chars().count();- }- }-- /// A tool call started; the first one closes the model's first response.- pub(super) fn tool_call(&mut self, tool_name: &str, round: u32, request_id: &str) {- if self.first_tool_ms.is_some() {- return;- }- let elapsed = self.started.elapsed().as_millis();- self.first_tool_ms = Some(elapsed);- log::info!(- "[web_channel][bridge] time-to-first-visible kind=tool_call first_tool_ms={elapsed} first_text_ms={:?} round={round} tool={tool_name} request_id={request_id}",- self.first_text_ms- );- }-- /// The turn finished: one summary line with both firsts and the total.- pub(super) fn done(&self, iterations: u32, interim_threshold: usize, request_id: &str) {- log::info!(- "[web_channel][bridge] time-to-first-visible kind=turn_done total_ms={} first_text_ms={:?} first_tool_ms={:?} round_one_narration_chars={} interim_threshold={interim_threshold} iterations={iterations} request_id={request_id}",- self.started.elapsed().as_millis(),- self.first_text_ms,- self.first_tool_ms,- self.round_one_narration_chars- );- }-- /// A point-in-time copy of this turn's timing, for carrying across the- /// `ProgressBridgeHandle` → `WebChatTaskResult` → `chat_done.timing`- /// pipeline (the bridge task itself never outlives the turn it times, so- /// the `Instant` stays put — only the derived millisecond counts leave- /// this module).- pub(super) fn snapshot(&self) -> TurnTimingSnapshot {- TurnTimingSnapshot {- first_token_ms: self.first_text_ms.map(|ms| ms as u64),- first_tool_ms: self.first_tool_ms.map(|ms| ms as u64),- total_ms: Some(self.started.elapsed().as_millis() as u64),- }- }-}--/// Plain-data copy of a turn's timing, safe to hand across an `Arc<Mutex<_>>`-/// out of the bridge task and into `chat_done.timing`.-#[derive(Debug, Clone, Copy, Default)]-pub(crate) struct TurnTimingSnapshot {- pub(crate) first_token_ms: Option<u64>,- pub(crate) first_tool_ms: Option<u64>,- pub(crate) total_ms: Option<u64>,-}--impl TurnTimingSnapshot {- /// Convert to the wire payload, filling `tokens_per_second` from- /// `output_tokens` when both it and `total_ms` are available and- /// `total_ms` is non-zero (avoids a division-by-zero / infinity on an- /// instantaneous synthetic result).- pub(crate) fn into_payload(- self,- output_tokens: Option<u64>,- ) -> crate::web_chat::TurnTimingPayload {- let tokens_per_second = match (output_tokens, self.total_ms) {- (Some(tokens), Some(total_ms)) if total_ms > 0 => {- Some(tokens as f64 / (total_ms as f64 / 1000.0))- }- _ => None,- };- crate::web_chat::TurnTimingPayload {- first_token_ms: self.first_token_ms,- first_tool_ms: self.first_tool_ms,- total_ms: self.total_ms,- tokens_per_second,- }- }-}--/// Rate-limits the live `turn_cost` socket event the bridge emits on every-/// `AgentProgress::TurnCostUpdated`: a multi-round turn can report one per-/// model call, and a fast-tool-calling round can do that several times a-/// second — far more often than a cost readout needs to repaint.-pub(super) struct TurnCostThrottle {- last_emit: Option<std::time::Instant>,-}--/// Minimum spacing between live `turn_cost` emissions for one turn.-const TURN_COST_EMIT_MIN_INTERVAL: std::time::Duration = std::time::Duration::from_millis(750);--impl TurnCostThrottle {- pub(super) fn new() -> Self {- Self { last_emit: None }- }-- /// Whether the caller should emit now. Unconditionally `true` on the- /// first call for a turn (`last_emit` still `None`) so the *first* cost- /// update always reaches the client immediately rather than waiting out- /// the interval. Advances `last_emit` on every `true` return.- pub(super) fn should_emit(&mut self) -> bool {- let should = self- .last_emit- .map(|at| at.elapsed() >= TURN_COST_EMIT_MIN_INTERVAL)- .unwrap_or(true);- if should {- self.last_emit = Some(std::time::Instant::now());- }- should- }-}--#[cfg(test)]-#[path = "turn_timing_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/web_chat/turn_timing_tests.rs b/crates/openhuman-core/src/web_chat/turn_timing_tests.rsdeleted file mode 100644index 663c22e964..0000000000--- a/crates/openhuman-core/src/web_chat/turn_timing_tests.rs+++ /dev/null@@ -1,109 +0,0 @@-use super::*;--// ── TurnCostThrottle ───────────────────────────────────────────────────────--/// The first `should_emit()` call for a fresh turn always returns `true` so-/// the initial cost readout reaches the client immediately, without waiting-/// out `TURN_COST_EMIT_MIN_INTERVAL`.-#[test]-fn turn_cost_throttle_always_emits_first_time() {- let mut throttle = TurnCostThrottle::new();- assert!(throttle.should_emit(), "first call must always emit");-}--/// A second call immediately after the first is suppressed — the throttle-/// enforces `TURN_COST_EMIT_MIN_INTERVAL` (750ms) between emissions so a-/// fast-tool-calling round doesn't repaint the cost readout several times a-/// second.-#[test]-fn turn_cost_throttle_suppresses_rapid_followup() {- let mut throttle = TurnCostThrottle::new();- assert!(throttle.should_emit(), "first call must emit");- assert!(- !throttle.should_emit(),- "an immediate second call must be suppressed"- );- assert!(- !throttle.should_emit(),- "a third rapid call must still be suppressed"- );-}--/// Once the minimum interval has elapsed, the throttle allows another-/// emission and resets its clock.-#[test]-fn turn_cost_throttle_emits_again_after_interval_elapses() {- let mut throttle = TurnCostThrottle::new();- assert!(throttle.should_emit(), "first call must emit");- assert!(!throttle.should_emit(), "immediate followup suppressed");-- // Fast-forward past the throttle window by backdating `last_emit`- // directly rather than sleeping the test for 750ms.- throttle.last_emit = Some(- std::time::Instant::now()- - TURN_COST_EMIT_MIN_INTERVAL- - std::time::Duration::from_millis(1),- );- assert!(- throttle.should_emit(),- "must emit again once the interval has elapsed"- );-}--// ── TurnTimingSnapshot::into_payload ───────────────────────────────────────--/// `tokens_per_second` is computed from `output_tokens / (total_ms / 1000)`-/// when both are available and `total_ms > 0`.-#[test]-fn into_payload_computes_tokens_per_second_when_available() {- let snapshot = TurnTimingSnapshot {- first_token_ms: Some(100),- first_tool_ms: None,- total_ms: Some(2000),- };- let payload = snapshot.into_payload(Some(40));- assert_eq!(payload.first_token_ms, Some(100));- assert_eq!(payload.first_tool_ms, None);- assert_eq!(payload.total_ms, Some(2000));- // 40 tokens / (2000ms / 1000) = 20 tokens/sec.- assert_eq!(payload.tokens_per_second, Some(20.0));-}--/// No `output_tokens` → no `tokens_per_second`, even with a valid `total_ms`.-#[test]-fn into_payload_omits_tokens_per_second_without_output_tokens() {- let snapshot = TurnTimingSnapshot {- first_token_ms: Some(50),- first_tool_ms: Some(75),- total_ms: Some(1000),- };- let payload = snapshot.into_payload(None);- assert_eq!(payload.tokens_per_second, None);-}--/// `total_ms == Some(0)` must not divide by zero — `tokens_per_second` stays-/// `None` rather than producing infinity on an instantaneous synthetic-/// result.-#[test]-fn into_payload_guards_against_division_by_zero_total_ms() {- let snapshot = TurnTimingSnapshot {- first_token_ms: None,- first_tool_ms: None,- total_ms: Some(0),- };- let payload = snapshot.into_payload(Some(10));- assert_eq!(payload.tokens_per_second, None);-}--/// No `total_ms` at all (turn never reached `TurnCompleted`) → no-/// `tokens_per_second`.-#[test]-fn into_payload_omits_tokens_per_second_without_total_ms() {- let snapshot = TurnTimingSnapshot {- first_token_ms: Some(10),- first_tool_ms: None,- total_ms: None,- };- let payload = snapshot.into_payload(Some(10));- assert_eq!(payload.tokens_per_second, None);-}diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rsindex f7e701b4da..4dc9029f80 100644--- a/crates/openhuman-core/src/web_chat/types.rs+++ b/crates/openhuman-core/src/web_chat/types.rs@@ -1,51 +1,11 @@//! Shared state and RPC parameter types for the web chat turn: the cached-//! `SessionEntry`/`SessionCacheFingerprint`, in-flight/parallel turn tracking-//! (`InFlightEntry`, `ParallelEntry`), the turn result (`WebChatTaskResult`),-//! and the `channel.web_*` request param structs.+//! `SessionEntry`/`SessionCacheFingerprint`, the turn result+//! (`WebChatTaskResult`), and the `channel.web_*` request param structs.use serde::Deserialize;-use tinyagents_harness::run_queue::QueueLane;use crate::agent::OpenHumanSessionHost;-/// How a web request arriving during an active turn is handled.-///-/// This is a web/orchestration disposition, not queue state. Only the three-/// variants returned by [`Self::queue_lane`] are ever inserted into TinyAgents'-/// run queue; interrupt and parallel are resolved by `start_chat` first.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]-pub(super) enum QueueMode {- #[default]- Interrupt,- Steer,- Followup,- Collect,- Parallel,-}--impl QueueMode {- pub(super) fn queue_lane(self) -> Option<QueueLane> {- match self {- Self::Steer => Some(QueueLane::Steer),- Self::Followup => Some(QueueLane::Followup),- Self::Collect => Some(QueueLane::Collect),- Self::Interrupt | Self::Parallel => None,- }- }-}--impl std::fmt::Display for QueueMode {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(match self {- Self::Interrupt => "interrupt",- Self::Steer => "steer",- Self::Followup => "followup",- Self::Collect => "collect",- Self::Parallel => "parallel",- })- }-}-/// All inputs that the cached `SessionEntry`'s `Agent` was built from,/// captured at build time. The cache-hit predicate is a single/// `entry.fingerprint == current_fingerprint` comparison — pulling the@@ -85,38 +45,6 @@ pub(super) struct SessionEntry {pub(super) fingerprint: SessionCacheFingerprint,}-#[derive(Debug)]-pub(super) struct InFlightEntry {- pub(super) request_id: String,- /// The client that started the turn, so a teardown that no client asked- /// for (a lost profile lease) still resolves that client's stream.- pub(super) client_id: String,- pub(super) handle: tokio::task::JoinHandle<()>,- pub(super) run_queue: std::sync::Arc<- tinyagents_harness::run_queue::RunQueue<crate::agent::queued_turn::QueuedTurn>,- >,- /// Cooperative cancellation for this turn. Cancelling it makes the turn's- /// `tokio::select!` arm fire and drops the in-flight turn future (which- /// cancels the in-flight LLM request and releases locks at a safe await- /// point) — a graceful alternative to the abrupt `handle.abort()`. The- /// handle is retained only as a hard backstop if cooperative cancellation- /// does not land within a grace period.- pub(super) cancel_token: tokio_util::sync::CancellationToken,-}--/// A concurrent, forked (`QueueMode::Parallel`) turn on a thread. Tracked in a-/// separate lane keyed by `request_id` so any number can run alongside the-/// primary in-flight turn without participating in interrupt/steer/queue-/// semantics. Carries `thread_id` so cancellation-by-thread can find it.-#[derive(Debug)]-pub(super) struct ParallelEntry {- pub(super) thread_id: String,- /// The client that started the turn (see [`InFlightEntry::client_id`]).- pub(super) client_id: String,- pub(super) handle: tokio::task::JoinHandle<()>,- pub(super) cancel_token: tokio_util::sync::CancellationToken,-}-#[derive(Debug, Clone)]pub(super) struct WebChatTaskResult {pub(super) full_response: String,@@ -138,29 +66,12 @@ pub(super) struct WebChatTaskResult {/// `wait_drained` — i.e. after the bridge has seen `TurnCompleted`./// `None` for a synthetic result (budget-exhausted placeholder) that/// never ran a bridge, or a turn that errored before completing a round.- pub(super) timing: Option<super::turn_timing::TurnTimingSnapshot>,+ pub(super) timing: Option<tinychannels_bus::web::TurnTimingSnapshot>,}-/// Per-request metadata carried alongside a chat send. Currently used by the-/// PTT flow (Task 4 wires it to `voice::reply_speech`); other voice surfaces-/// can populate it the same way.-#[derive(Debug, Default, Clone)]-pub struct ChatRequestMetadata {- pub speak_reply: Option<bool>,- pub source: Option<String>,- pub session_id: Option<u64>,- /// Resolved agent definition id driving this turn (e.g. `"orchestrator"`,- /// a task executor's agent). Stamped by the run entrypoint once the agent- /// is resolved — used purely for trace attribution (Langfuse `agent.id` /- /// `agent.turn:<id>` trace name), never for routing.- pub agent_id: Option<String>,- /// Do not stream the orchestrator's answer text (`text_delta`) to the- /// client; the reply arrives whole in `chat_done`. Set for threads whose- /// final reply is post-processed (TinyMemes treatment arm), so the user- /// never sees the original stream in and then get replaced. Interim- /// narration before tool calls is still flushed as `chat_interim`.- pub hold_text_stream: bool,-}+/// Per-request metadata carried alongside a chat send (the PTT flow, the voice+/// notes, trace attribution); the type is the web contract's.+pub use tinychannels_bus::web::ChatRequestMetadata;#[derive(Debug, Deserialize)]pub(crate) struct WebChatParams {