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
refactor(web_chat): restructure error handling and split socket loop
Steven Enamakelc8259dc784b3
diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_part_01.rs b/crates/openhuman-core/src/platform/socket/ws_loop_part_01.rsdeleted file mode 100644index f153fe71f7..0000000000--- a/crates/openhuman-core/src/platform/socket/ws_loop_part_01.rs+++ /dev/null@@ -1,688 +0,0 @@-use std::sync::Arc;--use parking_lot::Mutex;--use futures_util::{SinkExt, StreamExt};-use serde_json::json;-use tokio::sync::{mpsc, watch};-use tokio::time::{Duration, Instant};-use tokio_tungstenite::{- connect_async,- tungstenite::{http::StatusCode, Error as WsError, Message as WsMessage},-};--use crate::api::models::socket::ConnectionStatus;-use crate::util::utf8_safe_prefix_at_byte_boundary;--use super::event_handlers::{handle_sio_event, parse_sio_event};-#[cfg(test)]-use super::manager::AckRegistry;-use super::manager::{emit_state_change, SharedState};-use super::token_provider::{is_invalid_token_error, TokenProvider};-use super::types::{ConnectionOutcome, WsStream};--/// Maximum HTTP redirect hops to follow during a single WebSocket connect attempt.-///-/// Cloudflare and similar edges return a single 301 (e.g. when the configured-/// `BACKEND_URL` is `http://...` and the server only serves the upgrade over TLS)-/// before the upgrade succeeds. Three hops is enough headroom for chained-/// redirects while still bounding pathological loops.-const MAX_REDIRECT_HOPS: u8 = 3;--// ----------------------------------------------------------------------------// Background loop-// -----------------------------------------------------------------------------/// Number of consecutive `ConnectionOutcome::Failed` attempts at which the-/// loop fires exactly one `error`-level log (and therefore one Sentry event).-/// Below the threshold, repeated transient failures (gateway 5xx, TLS-/// handshake resets, DNS blips) stay at `warn` and don't reach the Sentry-/// tracing layer. Above the threshold, subsequent retries return to `warn` —-/// the one-shot `error` at the threshold is sufficient to page on a sustained-/// outage without generating unbounded events.-///-/// The value is 5 intentionally: the Sentry event fires on the **5th-/// consecutive failed attempt**, which corresponds to ~15 seconds of-/// accumulated backoff sleep (1 s + 2 s + 4 s + 8 s before the 5th try).-/// Transient blips that recover within 4 attempts produce zero Sentry noise;-/// sustained outages produce exactly one event per affected client.-///-/// See OPENHUMAN-TAURI-8M — a single gateway 503 incident generated 549-/// Sentry events because every retry was logged at `error`.-const FAIL_ESCALATE_THRESHOLD: u32 = 5;--/// Background loop that manages the WebSocket connection and reconnection.-///-/// `token_provider` is called before **each** connection attempt, so a-/// token that was refreshed or re-stored on disk (e.g. after the user-/// re-logged-in while the loop was sleeping) is picked up automatically.-///-/// On a `"Socket.IO connect error: Invalid token"` rejection the loop-/// performs one extra provider call to check whether a fresher token-/// became available. If the token is unchanged (or the second attempt also-/// fails with "Invalid token") the loop escalates immediately — it does-/// **not** waste the remaining back-off attempts on a provably dead token.-/// This is the fix for TAURI-RUST-9C (#2892).-pub(super) async fn ws_loop(- url: String,- token_provider: TokenProvider,- shared: Arc<SharedState>,- mut emit_rx: mpsc::UnboundedReceiver<String>,- mut shutdown_rx: watch::Receiver<bool>,- internal_tx: mpsc::UnboundedSender<String>,- emit_ready: Arc<Mutex<bool>>,-) {- let mut backoff = Duration::from_millis(1000);- let max_backoff = Duration::from_secs(30);- let mut consecutive_failures: u32 = 0;- // How many `RetryImmediately` short-circuits we've taken in the **current**- // "fresh-token cycle" (i.e. since the last successful connection or- // non-token-related failure). Bounded to 1 so a buggy / non-deterministic- // provider that returns a *different* non-empty token on every call cannot- // hot-loop: connect → Invalid token → fresh token → connect → Invalid token- // → fresh token → ... with no sleep and no escalation. After one immediate- // shot we fall through to the normal backoff + escalation path. See the- // CodeRabbit Major on PR #2905.- let mut fresh_token_retries: u32 = 0;- // Fresh token carried forward from a `RetryImmediately` decision. When- // `decide_after_invalid_token` re-fetches the provider and finds a- // genuinely different value, we stash it here so the next loop iteration- // skips the redundant top-of-loop provider call and uses **exactly** the- // token that was validated by the decision step — avoiding a redundant- // lock + disk read and the case where the logged fresh-token length- // drifts from what's actually sent over the wire. See the CodeRabbit- // Minor on PR #2905.- let mut pending_token: Option<String> = None;-- // `ws_url` is the *resolved* socket URL we're currently connecting to.- // If the backend responds with an HTTP 3xx during the upgrade (typical when- // BACKEND_URL is configured as `http://` and the edge forces TLS), we- // follow the Location header and pin the resolved URL here so subsequent- // reconnects skip the redirect round-trip entirely.- let mut ws_url = crate::api::socket::websocket_url(&url);-- loop {- if *shutdown_rx.borrow() {- break;- }-- // If a fresh token was carried forward from the previous iteration's- // `RetryImmediately` decision, consume it now and skip the redundant- // provider call — `decide_after_invalid_token` already validated that- // it is non-empty and distinct from the previously-rejected token, so- // re-reading the provider here would only re-acquire the same lock /- // re-hit the same disk file. Otherwise fetch the latest token- // afresh. If the provider returns an error (no token stored → user- // is logged out, profile corrupt), there is nothing useful to retry- // with — surface the error and exit cleanly rather than spamming- // the server.- let token = match pending_token.take() {- Some(t) => t,- None => match token_provider() {- Ok(t) if !t.trim().is_empty() => t,- Ok(_) => {- log::warn!("[socket] ws_loop: token provider returned empty token — stopping");- *shared.error.write() =- Some("session expired — please sign in again".to_string());- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(&shared);- return;- }- Err(e) => {- log::warn!("[socket] ws_loop: token provider failed — stopping: {e}");- *shared.error.write() =- Some("session expired — please sign in again".to_string());- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(&shared);- return;- }- },- };-- log::info!(- "[socket] Attempting connection (token_len={})...",- token.len()- );- // Record the credential this attempt actually authenticates with. The- // provider is re-read every iteration, so a session refreshed mid-loop- // would otherwise leave `SocketManager::is_live_for` comparing against- // the token this loop was spawned with and tearing down a healthy socket- // on the next connect (#6181).- *shared.connection_identity.write() = Some((url.clone(), token.clone()));- *shared.status.write() = ConnectionStatus::Connecting;- emit_state_change(&shared);-- let outcome = run_connection(- &mut ws_url,- &token,- &shared,- &mut emit_rx,- &mut shutdown_rx,- &internal_tx,- &emit_ready,- )- .await;-- // The connection is over. Clear this connection's readiness flag and- // drain whatever is still queued, both under the `emit_ready` lock so a- // concurrent `emit` cannot slip between them: without the shared lock,- // `emit` could observe `ready == true`, this teardown could clear+drain,- // and `emit`'s `tx.send` could then land a message in the just-emptied- // channel — where the next reconnect (a fresh sid, whose roster the- // backend has cleared) would forward it. `emit` takes the same lock- // across its check+send, so that interleaving cannot occur.- //- // Clearing also covers a connection that never handshook (`run_connection`- // only sets `true` after the CONNECT ACK), and draining is the backstop- // for anything already queued: `emit_rx` is owned by this loop, not by- // the connection, so a leftover message would otherwise be flushed onto- // the next socket. It is a no-op on a `Failed` attempt that never flipped- // the flag or queued anything.- let dropped = {- let mut ready = emit_ready.lock();- *ready = false;- drain_pending_emits(&mut emit_rx)- };- if dropped > 0 {- log::warn!("[socket] Dropped {dropped} queued emit(s) on disconnect");- }-- // The connection attempt has ended (lost, failed, or shutdown), so any- // in-flight `emit_with_ack` waiter can never receive its ACK now. Cancel- // them here — covering server-driven disconnects (`Lost`) and the- // session-expired escalation below — not just explicit- // `SocketManager::disconnect()` (CodeRabbit #4355).- shared.ack_registry.cancel_all();- super::medulla::workflows::end_connection_generation();-- match outcome {- ConnectionOutcome::Shutdown => {- log::info!("[socket] Clean shutdown");- break;- }- ConnectionOutcome::Lost(reason) => {- // `Lost` is only returned after a successful SIO CONNECT ACK- // (see `run_connection`), so reaching this arm proves the- // backend is reachable and the token is valid. Reset both- // the backoff and the failure streak — and clear the- // fresh-token retry counter so a long-lived session that- // accumulated a RetryImmediately on a prior reconnect cycle- // doesn't carry that dead state into the next one.- if consecutive_failures > 0 {- log::debug!(- "[socket] Connection re-established; resetting failure streak ({} cleared)",- consecutive_failures- );- }- consecutive_failures = 0;- fresh_token_retries = 0;- log::warn!("[socket] Connection lost: {}", reason);- backoff = Duration::from_millis(1000);- }- ConnectionOutcome::Failed(reason) if is_invalid_token_error(&reason) => {- // The server rejected our token explicitly. Try one more- // provider call — in case the token was refreshed on disk- // since we fetched it moments ago (e.g. another code path- // rotated it). If the provider returns a genuinely different- // token, we can give it one more shot without consuming the- // normal backoff budget.- log::warn!(- "[socket] Invalid token on attempt — checking for fresh token (current_len={})",- token.len()- );- match decide_after_invalid_token(&token, &token_provider) {- InvalidTokenAction::RetryImmediately { token: fresh } => {- let fresh_len = fresh.len();- fresh_token_retries = fresh_token_retries.saturating_add(1);- if fresh_token_retries > 1 {- // We already gave the fresh-token cycle one- // immediate shot. A provider that keeps returning- // *different* non-empty tokens (rapid server-side- // rotation, non-deterministic source, buggy impl)- // could otherwise hot-loop forever with no sleep- // and no escalation — arguably worse than the- // 5-retry storm this PR was originally fixing. Fall- // through to the normal failure path so backoff- // sleeps and `consecutive_failures` escalation- // converge on a definitive outcome.- log::warn!(- "[socket] Fresh token available (len={fresh_len}) but already \- retried once this cycle — escalating to normal backoff path"- );- consecutive_failures = consecutive_failures.saturating_add(1);- log_connection_failure(consecutive_failures, &reason);- // Fall through to the backoff sleep below.- // Intentionally drop `fresh` here: the bounded- // path now demands a backoff sleep, after which- // the next loop iteration will re-fetch the- // provider afresh (the token we just got may- // itself be stale by the time the sleep- // completes — this is the only knowable-correct- // policy for a rotating-source provider).- } else {- // We have a genuinely different token — try once- // immediately (no backoff sleep) with the **exact**- // token the decision step validated. Stash it for- // the next iteration so the top-of-loop provider- // call is skipped and we don't re-acquire the- // session-store lock or re-read from disk just to- // get the same value back. If this attempt also- // fails we will go through the normal escalation- // path on the next loop iteration (either- // same-token Escalate or the bounded fall-through- // above).- log::info!(- "[socket] Fresh token available (len={fresh_len}), retrying immediately"- );- pending_token = Some(fresh);- // Don't increment consecutive_failures for an attempt we- // couldn't have avoided — the token we used was already- // stale at fetch time.- continue;- }- }- InvalidTokenAction::Escalate { reason } => {- // No fresh token — the session is definitively expired.- // Escalate immediately instead of wasting more attempts- // on what is provably a dead token. This is the core fix- // for TAURI-RUST-9C (#2892).- log::warn!("[socket] Session expired ({reason}) — stopping reconnect loop");- *shared.error.write() =- Some("session expired — please sign in again".to_string());- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(&shared);- return;- }- }- }- ConnectionOutcome::Failed(reason) => {- consecutive_failures = consecutive_failures.saturating_add(1);- log_connection_failure(consecutive_failures, &reason);- // keep growing backoff- }- }-- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(&shared);-- if *shutdown_rx.borrow() {- break;- }-- log::info!("[socket] Reconnecting in {:?}...", backoff);- tokio::select! {- _ = tokio::time::sleep(backoff) => {}- _ = shutdown_rx.changed() => {- if *shutdown_rx.borrow() { break; }- }- }- backoff = (backoff * 2).min(max_backoff);- }-- log::info!("[socket] WebSocket loop exiting");- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(&shared);-}--// ----------------------------------------------------------------------------// Failure logging-// -----------------------------------------------------------------------------/// Log a connection failure at the appropriate level based on how many-/// consecutive failures have occurred.-///-/// - Below `FAIL_ESCALATE_THRESHOLD`: `warn` — transient blips (DNS, gateway-/// 5xx, TLS resets) stay out of Sentry.-/// - Exactly at the threshold: routed through-/// [`crate::core::observability::report_error_or_expected`] so transport--/// level user-environment shapes (`network is unreachable`, `dns error`,-/// `connection refused/reset`, `tls handshake`) demote to a `warn`-/// breadcrumb while genuine outages (gateway 5xx, server-side WebSocket-/// close, malformed handshake) fire exactly one Sentry event per affected-/// client.-/// - Above the threshold: `warn` — already paged once; avoid unbounded events-/// during a long outage.-///-/// Extracted as a pure function so it can be unit-tested without running an-/// async event loop or touching the WS stack.-fn log_connection_failure(consecutive: u32, reason: &str) {- if consecutive == FAIL_ESCALATE_THRESHOLD {- // Route the one-shot sustained-outage escalation through the- // observability classifier so an offline user (no wifi / airplane mode- // / `Network is unreachable (os error 51)` — see OPENHUMAN-TAURI-BH)- // does not page on every affected client. Sentry has no signal to act- // on a user being offline — no status, no trace, no payload — so the- // event was pure noise. Genuine outage shapes (gateway 5xx, malformed- // handshake, …) don't match the classifier and still fire one Sentry- // event per affected client, preserving the OPENHUMAN-TAURI-8M intent.- let detailed = format!(- "[socket] Connection failed (sustained outage after {consecutive} attempts): {reason}"- );- let attempts = consecutive.to_string();- crate::core::observability::report_error_or_expected(- detailed.as_str(),- "socket",- "ws_connect",- &[("attempts", attempts.as_str())],- );- } else {- // Below threshold (transient blips) or above threshold (already fired- // the one-shot error): stay at `warn` so subsequent retries don't pile- // up additional Sentry events.- log::warn!(- "[socket] Connection failed (attempt {}/{}): {}",- consecutive,- FAIL_ESCALATE_THRESHOLD,- reason- );- }-}--// ----------------------------------------------------------------------------// Invalid-token decision helper-// -----------------------------------------------------------------------------/// Action the reconnect loop should take after receiving an "Invalid token"-/// rejection from the server.-enum InvalidTokenAction {- /// A genuinely different token is available — retry the connection- /// immediately (no backoff sleep). The fresh token is carried forward so- /// the next `run_connection` uses **exactly** the validated value, not- /// whatever a subsequent re-read of the provider returns — avoiding a- /// redundant lock + disk I/O and the case where the logged `fresh_len`- /// drifts from the token actually sent over the wire.- RetryImmediately { token: String },- /// No fresh token is available; the session is definitively expired.- /// `reason` is a short diagnostic string for the log line.- Escalate { reason: String },-}--/// Pure decision function: given the token that was just rejected and the-/// provider that may have a fresher one, decide what the reconnect loop-/// should do next.-///-/// Calls `provider()` exactly once. No socket I/O.-///-/// - Provider returns a **different, non-empty** token → `RetryImmediately`-/// carrying the fresh token for the caller to reuse on the next attempt.-/// - Provider returns the **same** token → `Escalate` (no point retrying).-/// - Provider returns an **empty** token → `Escalate` (treat as no session).-/// - Provider returns `Err` → `Escalate` with the provider error as reason.-fn decide_after_invalid_token(- previous_token: &str,- provider: &TokenProvider,-) -> InvalidTokenAction {- match provider() {- Ok(fresh) if !fresh.trim().is_empty() && fresh != previous_token => {- InvalidTokenAction::RetryImmediately { token: fresh }- }- Ok(same) if same == previous_token => InvalidTokenAction::Escalate {- reason: "token unchanged after provider re-fetch".to_string(),- },- Ok(_) => InvalidTokenAction::Escalate {- reason: "provider returned empty token".to_string(),- },- Err(e) => InvalidTokenAction::Escalate {- reason: format!("provider error: {e}"),- },- }-}--// ----------------------------------------------------------------------------// Emit-channel draining-// -----------------------------------------------------------------------------/// Discard whatever is still queued on the emit channel, reporting how much.-///-/// Called when a connection ends. The channel outlives the socket — it is-/// created once per `SocketManager::connect` and re-used by every reconnect-/// attempt — so anything left in it would otherwise be delivered on the next-/// connection, where nothing is waiting for it.-///-/// A free function rather than an inline loop so the behaviour is directly-/// testable without standing up a socket.-fn drain_pending_emits(rx: &mut mpsc::UnboundedReceiver<String>) -> usize {- let mut dropped = 0usize;- while rx.try_recv().is_ok() {- dropped += 1;- }- dropped-}--// ----------------------------------------------------------------------------// Single connection attempt-// -----------------------------------------------------------------------------/// Run a single WebSocket connection through handshake and event loop.-///-/// `ws_url` is taken by mutable reference so that any HTTP redirect we follow-/// during the upgrade (see `connect_with_redirects`) is pinned for the next-/// reconnect attempt — we don't want to re-hit the redirect every time the-/// loop backs off and retries.-async fn run_connection(- ws_url: &mut String,- token: &str,- shared: &Arc<SharedState>,- emit_rx: &mut mpsc::UnboundedReceiver<String>,- shutdown_rx: &mut watch::Receiver<bool>,- internal_tx: &mpsc::UnboundedSender<String>,- emit_ready: &Mutex<bool>,-) -> ConnectionOutcome {- log::info!("[socket] WS URL: {}", ws_url);-- // 2. Connect via WebSocket (uses rustls TLS for wss://). Follow HTTP 3xx- // redirects up to MAX_REDIRECT_HOPS so a `http://` config behind a- // Cloudflare-style edge that 301s to `https://` connects cleanly- // instead of looping at error-level forever.- let ws_stream = match connect_with_redirects(ws_url, shared).await {- Ok(stream) => stream,- Err(e) => return ConnectionOutcome::Failed(format!("WebSocket connect: {e}")),- };-- log::info!("[socket] WebSocket connected, starting handshake");- let (mut ws_write, mut ws_read) = ws_stream.split();-- // 3. Read Engine.IO OPEN packet (type 0)- let open_data =- match tokio::time::timeout(Duration::from_secs(10), read_eio_open(&mut ws_read)).await {- Ok(Ok(data)) => data,- Ok(Err(e)) => return ConnectionOutcome::Failed(format!("EIO OPEN: {e}")),- Err(_) => return ConnectionOutcome::Failed("Timeout waiting for EIO OPEN".into()),- };-- let ping_interval = open_data- .get("pingInterval")- .and_then(|v| v.as_u64())- .unwrap_or(25000);- let ping_timeout_ms = open_data- .get("pingTimeout")- .and_then(|v| v.as_u64())- .unwrap_or(20000);- let eio_sid = open_data.get("sid").and_then(|v| v.as_str()).unwrap_or("?");- log::info!(- "[socket] EIO OPEN: sid={}, ping={}ms, timeout={}ms",- eio_sid,- ping_interval,- ping_timeout_ms- );-- // 4. Send Socket.IO CONNECT with auth token- let connect_payload = json!({"token": token});- let connect_msg = format!("40{}", serde_json::to_string(&connect_payload).unwrap());- if let Err(e) = ws_write.send(WsMessage::Text(connect_msg.into())).await {- return ConnectionOutcome::Failed(format!("Send SIO CONNECT: {e}"));- }-- // 5. Read Socket.IO CONNECT ACK (type 40)- let ack_data =- match tokio::time::timeout(Duration::from_secs(10), read_sio_connect_ack(&mut ws_read))- .await- {- Ok(Ok(data)) => data,- Ok(Err(e)) => return ConnectionOutcome::Failed(format!("SIO CONNECT: {e}")),- Err(_) => {- return ConnectionOutcome::Failed("Timeout waiting for SIO CONNECT ACK".into())- }- };-- let sio_sid = ack_data- .get("sid")- .and_then(|v| v.as_str())- .map(String::from);- log::info!("[socket] SIO CONNECT ACK: sid={:?}", sio_sid);-- // 6. Update state to Connected and mark this connection ready to emit.- // The readiness flag is the emit gate (see `SocketManager::emit`): only now,- // past a completed Socket.IO CONNECT ACK, is a queued message guaranteed to- // ride *this* live socket rather than be dropped by `drain_pending_emits`.- // A later server `error` EVENT flips `status` to `Error` for the UI but does- // not return from this function, so the socket stays live and this flag- // stays set — emits keep flowing until the connection is actually torn down.- *shared.status.write() = ConnectionStatus::Connected;- *shared.socket_id.write() = sio_sid;- *emit_ready.lock() = true;- emit_state_change(shared);-- // 7. Main event loop- // Deadline = pingInterval + pingTimeout + 5 s grace so minor server-side- // jitter doesn't cause a spurious reconnect on a healthy connection.- let timeout_ms = ping_interval + ping_timeout_ms + 5_000;- let timeout_duration = Duration::from_millis(timeout_ms);- let mut deadline = Instant::now() + timeout_duration;-- loop {- tokio::select! {- msg = ws_read.next() => {- match msg {- Some(Ok(WsMessage::Text(text))) => {- deadline = Instant::now() + timeout_duration;- handle_eio_message(&text, internal_tx, shared);- }- Some(Ok(WsMessage::Ping(data))) => {- let _ = ws_write.send(WsMessage::Pong(data)).await;- }- Some(Ok(WsMessage::Close(_))) => {- log::info!("[socket] Server closed WebSocket");- return ConnectionOutcome::Lost("Server closed connection".into());- }- Some(Err(e)) => {- return ConnectionOutcome::Lost(format!("WebSocket error: {e}"));- }- None => {- return ConnectionOutcome::Lost("WebSocket stream ended".into());- }- _ => {} // Binary, Pong, Frame- }- }- outgoing = emit_rx.recv() => {- match outgoing {- Some(msg) => {- if let Err(e) = ws_write.send(WsMessage::Text(msg.into())).await {- return ConnectionOutcome::Lost(format!("Send failed: {e}"));- }- }- None => {- let _ = ws_write.send(WsMessage::Close(None)).await;- return ConnectionOutcome::Shutdown;- }- }- }- _ = tokio::time::sleep_until(deadline) => {- log::warn!(- "[socket] No server ping received within {}ms (interval={}ms + timeout={}ms + 5s grace); reconnecting",- timeout_ms,- ping_interval,- ping_timeout_ms,- );- return ConnectionOutcome::Lost("Ping timeout".into());- }- _ = shutdown_rx.changed() => {- if *shutdown_rx.borrow() {- log::info!("[socket] Shutdown signal received");- let _ = ws_write.send(WsMessage::Close(None)).await;- return ConnectionOutcome::Shutdown;- }- }- }- }-}--// ----------------------------------------------------------------------------// Handshake helpers-// -----------------------------------------------------------------------------/// Read the Engine.IO OPEN packet (type 0) from the WebSocket.-///-/// Format: `0{"sid":"...","upgrades":[],"pingInterval":25000,"pingTimeout":20000}`-async fn read_eio_open(- ws_read: &mut futures_util::stream::SplitStream<WsStream>,-) -> Result<serde_json::Value, String> {- loop {- match ws_read.next().await {- Some(Ok(WsMessage::Text(text))) => {- let s: &str = &text;- if let Some(json_str) = s.strip_prefix('0') {- return serde_json::from_str(json_str)- .map_err(|e| format!("Parse EIO OPEN JSON: {e}"));- }- log::debug!(- "[socket] Skipping non-OPEN packet: {}",- utf8_safe_prefix_at_byte_boundary(s, 40)- );- }- Some(Ok(_)) => continue,- Some(Err(e)) => return Err(format!("WS error during handshake: {e}")),- None => return Err("WebSocket closed before OPEN".into()),- }- }-}--/// Read the Socket.IO CONNECT ACK (type 40) from the WebSocket.-///-/// Format: `40{"sid":"..."}` or `44{"message":"error"}` for connect error.-async fn read_sio_connect_ack(- ws_read: &mut futures_util::stream::SplitStream<WsStream>,-) -> Result<serde_json::Value, String> {- loop {- match ws_read.next().await {- Some(Ok(WsMessage::Text(text))) => {- let s: &str = &text;- // Engine.IO MESSAGE (4) + Socket.IO CONNECT (0)- if let Some(json_str) = s.strip_prefix("40") {- if json_str.is_empty() {- return Ok(json!({}));- }- return serde_json::from_str(json_str)- .map_err(|e| format!("Parse CONNECT ACK: {e}"));- }- // Engine.IO MESSAGE (4) + Socket.IO CONNECT_ERROR (4)- if let Some(json_str) = s.strip_prefix("44") {- let err: serde_json::Value =- serde_json::from_str(json_str).unwrap_or(json!({"message": "unknown"}));- let msg = err- .get("message")- .and_then(|v| v.as_str())- .unwrap_or("Connect error");- return Err(format!("Socket.IO connect error: {msg}"));- }- // Engine.IO PING (2) — respond via log, can't write from here- if s.starts_with('2') {- log::debug!("[socket] EIO ping during handshake (will respond after)");- continue;- }- log::debug!(- "[socket] Skipping packet during SIO handshake: {}",- utf8_safe_prefix_at_byte_boundary(s, 40)- );- }- Some(Ok(_)) => continue,- Some(Err(e)) => return Err(format!("WS error during SIO handshake: {e}")),- None => return Err("WebSocket closed before CONNECT ACK".into()),- }- }-}diff --git a/crates/openhuman-core/src/platform/socket/ws_loop_part_02.rs b/crates/openhuman-core/src/platform/socket/ws_loop_part_02.rsdeleted file mode 100644index b69a717f5b..0000000000--- a/crates/openhuman-core/src/platform/socket/ws_loop_part_02.rs+++ /dev/null@@ -1,281 +0,0 @@--// ----------------------------------------------------------------------------// Message handling-// -----------------------------------------------------------------------------/// Handle an incoming Engine.IO text message by its type prefix.-fn handle_eio_message(- text: &str,- emit_tx: &mpsc::UnboundedSender<String>,- shared: &Arc<SharedState>,-) {- if text.is_empty() {- return;- }-- match text.as_bytes()[0] {- b'2' => {- // Engine.IO PING → respond with PONG- let _ = emit_tx.send("3".to_string());- }- b'3' => {- // Engine.IO PONG — ignore (server responding to our ping)- }- b'4' => {- // Engine.IO MESSAGE → contains Socket.IO packet- if text.len() > 1 {- handle_sio_packet(&text[1..], emit_tx, shared);- }- }- b'1' => {- log::info!("[socket] Engine.IO CLOSE from server");- }- b'6' => {- // Engine.IO NOOP- }- _ => {- log::debug!(- "[socket] Unknown EIO packet: {}",- utf8_safe_prefix_at_byte_boundary(text, 30)- );- }- }-}--/// Handle a Socket.IO packet (after stripping the Engine.IO '4' prefix).-fn handle_sio_packet(- text: &str,- emit_tx: &mpsc::UnboundedSender<String>,- shared: &Arc<SharedState>,-) {- if text.is_empty() {- return;- }-- match text.as_bytes()[0] {- b'2' => {- // Socket.IO EVENT: 2["eventName", data]- if let Some((event_name, data)) = parse_sio_event(&text[1..]) {- handle_sio_event(&event_name, data, emit_tx, shared);- } else {- log::warn!(- "[socket] Failed to parse SIO EVENT: {}",- utf8_safe_prefix_at_byte_boundary(text, 80)- );- }- }- b'3' => {- // Socket.IO ACK: 3<ackId>[ackPayload]- if let Some((ack_id, data)) = parse_sio_ack(&text[1..]) {- if shared.ack_registry.resolve(ack_id, data) {- log::debug!("[socket] SIO ACK resolved ack_id={ack_id}");- } else {- log::warn!("[socket] SIO ACK had no pending waiter ack_id={ack_id}");- }- } else {- log::warn!(- "[socket] Failed to parse SIO ACK: {}",- utf8_safe_prefix_at_byte_boundary(text, 80)- );- }- }- b'0' => {- // Socket.IO CONNECT (re-ack during reconnection) — update sid- log::debug!("[socket] SIO CONNECT re-ack");- if text.len() > 1 {- if let Ok(data) = serde_json::from_str::<serde_json::Value>(&text[1..]) {- if let Some(sid) = data.get("sid").and_then(|v| v.as_str()) {- *shared.socket_id.write() = Some(sid.to_string());- emit_state_change(shared);- }- }- }- }- b'1' => {- // Socket.IO DISCONNECT- log::info!("[socket] SIO DISCONNECT from server");- super::medulla::workflows::end_connection_generation();- *shared.status.write() = ConnectionStatus::Disconnected;- *shared.socket_id.write() = None;- emit_state_change(shared);- }- b'4' => {- // Socket.IO CONNECT_ERROR- let error_str = if text.len() > 1 {- &text[1..]- } else {- "unknown"- };- log::error!("[socket] SIO CONNECT_ERROR: {}", error_str);- }- _ => {- log::debug!(- "[socket] Unknown SIO packet type: {}",- utf8_safe_prefix_at_byte_boundary(text, 30)- );- }- }-}--fn parse_sio_ack(text: &str) -> Option<(u64, serde_json::Value)> {- let json_start = text.find('[')?;- if json_start == 0 {- return None;- }- let ack_id = text[..json_start].parse::<u64>().ok()?;- let mut args: Vec<serde_json::Value> = serde_json::from_str(&text[json_start..]).ok()?;- let data = if args.len() == 1 {- args.pop().unwrap_or(serde_json::Value::Null)- } else {- serde_json::Value::Array(args)- };- Some((ack_id, data))-}--// ----------------------------------------------------------------------------// Redirect-following connect-// -----------------------------------------------------------------------------/// Connect to `ws_url`, following HTTP 3xx redirects up to `MAX_REDIRECT_HOPS`.-///-/// Plain `connect_async` returns an error on any non-`101 Switching Protocols`-/// response, so a Cloudflare-style `http://… → https://…` 301 (which happens-/// whenever `BACKEND_URL` is configured without TLS) used to be fatal — the-/// reconnect loop would hammer the same dead URL forever at error level.-///-/// On each redirect we:-/// 1. resolve the `Location` header against the current URL (handles relative-/// Location values),-/// 2. upgrade the scheme so the next attempt is still a WebSocket-/// (`http` → `ws`, `https` → `wss`; `ws`/`wss` pass through),-/// 3. mutate `ws_url` in place so the redirect target is pinned for-/// subsequent reconnects (no need to re-hit the redirect every retry),-/// 4. record a one-shot warning in `SharedState.error` the first time we-/// follow a redirect so the UI can surface "your `BACKEND_URL` is stale".-///-/// On non-redirect failures the original error is returned and the caller-/// counts it toward the exponential backoff like before.-async fn connect_with_redirects(- ws_url: &mut String,- shared: &Arc<SharedState>,-) -> Result<WsStream, WsError> {- let original = ws_url.clone();- for hop in 0..=MAX_REDIRECT_HOPS {- match connect_async(ws_url.as_str()).await {- Ok((stream, _response)) => return Ok(stream),- Err(WsError::Http(response)) if is_redirect_status(response.status()) => {- if hop == MAX_REDIRECT_HOPS {- log::error!(- "[socket] Exceeded {MAX_REDIRECT_HOPS} redirect hops starting from {original}; giving up"- );- return Err(WsError::Http(response));- }- let location = match extract_location_header(&response) {- Some(loc) => loc,- None => {- log::error!(- "[socket] Redirect {} from {ws_url} missing Location header",- response.status()- );- return Err(WsError::Http(response));- }- };- let next_url = match resolve_redirect_target(ws_url, &location) {- Ok(url) => url,- Err(e) => {- log::error!(- "[socket] Cannot follow redirect to {location} from {ws_url}: {e}"- );- return Err(WsError::Http(response));- }- };- log::warn!(- "[socket] Server redirected ({}) {} → {}",- response.status(),- ws_url,- next_url- );- // Only persist a stale-BACKEND_URL warning for permanent- // redirects (301 / 308). Temporary redirects (302 / 307) say- // "this time, go elsewhere" — the configured BACKEND_URL is- // still correct, and surfacing a "please update config" hint- // for a transient hop would be misleading. Per CodeRabbit- // review on PR #1547.- if matches!(- response.status(),- StatusCode::MOVED_PERMANENTLY | StatusCode::PERMANENT_REDIRECT- ) {- record_redirect_warning(shared, &original, &next_url);- }- *ws_url = next_url;- }- Err(e) => return Err(e),- }- }- // Unreachable: the loop either returns Ok, returns the redirect error after- // exhausting hops, or returns a non-redirect Err.- unreachable!("connect_with_redirects exited loop without returning")-}--/// Statuses we treat as "follow the Location and retry".-///-/// 308 (Permanent Redirect) and 307 (Temporary Redirect) explicitly preserve-/// the method; 301/302 historically do too for upgrade requests in practice.-/// Anything else (300, 304, ...) stays an error.-fn is_redirect_status(status: StatusCode) -> bool {- matches!(- status,- StatusCode::MOVED_PERMANENTLY- | StatusCode::FOUND- | StatusCode::TEMPORARY_REDIRECT- | StatusCode::PERMANENT_REDIRECT- )-}--fn extract_location_header(- response: &tokio_tungstenite::tungstenite::http::Response<Option<Vec<u8>>>,-) -> Option<String> {- response- .headers()- .get(tokio_tungstenite::tungstenite::http::header::LOCATION)- .and_then(|v| v.to_str().ok())- .map(|s| s.to_string())-}--/// Resolve `location` against `current_ws_url` and rewrite the scheme so the-/// result is still a valid WebSocket URL.-///-/// `location` may be absolute (`https://host/path?q=1`) or relative-/// (`/socket.io/?EIO=4`). We use the `url` crate's relative-URL parser to do-/// the join the same way browsers do, then map `http`→`ws` / `https`→`wss`.-fn resolve_redirect_target(current_ws_url: &str, location: &str) -> Result<String, String> {- let base = url::Url::parse(current_ws_url).map_err(|e| format!("invalid current URL: {e}"))?;- let resolved = base- .join(location)- .map_err(|e| format!("invalid Location {location:?}: {e}"))?;-- let upgraded_scheme = match resolved.scheme() {- "http" => "ws",- "https" => "wss",- "ws" | "wss" => resolved.scheme(),- other => return Err(format!("unsupported scheme in Location: {other}")),- };-- let mut next = resolved.clone();- next.set_scheme(upgraded_scheme)- .map_err(|_| format!("failed to set scheme {upgraded_scheme} on {resolved}"))?;- Ok(next.to_string())-}--/// Persist a one-shot, user-visible warning that the backend redirected the-/// configured socket URL. Subsequent redirects in the same connect attempt-/// don't overwrite — the first hop carries the actionable signal.-fn record_redirect_warning(shared: &Arc<SharedState>, original: &str, resolved: &str) {- let mut slot = shared.error.write();- if slot.is_some() {- return;- }- *slot = Some(format!(- "Backend redirected {original} → {resolved}. Update BACKEND_URL to the resolved URL to avoid the extra hop."- ));-}diff --git a/crates/openhuman-core/src/web_chat/ops.rs b/crates/openhuman-core/src/web_chat/ops.rsindex aa3879882e..d674dcacb0 100644--- a/crates/openhuman-core/src/web_chat/ops.rs+++ b/crates/openhuman-core/src/web_chat/ops.rs@@ -18,16 +18,16 @@ pub(super) use budget_correlation::{};pub use channel_ops::{- cancel_chat, cancel_chat_scoped, channel_web_cancel, channel_web_chat,- channel_web_queue_clear, channel_web_queue_status,+ cancel_chat, cancel_chat_scoped, channel_web_cancel, channel_web_chat, channel_web_queue_clear,+ channel_web_queue_status,};pub use start_chat::start_chat;-pub(super) use state::{cancel_in_flight_gracefully, event_session_id_for, key_for};-pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};#[cfg(any(test, debug_assertions))]pub use state::parallel_in_flight_entries_for_test;+pub(super) use state::{cancel_in_flight_gracefully, event_session_id_for, key_for};+pub use state::{cancel_should_target, in_flight_entries_for_test, invalidate_thread_sessions};pub(super) use state::{IN_FLIGHT, PARALLEL_IN_FLIGHT, THREAD_SESSIONS};#[cfg(any(test, debug_assertions))]diff --git a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs b/crates/openhuman-core/src/web_chat/ops/channel_ops.rsindex 1bd0b567fc..841ad1e00b 100644--- a/crates/openhuman-core/src/web_chat/ops/channel_ops.rs+++ b/crates/openhuman-core/src/web_chat/ops/channel_ops.rs@@ -223,11 +223,7 @@ pub async fn channel_web_cancel(let cancelled = if cancelled_request_id.is_some() {true} else {- crate::agent::task_dispatcher::cancel_session_scoped(- thread_id.trim(),- request_id,- )- .await+ crate::agent::task_dispatcher::cancel_session_scoped(thread_id.trim(), request_id).await};Ok(RpcOutcome::single_log(diff --git a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rsindex f3af806ffb..a0ae7bd699 100644--- a/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs+++ b/crates/openhuman-core/src/web_chat/ops/parallel_turn.rs@@ -13,7 +13,9 @@ 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::PARALLEL_IN_FLIGHT;-use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag};+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@@ -46,132 +48,132 @@ pub(crate) async fn spawn_parallel_turn(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(),- };- 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(- task_cancel_token,- origin,- approval_ctx,- run_chat_task(- &client_id_task,- &thread_id_task,- &request_id_task,- &user_message,- model_override,- temperature,- profile_id,- locale,- run_queue,- metadata,- /* fork */ true,- ),- )- .await;-- match result {- Some(Ok(chat_result)) => {- crate::web_chat::presentation::deliver_response(+ let approval_ctx = crate::security::approval::ApprovalChatContext {+ thread_id: thread_id_task.clone(),+ client_id: client_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(+ task_cancel_token,+ origin,+ approval_ctx,+ run_chat_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()),- )- .await;- }- Some(Err(err)) => {- log::warn!(+ model_override,+ temperature,+ profile_id,+ locale,+ run_queue,+ metadata,+ /* fork */ true,+ ),+ )+ .await;++ match result {+ Some(Ok(chat_result)) => {+ crate::web_chat::presentation::deliver_response(+ &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()),+ )+ .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!(+ 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;+ 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)),- ],- );- }+ // 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(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,- ..Default::default()- });- }- None => {- log::info!(+ publish_web_channel_event(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,+ ..Default::default()+ });+ }+ None => {+ log::info!("[web-channel] parallel turn cancelled cooperatively thread_id={} request_id={}",thread_id_task,request_id_task);+ }}- }- PARALLEL_IN_FLIGHT.lock().await.remove(&request_id_task);+ PARALLEL_IN_FLIGHT.lock().await.remove(&request_id_task);},));diff --git a/crates/openhuman-core/src/web_chat/ops/start_chat.rs b/crates/openhuman-core/src/web_chat/ops/start_chat.rsindex 0c1e1430f0..4a643b6741 100644--- a/crates/openhuman-core/src/web_chat/ops/start_chat.rs+++ b/crates/openhuman-core/src/web_chat/ops/start_chat.rs@@ -19,7 +19,9 @@ use super::super::types::{ChatRequestMetadata, InFlightEntry};use super::super::web_errors::classify_inference_error;use super::parallel_turn::spawn_parallel_turn;use super::state::{cancel_in_flight_gracefully, key_for, IN_FLIGHT};-use super::turn_guards::{run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag};+use super::turn_guards::{+ run_turn_under_cancel_and_deadline, sentry_suppression_reason, timeout_bound_tag,+};fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {match action {@@ -78,9 +80,7 @@ pub async fn start_chat(// than passing the raw `[FILE:data:…]`/`[IMAGE:data:…]` blob through —// otherwise the injection scan, history/JSONL persistence, and memory// autosave all see the multi-MB data URI again, reopening the flood path.- let (file_cfg, image_cfg) = match crate::config::rpc::load_config_with_timeout()- .await- {+ let (file_cfg, image_cfg) = match crate::config::rpc::load_config_with_timeout().await {Ok(cfg) => {log::debug!("[web-channel][ingress] using configured multimodal limits thread_id={}",@@ -102,8 +102,7 @@ pub async fn start_chat(let extracted =crate::agent::multimodal::inline_file_attachments(&message, &file_cfg).await;let processed =- crate::agent::multimodal::stash_image_attachments(&extracted, &image_cfg)- .await;+ crate::agent::multimodal::stash_image_attachments(&extracted, &image_cfg).await;log::debug!("[web-channel][ingress] attachment preprocessing complete thread_id={} before_chars={} after_chars={}",thread_id,@@ -153,9 +152,7 @@ pub async fn start_chat(// is a yes/no reply, route it to the gate rather than starting a new turn.if let Some(gate) = crate::security::approval::ApprovalGate::try_global() {if let Some(request_id) = gate.pending_for_thread(&thread_id) {- if let Some(decision) =- crate::security::approval::parse_approval_reply(&message)- {+ if let Some(decision) = crate::security::approval::parse_approval_reply(&message) {match gate.decide(&request_id, decision) {Ok(Some(_)) => {log::info!(@@ -356,167 +353,167 @@ pub async fn start_chat(let user_message = message.clone();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(),- };- 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()),- };- // `None` => the turn was cancelled cooperatively before producing a- // result; the interrupting/cancelling side already emitted the- // user-facing `chat_error`, so we just unwind quietly here.- let result = run_turn_under_cancel_and_deadline(- task_cancel_token,- origin,- approval_ctx,- run_chat_task(- &client_id_task,- &thread_id_task,- &request_id_task,- &user_message,- model_override,- temperature,- profile_id,- locale,- turn_run_queue_task,- metadata,- /* fork */ false,- ),- )- .await;+ let approval_ctx = crate::security::approval::ApprovalChatContext {+ thread_id: thread_id_task.clone(),+ client_id: client_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()),+ };+ // `None` => the turn was cancelled cooperatively before producing a+ // result; the interrupting/cancelling side already emitted the+ // user-facing `chat_error`, so we just unwind quietly here.+ let result = run_turn_under_cancel_and_deadline(+ task_cancel_token,+ origin,+ approval_ctx,+ run_chat_task(+ &client_id_task,+ &thread_id_task,+ &request_id_task,+ &user_message,+ model_override,+ temperature,+ profile_id,+ locale,+ turn_run_queue_task,+ metadata,+ /* fork */ false,+ ),+ )+ .await;- let result = match result {- Some(res) => res,- None => {- log::info!(+ let result = match result {+ Some(res) => res,+ None => {+ log::info!("[web-channel] turn cancelled cooperatively client_id={} thread_id={} request_id={}",client_id_task,thread_id_task,request_id_task);- // Release any in-flight slot we still own and stop. The- // `request_id` guard below prevents clobbering a newer turn that- // replaced us on the interrupt path.- let mut in_flight = IN_FLIGHT.lock().await;- if let Some(current) = in_flight.get(&map_key_task) {- if current.request_id == request_id_task {- in_flight.remove(&map_key_task);+ // Release any in-flight slot we still own and stop. The+ // `request_id` guard below prevents clobbering a newer turn that+ // replaced us on the interrupt path.+ let mut in_flight = IN_FLIGHT.lock().await;+ if let Some(current) = in_flight.get(&map_key_task) {+ if current.request_id == request_id_task {+ in_flight.remove(&map_key_task);+ }}+ return;}- return;- }- };+ };- match result {- Ok(chat_result) => {- crate::web_chat::presentation::deliver_response(- &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()),- )- .await;- }- Err(err) => {- log::warn!(+ match result {+ Ok(chat_result) => {+ crate::web_chat::presentation::deliver_response(+ &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()),+ )+ .await;+ }+ Err(err) => {+ log::warn!("[web-channel] run_chat_task failed client_id={} thread_id={} request_id={} error={}",client_id_task,thread_id_task,request_id_task,err);- let detailed = format!(- "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;- let classified_type_string = classified_type.to_string();- if let Some(reason) = sentry_suppression_reason(&detailed) {- log::info!(- target: "web_channel",- "[web_channel.run_chat_task] 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",- "run_chat_task",- &[- ("channel", "web"),- ("error_type", classified_type),- ("thread_id", thread_id_task.as_str()),- ("request_id", request_id_task.as_str()),- // Names which ceiling fired for the harness- // timeouts this arm now reports (#5804); "none"- // for every other error type.- ("timeout_bound", timeout_bound_tag(&detailed)),- ],+ let detailed = format!(+ "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;+ let classified_type_string = classified_type.to_string();+ if let Some(reason) = sentry_suppression_reason(&detailed) {+ log::info!(+ target: "web_channel",+ "[web_channel.run_chat_task] 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",+ "run_chat_task",+ &[+ ("channel", "web"),+ ("error_type", classified_type),+ ("thread_id", thread_id_task.as_str()),+ ("request_id", request_id_task.as_str()),+ // Names which ceiling fired for the harness+ // timeouts this arm now reports (#5804); "none"+ // for every other error type.+ ("timeout_bound", timeout_bound_tag(&detailed)),+ ],+ );+ }+ publish_web_channel_event(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_type_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,+ ..Default::default()+ });}- publish_web_channel_event(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_type_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,- ..Default::default()- });}- }- // Drain followup messages queued during this turn.- let followups = {- let mut in_flight = IN_FLIGHT.lock().await;- let followups = if let Some(current) = in_flight.get(&map_key_task) {- if current.request_id == request_id_task {- let fups = current.run_queue.drain_followups().await;- in_flight.remove(&map_key_task);- fups+ // Drain followup messages queued during this turn.+ let followups = {+ let mut in_flight = IN_FLIGHT.lock().await;+ let followups = if let Some(current) = in_flight.get(&map_key_task) {+ if current.request_id == request_id_task {+ let fups = current.run_queue.drain_followups().await;+ in_flight.remove(&map_key_task);+ fups+ } else {+ Vec::new()+ }} else {Vec::new()- }- } else {- Vec::new()+ };+ followups};- followups- };- if !followups.is_empty() {- log::info!(- "[web-channel] dispatching {} followup(s) thread_id={}",- followups.len(),- thread_id_task- );- crate::core::bus::BUS.publish(- crate::core::events::DomainEvent::RunQueueFollowupDispatched {- thread_id: thread_id_task.clone(),- followup_count: followups.len(),- },- );- dispatch_followups(followups);- }+ if !followups.is_empty() {+ log::info!(+ "[web-channel] dispatching {} followup(s) thread_id={}",+ followups.len(),+ thread_id_task+ );+ crate::core::bus::BUS.publish(+ crate::core::events::DomainEvent::RunQueueFollowupDispatched {+ thread_id: thread_id_task.clone(),+ followup_count: followups.len(),+ },+ );+ dispatch_followups(followups);+ }},));@@ -540,25 +537,25 @@ fn dispatch_followups(followups: Vec<crate::agent::harness::run_queue::QueuedMesfor fup in followups {tokio::spawn(crate::core::runtime::context::CoreContext::propagate(async move {- if let Err(err) = start_chat(- &fup.client_id,- &fup.thread_id,- &fup.text,- fup.model_override,- fup.temperature,- fup.profile_id,- fup.locale,- Some("followup".to_string()),- ChatRequestMetadata::default(),- )- .await- {- log::warn!(- "[web-channel] failed to dispatch followup thread_id={} err={}",- fup.thread_id,- err- );- }+ if let Err(err) = start_chat(+ &fup.client_id,+ &fup.thread_id,+ &fup.text,+ fup.model_override,+ fup.temperature,+ fup.profile_id,+ 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/web_errors.rs b/crates/openhuman-core/src/web_chat/web_errors.rsindex 19d442e15f..4e5c1c8c8b 100644--- a/crates/openhuman-core/src/web_chat/web_errors.rs+++ b/crates/openhuman-core/src/web_chat/web_errors.rs@@ -21,5 +21,9 @@ pub(crate) use provider_detail::{with_provider_detail,};pub(crate) use response_predicates::is_empty_provider_response_text;-pub(crate) use retry::{parse_retry_after_secs_from_str, retry_after_hint, is_non_retryable_rate_limit_text};-pub(crate) use timeout::{is_outer_backstop_timeout, is_turn_timeout_error, turn_timeout_error_message};+pub(crate) use retry::{+ is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,+};+pub(crate) use timeout::{+ is_outer_backstop_timeout, is_turn_timeout_error, turn_timeout_error_message,+};diff --git a/crates/openhuman-core/src/web_chat/web_errors/classify.rs b/crates/openhuman-core/src/web_chat/web_errors/classify.rsindex 009b067662..44338a9424 100644--- a/crates/openhuman-core/src/web_chat/web_errors/classify.rs+++ b/crates/openhuman-core/src/web_chat/web_errors/classify.rs@@ -7,13 +7,17 @@ use super::budget::{generic_inference_error_user_message, inference_budget_exceeded_user_message,is_action_budget_exhausted, is_inference_budget_exceeded_error,};-use super::provider_detail::{extract_provider_name, is_fallback_chain_exhausted, with_provider_detail};+use super::provider_detail::{+ extract_provider_name, is_fallback_chain_exhausted, with_provider_detail,+};use super::response_predicates::{is_connection_dropped_text, is_empty_provider_response_text, is_malformed_tool_history_text,is_provider_request_rejected_text, is_transient_unavailability_text,malformed_history_user_message,};-use super::retry::{is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint};+use super::retry::{+ is_non_retryable_rate_limit_text, parse_retry_after_secs_from_str, retry_after_hint,+};use super::timeout::is_turn_timeout_error;/// Structured chat-error envelope produced by [`classify_inference_error`].diff --git a/crates/openhuman-core/src/web_chat/web_tests.rs b/crates/openhuman-core/src/web_chat/web_tests.rsindex aa4821e6d9..b321019644 100644--- a/crates/openhuman-core/src/web_chat/web_tests.rs+++ b/crates/openhuman-core/src/web_chat/web_tests.rs@@ -117,11 +117,11 @@ async fn wait_for_parallel<F: Fn(&[(String, String)]) -> bool>(pred: F) -> Vec<(.expect("parallel in-flight condition not met before timeout")}-#[path = "web_tests_start_chat_ingress_tests.rs"]-mod start_chat_ingress_tests;-#[path = "web_tests_rate_limit_classification_tests.rs"]-mod rate_limit_classification_tests;#[path = "web_tests_error_code_classification_tests.rs"]mod error_code_classification_tests;+#[path = "web_tests_rate_limit_classification_tests.rs"]+mod rate_limit_classification_tests;#[path = "web_tests_session_and_concurrency_tests.rs"]mod session_and_concurrency_tests;+#[path = "web_tests_start_chat_ingress_tests.rs"]+mod start_chat_ingress_tests;