The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(web_chat): handle missing thread state in ops handlers
Steven Enamakelf0aef42ee300
diff --git a/crates/openhuman-core/src/bin/fleet_tests.rs b/crates/openhuman-core/src/bin/fleet_tests.rsindex 07389d2b88..02b13a6a13 100644--- a/crates/openhuman-core/src/bin/fleet_tests.rs+++ b/crates/openhuman-core/src/bin/fleet_tests.rs@@ -227,4 +227,3 @@ fn fleet_cors_headers_echo_allowed_origin_only() {.get(header::ACCESS_CONTROL_ALLOW_ORIGIN).is_none());}-}diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rsindex 57f2b2278f..2fe5f20643 100644--- a/crates/openhuman-core/src/core/observability.rs+++ b/crates/openhuman-core/src/core/observability.rs@@ -3710,612 +3710,9 @@ fn parse_version(version: &str) -> Option<(u32, u32)> {}#[cfg(test)]-mod tests {- use super::*;+#[path = "obs_tests_placeholder.rs"]+mod tests;- #[test]- fn usage_probe_backoff_sentinel_classifies_only_its_own_prefix() {- // The producer in `team::ops` builds its sentinel from this prefix.- let sentinel = format!("{USAGE_PROBE_BACKOFF_PREFIX} recent /teams/me/usage failure");- assert!(is_suppressed_usage_probe_backoff(&sentinel));- // Real backend error strings must NEVER match — they keep reporting.- assert!(!is_suppressed_usage_probe_backoff(- "GET /teams/me/usage failed (500 Internal Server Error): "- ));- assert!(!is_suppressed_usage_probe_backoff(- "GET /teams/me/usage failed (404 Not Found); response_body_len=91"- ));- assert!(!is_suppressed_usage_probe_backoff("SESSION_EXPIRED: ..."));- assert!(!is_suppressed_usage_probe_backoff(""));- }-- /// Helper must accept `&anyhow::Error`, `&dyn std::error::Error`, and- /// plain `&str` — the three shapes that show up at error sites today.- #[test]- fn report_error_accepts_common_error_shapes() {- let anyhow_err = anyhow::anyhow!("boom");- report_error(&anyhow_err, "test", "anyhow_shape", &[]);-- let io_err = std::io::Error::other("io failed");- report_error(&io_err, "test", "io_shape", &[("kind", "io")]);-- report_error("plain message", "test", "str_shape", &[]);- }-- #[test]- fn anyhow_chain_is_rendered_in_full() {- // Regression guard: `err.to_string()` on an anyhow chain only emits- // the outermost context. Using `{:#}` joins every cause, which is- // what Sentry needs to actually diagnose wrapped failures.- let inner = std::io::Error::other("inner cause");- let wrapped = anyhow::Error::from(inner).context("outer ctx");- assert_eq!(format!("{wrapped:#}"), "outer ctx: inner cause");- }-- /// Sentry TAURI-RUST-5EH: the benign already-decided/expired approval race- /// (`rpc::approval_decide` after `get_decision` confirms a persisted- /// decision) must classify as `ApprovalNoPendingRace` so the ~1,995-event- /// flood is demoted — while a genuine never-registered id (distinct- /// "ever registered" wording) must stay reportable (`None`).- #[test]- fn classifies_benign_approval_race_but_keeps_genuine_loss() {- assert_eq!(- expected_error_kind(- "rpc.invoke_method failed: no pending approval found for request_id \- '4f1c…' (already decided or expired)"- ),- Some(ExpectedErrorKind::ApprovalNoPendingRace),- "benign already-decided/expired race must be demoted"- );- assert_eq!(- expected_error_kind(- "rpc.invoke_method failed: no pending approval ever registered \- for request_id '4f1c…'"- ),- None,- "a genuine lost registration must remain a Sentry signal"- );- }-- /// Exercise the full demotion path (classifier -> report arm) for a benign- /// approval race: it must take the expected branch and not panic.- #[test]- fn report_error_or_expected_demotes_benign_approval_race() {- report_error_or_expected(- "no pending approval found for request_id 'abc' (already decided or expired)",- "rpc",- "invoke_method",- &[],- );- }-- #[test]- fn classifies_expected_config_errors() {- assert_eq!(- expected_error_kind("rpc.invoke_method failed: local ai is disabled"),- Some(ExpectedErrorKind::LocalAiDisabled)- );- assert_eq!(- expected_error_kind(- "agent.provider_chat failed: ollama API key not set. Configure via the web UI"- ),- Some(ExpectedErrorKind::ApiKeyMissing)- );- assert_eq!(- expected_error_kind("ollama embed failed with status 500"),- None- );- }-- /// Sentry TAURI-RUST-83A: the Codex-CLI import user-state errors must- /// classify as `CodexCliAuthUnavailable` so the ~430-event flood stays out- /// of Sentry. Verbatim envelope shapes from- /// `openai_oauth::store::import_codex_cli_auth_from_path` (with a fake path- /// in place of the real `~/.codex/auth.json`).- #[test]- fn classifies_codex_cli_import_user_state_as_expected() {- for msg in [- "Could not read Codex CLI auth at /home/u/.codex/auth.json: No such file \- or directory. Run `codex login` first, then try Codex auth again.",- "Could not parse Codex CLI auth at /home/u/.codex/auth.json: expected value. \- Run `codex login` again, then try Codex auth again.",- "Codex CLI auth at /home/u/.codex/auth.json has no tokens. Run `codex login` first.",- "Codex CLI auth at /home/u/.codex/auth.json has no access token. Run `codex login` first.",- "home directory is not set; cannot find ~/.codex/auth.json",- ] {- assert_eq!(- expected_error_kind(msg),- Some(ExpectedErrorKind::CodexCliAuthUnavailable),- "must classify as CodexCliAuthUnavailable: {msg}"- );- }- }-- /// Exercise the full demotion path (classifier -> report arm) for a codex- /// auth-unavailable message: it must take the expected branch and not panic.- #[test]- fn report_error_or_expected_demotes_codex_auth_unavailable() {- report_error_or_expected(- "Could not read Codex CLI auth at /home/u/.codex/auth.json: No such file \- or directory. Run `codex login` first, then try Codex auth again.",- "inference",- "openai_oauth_import_codex_cli",- &[],- );- }-- /// Sentry TAURI-RUST-CGP: a remote MCP server's connect-time 401 is- /// preventable user-state (the server needs OAuth sign-in), already handled- /// by the `needs_auth` UX (#3733 / #3719), so it must classify as- /// `McpServerNeedsAuth` and stay out of Sentry. The canonical body comes- /// straight from `tinymcp::Error::Unauthorized`'s `Display` impl (both the- /// bare and `resource metadata:` variants), plus the- /// `mcp_clients_connect`-prefixed RPC re-report shape that actually reaches- /// the dispatcher.- #[test]- fn classifies_mcp_connect_401_as_needs_auth() {- // The 401 is a variant of `tinymcp`'s error now rather than a- // standalone type. What this test pins is unchanged: the *wording* the- // classifier keys on, which is what reaches the dispatcher.- let bare = tinymcp::Error::Unauthorized {- endpoint: "https://youtube.run.tools".to_string(),- resource_metadata: None,- };- let with_meta = tinymcp::Error::Unauthorized {- endpoint: "https://youtube.run.tools".to_string(),- resource_metadata: Some(- "https://youtube.run.tools/.well-known/oauth-protected-resource".to_string(),- ),- };- for msg in [- bare.to_string(),- with_meta.to_string(),- // The stringified RPC re-report shape that propagates from- // `mcp_clients_connect` to `report_error_or_expected`.- format!("openhuman.mcp_clients_connect failed: {with_meta}"),- ] {- assert_eq!(- expected_error_kind(&msg),- Some(ExpectedErrorKind::McpServerNeedsAuth),- "must classify MCP connect 401 as McpServerNeedsAuth: {msg}"- );- }- // Full demotion path (classifier -> report arm) must not panic.- report_error_or_expected(- &bare.to_string(),- "rpc",- "openhuman.mcp_clients_connect",- &[],- );- }-- /// #5805 — an unconfigured wallet is the default state of an optional- /// feature, but every path that surfaced it reached Sentry as an error: 55- /// events in 72 minutes on one ordinary local session, while a genuine- /// turn-killing failure in the same session emitted zero (#5804).- ///- /// The bare message was already demoted at the RPC boundary by- /// `jsonrpc::is_wallet_not_configured_error`, which is exact equality — so- /// a single caller adding context defeated it. The observed wrap is- /// `self_identity key_status: {e}`, but nothing about the fix is specific- /// to that method: the classifier is substring-based, so it must hold for- /// any wrapper, at any nesting depth, on every path that reports through- /// `report_error_or_expected`. The cases below pin exactly that.- #[test]- fn classifies_wallet_not_configured_as_expected_however_it_is_wrapped() {- let sentinel = crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE;- for msg in [- // Bare, as the wallet layer produces it.- sentinel.to_string(),- // The wrap that #5805 actually observed.- format!("wallet status: {sentinel}"),- // Two layers — a wrapper wrapping a wrapper. Exact equality and a- // single-prefix strip both fail here; substring matching does not.- format!("wallet transfer failed: wallet status: {sentinel}"),- // A different domain entirely, to show the fix is not scoped to the- // one call site the issue was found through.- format!("wallet balance failed: {sentinel}"),- ] {- assert_eq!(- expected_error_kind(&msg),- Some(ExpectedErrorKind::WalletNotConfigured),- "must classify an unconfigured wallet as expected, however wrapped: {msg}"- );- }- // Full demotion path (classifier -> report arm) must not panic.- report_error_or_expected(- &format!("wallet status: {sentinel}"),- "rpc",- "invoke_method",- &[],- );- }-- /// The demotion must stay narrow: a real wallet fault still has to page.- /// The needle is a whole sentence, so merely mentioning a wallet — or- /// failing *after* one is configured — must not be swallowed.- #[test]- fn wallet_demotion_does_not_swallow_real_wallet_failures() {- for msg in [- "wallet keychain read failed: entry not found",- "no wallet account derived for chain 'solana'",- "wallet is not responding",- "failed to decrypt wallet mnemonic",- ] {- assert_ne!(- expected_error_kind(msg),- Some(ExpectedErrorKind::WalletNotConfigured),- "must NOT classify as WalletNotConfigured: {msg}"- );- }- }-- /// `is_wallet_not_configured_message` compares the shared constant against- /// an already-lowercased haystack without allocating, which is only sound- /// while the constant itself is lowercase. If a future reword introduces a- /// capital, this fails here rather than silently ending the demotion.- #[test]- fn wallet_not_configured_sentinel_is_ascii_lowercase() {- let sentinel = crate::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE;- assert_eq!(- sentinel,- sentinel.to_ascii_lowercase(),- "WALLET_NOT_CONFIGURED_MESSAGE must stay ASCII-lowercase, or \- is_wallet_not_configured_message must lowercase it before comparing"- );- }-- /// Sentry TAURI-RUST-QWW (#5164): a memory-store identifier rejection is- /// deterministic in the caller's own input, so it repeats at the caller's- /// retry rate (3,055 events / 1 user / 1 day) without carrying new signal.- /// Every rejection wording the store emits must classify as- /// `MemoryIdentifierRejected`, including the retired PII wording that- /// pre-#5164 cores still send.- #[test]- fn classifies_memory_identifier_rejections_as_expected() {- for msg in [- "document namespace/key cannot contain secrets",- "document namespace/key cannot contain personal identifiers",- "document key cannot be empty",- "kv key cannot contain secrets",- "kv namespace/key cannot contain secrets",- "episodic session_id/role cannot contain secrets",- // The stringified RPC re-report shape that reaches the dispatcher.- "openhuman.memory_store failed: document namespace/key cannot contain secrets",- ] {- assert_eq!(- expected_error_kind(msg),- Some(ExpectedErrorKind::MemoryIdentifierRejected),- "must classify as MemoryIdentifierRejected: {msg}"- );- }- // Full demotion path (classifier -> report arm) must not panic.- report_error_or_expected(- "document namespace/key cannot contain secrets",- "rpc",- "openhuman.memory_store",- &[],- );- }-- /// Guard against over-suppression: a real failure on the same memory write- /// path — SQLite, embeddings, the markdown sidecar — carries none of the- /// rejection wording and MUST still reach Sentry (stay `None`). Nor may a- /// bare "cannot contain secrets" from an unrelated domain borrow the- /// memory-store demotion.- #[test]- fn does_not_classify_real_memory_write_failures_as_identifier_rejections() {- for msg in [- "upsert memory_docs: database is locked",- "insert vector chunk: disk I/O error",- "lookup existing document_id: no such table: memory_docs",- "write_markdown_doc: permission denied",- "webhook payload cannot contain secrets",- ] {- assert_ne!(- expected_error_kind(msg),- Some(ExpectedErrorKind::MemoryIdentifierRejected),- "must NOT classify as MemoryIdentifierRejected: {msg}"- );- }- }-- /// Guard against over-suppression: an MCP transport failure that is NOT the- /// typed 401 (a 500, or a generic "unauthorized" with no MCP anchor) MUST- /// still reach Sentry (stay `None`) so a real defect isn't blinded.- #[test]- fn does_not_classify_other_mcp_or_401_errors_as_needs_auth() {- for msg in [- "MCP server `https://youtube.run.tools` returned HTTP 500: internal error",- "openhuman.mcp_clients_connect failed: connection refused",- "Unauthorized (HTTP 401) from some unrelated provider",- ] {- assert_ne!(- expected_error_kind(msg),- Some(ExpectedErrorKind::McpServerNeedsAuth),- "must NOT classify as McpServerNeedsAuth: {msg}"- );- }- }-- /// Guard against over-suppression on the import path: a genuine- /// keyring/persist failure (`upsert_profile`) or an unrelated error carries- /// neither the `codex cli auth` nor the `.codex/auth.json` anchor and MUST- /// still reach Sentry (stay `None`) so a real defect isn't blinded.- #[test]- fn does_not_classify_codex_persist_failure_as_codex_auth_unavailable() {- for msg in [- "failed to write auth profile store: keyring error: access denied",- "Auth profile not found: provider:openai/oauth",- "unable to open database file",- ] {- assert_ne!(- expected_error_kind(msg),- Some(ExpectedErrorKind::CodexCliAuthUnavailable),- "real-defect/unrelated error must NOT be demoted as codex auth-unavailable: {msg}"- );- }- }-- /// Sentry TAURI-RUST-8FQ: the OpenAI ChatGPT/Codex OAuth `token_expired`- /// 401 re-raised at the RPC boundary (`{provider} Responses API error: …`)- /// must classify as `ProviderUserState` so the re-report is demoted, not- /// just the emit-site event. A genuine bad-key 401 must stay reportable.- #[test]- fn classifies_openai_oauth_token_expired_as_provider_user_state() {- let bail = "openai Responses API error: {\"error\":{\"message\":\"Provided \- authentication token is expired. Please try signing in again.\",\- \"type\":null,\"code\":\"token_expired\"}}";- assert_eq!(- expected_error_kind(bail),- Some(ExpectedErrorKind::ProviderUserState),- "OAuth token_expired re-report must be demoted at the RPC boundary"- );- // A real misconfigured key must NOT be swallowed by this arm.- let bad_key = "openai Responses API error: {\"error\":{\"code\":\"invalid_api_key\",\- \"message\":\"Incorrect API key provided.\"}}";- assert_ne!(- expected_error_kind(bad_key),- Some(ExpectedErrorKind::ProviderUserState),- "a genuine bad-key 401 must remain reportable"- );- }-- /// Sentry TAURI-RUST-R4: the composio direct-mode factory bail must- /// classify as `ApiKeyMissing` so any residual emit (explicit- /// execute/authorize call with no key) stays out of Sentry. Uses the- /// verbatim wire shape from `client.rs`.- #[test]- fn classifies_composio_direct_no_api_key_as_api_key_missing() {- assert_eq!(- expected_error_kind(- "[composio] list_connections: composio direct mode selected but no api key \- is configured (set via composio.set_api_key RPC or config.composio.api_key)"- ),- Some(ExpectedErrorKind::ApiKeyMissing)- );- }-- /// Sentry TAURI-RUST-52S: Cohere's hosted `/v2/embed` returns a 401 with- /// body `"no api key supplied"` when called with an empty bearer (BYO-key- /// embedding path, no key configured). Verbatim wire shape from the embed- /// client must classify as `ApiKeyMissing` so the 8.7k-event flood stays- /// out of Sentry even from clients that predate the call-site guard.- #[test]- fn classifies_cohere_missing_api_key_401_as_api_key_missing() {- assert_eq!(- expected_error_kind(- "Cohere embed API error (401 Unauthorized): \- {\"id\":\"3176e92f-d18e-4019-bd43-314821504a61\",\- \"message\":\"no api key supplied\"}"- ),- Some(ExpectedErrorKind::ApiKeyMissing)- );- }-- /// TAURI-RUST-HCK — the single-source `is_api_key_unset_message` matcher- /// (consumed by the cron scheduler's halt-on-first classifier) must match- /// the VERBATIM wording emitted by the inference credential guard- /// (`credential_for_request`), so a wording drift fails CI instead of- /// silently re-opening the cron flood. It must NOT match a present-but-- /// rejected key (401 "Invalid API key") nor an ordinary provider error.- #[test]- fn is_api_key_unset_message_matches_verbatim_credential_guard_wording() {- assert!(is_api_key_unset_message(- "openrouter API key not set. Configure via the web UI or set the appropriate env var."- ));- assert!(is_api_key_unset_message(- "Cohere embed API error (401 Unauthorized): {\"message\":\"no api key supplied\"}"- ));- assert!(!is_api_key_unset_message(- "OpenAI API error (401 Unauthorized): invalid_api_key"- ));- assert!(!is_api_key_unset_message(- "OpenHuman API error (500 Internal Server Error): {\"error\":\"Internal server error\"}"- ));- }-- /// Guard against over-suppression: a genuine BYO-key auth failure- /// (wrong/expired key the upstream rejected) is an actionable bug- /// shape and MUST still reach Sentry (stay `None`), not get demoted by- /// the new "no api key is configured" substring.- #[test]- fn does_not_classify_invalid_api_key_401_as_missing() {- assert_eq!(- expected_error_kind("OpenAI API error (401 Unauthorized): invalid_api_key"),- None- );- }-- /// Task B (issue #2898): prove the canonical 429 error message produced by- /// the embedding clients is already classified as `TransientUpstreamHttp`- /// so Sentry events are suppressed even without backoff.- ///- /// The `is_transient_upstream_http_message` matcher checks for- /// `"api error (429 "` (case-insensitive), which is present in both the- /// OpenAI and Cohere canonical error shapes.- #[test]- fn embedding_429_classifies_as_transient_upstream_http() {- // OpenAI/Voyage canonical shape (openai.rs emit site).- let msg = "Embedding API error (429 Too Many Requests): Rate limit exceeded.";- assert_eq!(- expected_error_kind(msg),- Some(ExpectedErrorKind::TransientUpstreamHttp),- "OpenAI 429 must classify as TransientUpstreamHttp: {msg}"- );-- // Cohere canonical shape (cohere.rs emit site).- let cohere_msg = "Cohere embed API error (429 Too Many Requests): rate limit exceeded.";- assert_eq!(- expected_error_kind(cohere_msg),- Some(ExpectedErrorKind::TransientUpstreamHttp),- "Cohere 429 must classify as TransientUpstreamHttp: {cohere_msg}"- );-- // After-cap bail shape from the retry loop (openai.rs).- let cap_msg =- "Embedding API error (429 Too Many Requests): rate limit exceeded after 3 retries";- assert_eq!(- expected_error_kind(cap_msg),- Some(ExpectedErrorKind::TransientUpstreamHttp),- "retry-cap bail message must classify as TransientUpstreamHttp: {cap_msg}"- );-- // After-cap bail shape from the retry loop (cohere.rs).- let cohere_cap_msg =- "Cohere embed API error (429 Too Many Requests): rate limit exceeded after 3 retries";- assert_eq!(- expected_error_kind(cohere_cap_msg),- Some(ExpectedErrorKind::TransientUpstreamHttp),- "Cohere retry-cap bail message must classify as TransientUpstreamHttp: {cohere_cap_msg}"- );- }-- #[test]- fn classifies_embedding_html_403_edge_block_as_upstream_edge_block() {- // TAURI-RUST-8S3: edge/CDN/WAF or regional 403 block in front of- // api.cohere.com — the body is a generic HTML gateway page, not- // Cohere's JSON error envelope. Endpoint correct, key sent, no local- // lever → demote.- let cohere_html_403 = "Cohere embed API error (403 Forbidden): <!doctype html>\- <html><head><title>403</title></head><body>403 Forbidden</body></html>";- assert_eq!(- expected_error_kind(cohere_html_403),- Some(ExpectedErrorKind::UpstreamEdgeBlock),- "HTML 403 gateway page from an embed call must classify as UpstreamEdgeBlock: {cohere_html_403}"- );-- // Generic embed shape (openai/voyage/custom embed path) fronted by the- // same edge tier — also demoted (matcher is not pinned to one provider).- let openai_html_403 =- "Embedding API error (403 Forbidden): <!DOCTYPE html><title>403 Forbidden</title>";- assert_eq!(- expected_error_kind(openai_html_403),- Some(ExpectedErrorKind::UpstreamEdgeBlock),- "generic embed HTML 403 must classify as UpstreamEdgeBlock: {openai_html_403}"- );- }-- #[test]- fn does_not_classify_embedding_json_403_as_edge_block() {- // A JSON 403 envelope means the provider's app answered with a- // structured, actionable error (bad key, blocked org) — must stay in- // Sentry. The discrimination guard for TAURI-RUST-8S3.- let cohere_json_403 =- r#"Cohere embed API error (403 Forbidden): {"message": "invalid api token"}"#;- assert_eq!(- expected_error_kind(cohere_json_403),- None,- "JSON 403 envelope must NOT be demoted — stays actionable: {cohere_json_403}"- );-- // A non-embed HTML 403 from some unrelated path must not be silenced by- // this embed-scoped matcher.- let non_embed_html_403 =- "page fetch failed (403 Forbidden): <!doctype html><title>403</title>";- assert_eq!(- expected_error_kind(non_embed_html_403),- None,- "non-embed HTML 403 must not match the embed edge-block matcher: {non_embed_html_403}"- );- }-- #[test]- fn report_error_or_expected_demotes_embedding_html_403_edge_block() {- // Drive the full demote path (`report_error_or_expected` →- // `report_expected_message`'s `UpstreamEdgeBlock` arm) so the added- // logging branch is exercised, not just the classifier. The HTML 403- // edge-block body must take the demoted `warn!` arm and must NOT fall- // through to the hard `report_error_message` capture path.- let cohere_html_403 = anyhow::anyhow!(- "Cohere embed API error (403 Forbidden): <!doctype html>\- <html><head><title>403</title></head><body>403 Forbidden</body></html>"- );- // Confirm the classifier routes it to the demoted arm…- assert_eq!(- expected_error_kind(&format!("{cohere_html_403:#}")),- Some(ExpectedErrorKind::UpstreamEdgeBlock),- "edge-block 403 must classify so report_error_or_expected demotes it"- );- // …then actually invoke the report path to cover the logging arm.- report_error_or_expected(&cohere_html_403, "embeddings", "embed", &[]);-- // Companion: a JSON 403 envelope is actionable — it must NOT be demoted- // (classifier returns None, so the hard report path is taken instead).- let cohere_json_403 =- r#"Cohere embed API error (403 Forbidden): {"message": "invalid api token"}"#;- assert_eq!(- expected_error_kind(cohere_json_403),- None,- "JSON 403 envelope must stay actionable — not routed to the demote arm"- );- }-- #[test]- fn does_not_classify_unrelated_is_not_configured_messages() {- assert_eq!(- expected_error_kind("workspace path is not configured for this user"),- None- );- assert_eq!(- expected_error_kind("provider 'voyage' is not configured in settings"),- None- );- }-- #[test]- fn classifies_ollama_user_config_rejections() {- // TAURI-RUST-XS (~376 events): user pointed embedder at a chat /- // vision model id, sometimes with a temperature suffix like `@0.7`- // that Ollama parses as malformed.- for raw in [- // Canonical XS wire shape from- // `OllamaEmbedding::embed` non-2xx path on a 400 Bad Request.- r#"ollama embed failed with status 400 Bad Request: {"error":"invalid model name"}"#,- // Same shape with a temperature-suffix model id the user pasted- // into Settings → Embeddings → Ollama.- r#"ollama embed failed with status 400 Bad Request: {"error":"invalid model name: qwen3-vl:[email protected]"}"#,- // OPENHUMAN-TAURI-MA — model not pulled (404 Not Found).- r#"ollama embed failed with status 404 Not Found: {"error":"model \"bge-m3\" not found, try pulling it first"}"#,- // OPENHUMAN-TAURI-KM — same shape, different model id + `:latest` tag.- r#"ollama embed failed with status 404 Not Found: {"error":"model \"nomic-embed-text:latest\" not found, try pulling it first"}"#,- // OPENHUMAN-TAURI-GX — daemon-unreachable opt-in state.- "ollama embeddings opted-in but daemon unreachable at http://localhost:11434; falling back to cloud embeddings for this session",- // TAURI-RUST-3X — 501-status model-does-not-support-embeddings.- r#"ollama embed failed with status 501 Not Implemented: {"error":"this model does not support embeddings"}"#,- // TAURI-RUST-8WA — 501-status daemon started without embed support.- // Exact wire body so a narrow-back to "this model …" fails CI.- r#"ollama embed failed with status 501 Not Implemented: {"error":"This server does not support embeddings. Start it with `--embeddings`"}"#,- // TAURI-RUST-3E — 401 unauthorized embed (auth required at ollama endpoint).- r#"ollama embed failed with status 401 Unauthorized: {"error": "unauthorized"}"#,- ] {- assert_eq!(- expected_error_kind(raw),- Some(ExpectedErrorKind::ProviderUserState),- "should classify Ollama user-config rejection: {raw}"- );- }- }#[test]fn classifies_embedding_backend_auth_failure() {diff --git a/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs b/crates/openhuman-core/src/integrations/composio/schemas/definitions.rsindex 6f25cd1017..125a757cb8 100644--- a/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs+++ b/crates/openhuman-core/src/integrations/composio/schemas/definitions.rs@@ -5,7 +5,7 @@use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-pub fn schemas(function: &str) -> ControllerSchema {+pub(super) fn schemas(function: &str) -> ControllerSchema {match function {"list_toolkits" => ControllerSchema {namespace: "composio",diff --git a/crates/openhuman-core/src/threads/schemas/handlers.rs b/crates/openhuman-core/src/threads/schemas/handlers.rsnew file mode 100644index 0000000000..1c1e58a23f--- /dev/null+++ b/crates/openhuman-core/src/threads/schemas/handlers.rs@@ -0,0 +1,231 @@+//! Thin JSON-RPC handlers that parse params and delegate to [`super::super::ops`].++use serde::de::DeserializeOwned;+use serde_json::{Map, Value};++use crate::agent::task_board::{TaskBoard, TaskBoardCard, TaskBoardStore};+use crate::core::all::ControllerFuture;+use crate::memory::{+ AppendConversationMessageRequest, ConversationMessagesRequest, CreateConversationThreadRequest,+ DeleteConversationThreadRequest, EmptyRequest, GenerateConversationThreadTitleRequest,+ UpdateConversationMessageRequest, UpdateConversationThreadLabelsRequest,+ UpdateConversationThreadTitleRequest, UpsertConversationThreadRequest,+};+use crate::threads::turn_state::{+ ClearTurnStateRequest, GetTurnStateForRequestRequest, GetTurnStateRequest,+};++use super::super::ops;++pub(super) fn handle_list(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(ops::threads_list(EmptyRequest {}).await?) })+}++pub(super) fn handle_upsert(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<UpsertConversationThreadRequest>(params)?;+ to_json(ops::thread_upsert(p).await?)+ })+}++pub(super) fn handle_create_new(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<CreateConversationThreadRequest>(params)?;+ to_json(ops::thread_create_new(p).await?)+ })+}++pub(super) fn handle_messages_list(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ConversationMessagesRequest>(params)?;+ to_json(ops::messages_list(p).await?)+ })+}++pub(super) fn handle_message_append(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<AppendConversationMessageRequest>(params)?;+ to_json(ops::message_append(p).await?)+ })+}++pub(super) fn handle_generate_title(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<GenerateConversationThreadTitleRequest>(params)?;+ to_json(ops::thread_generate_title(p).await?)+ })+}++pub(super) fn handle_update_labels(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<UpdateConversationThreadLabelsRequest>(params)?;+ to_json(ops::thread_update_labels(p).await?)+ })+}++pub(super) fn handle_update_title(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<UpdateConversationThreadTitleRequest>(params)?;+ to_json(ops::thread_update_title(p).await?)+ })+}++pub(super) fn handle_message_update(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<UpdateConversationMessageRequest>(params)?;+ to_json(ops::message_update(p).await?)+ })+}++pub(super) fn handle_delete(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<DeleteConversationThreadRequest>(params)?;+ to_json(ops::thread_delete(p).await?)+ })+}++pub(super) fn handle_purge(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(ops::threads_purge(EmptyRequest {}).await?) })+}++pub(super) fn handle_turn_state_get(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<GetTurnStateRequest>(params)?;+ to_json(ops::turn_state_get(p).await?)+ })+}++pub(super) fn handle_turn_state_list(_params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move { to_json(ops::turn_state_list(EmptyRequest {}).await?) })+}++pub(super) fn handle_turn_state_history(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<GetTurnStateRequest>(params)?;+ to_json(ops::turn_state_history(p).await?)+ })+}++pub(super) fn handle_turn_state_get_turn(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<GetTurnStateForRequestRequest>(params)?;+ to_json(ops::turn_state_get_turn(p).await?)+ })+}++pub(super) fn handle_turn_state_clear(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ClearTurnStateRequest>(params)?;+ to_json(ops::turn_state_clear(p).await?)+ })+}++#[derive(serde::Deserialize)]+struct TaskBoardGetParams {+ thread_id: String,+}++#[derive(serde::Deserialize)]+struct TaskBoardPutParams {+ thread_id: String,+ cards: Vec<TaskBoardCard>,+}++pub(super) fn handle_task_board_get(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<TaskBoardGetParams>(params)?;+ let thread_id = p.thread_id.trim().to_string();+ tracing::debug!(thread_id = %thread_id, "[rpc][task_board] get entry");+ let config = crate::config::Config::load_or_init().await.map_err(|e| {+ tracing::debug!(+ thread_id = %thread_id,+ error = %e,+ "[rpc][task_board] get load_config_error"+ );+ format!("load config: {e}")+ })?;+ tracing::trace!(thread_id = %thread_id, "[rpc][task_board] get loading_board");+ let board = crate::agent::task_board::board_for_thread(&config.workspace_dir, &thread_id)+ .await+ .map_err(|e| {+ tracing::debug!(+ thread_id = %thread_id,+ error = %e,+ "[rpc][task_board] get board_error"+ );+ e+ })?;+ tracing::debug!(+ thread_id = %thread_id,+ card_count = board.cards.len(),+ "[rpc][task_board] get exit"+ );+ Ok(serde_json::json!({ "taskBoard": board }))+ })+}++pub(super) fn handle_task_board_put(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<TaskBoardPutParams>(params)?;+ let thread_id = p.thread_id.trim().to_string();+ tracing::debug!(+ thread_id = %thread_id,+ card_count = p.cards.len(),+ "[rpc][task_board] put entry"+ );+ let config = crate::config::Config::load_or_init().await.map_err(|e| {+ tracing::debug!(+ thread_id = %thread_id,+ error = %e,+ "[rpc][task_board] put load_config_error"+ );+ format!("load config: {e}")+ })?;+ let board = TaskBoard {+ thread_id: thread_id.clone(),+ cards: p.cards,+ updated_at: chrono::Utc::now().to_rfc3339(),+ };+ let saved = TaskBoardStore::new(config.workspace_dir)+ .put(board)+ .await+ .map_err(|e| {+ tracing::debug!(+ thread_id = %thread_id,+ error = %e,+ "[rpc][task_board] put store_error"+ );+ e+ })?;+ tracing::debug!(+ thread_id = %thread_id,+ card_count = saved.cards.len(),+ "[rpc][task_board] put exit"+ );+ Ok(serde_json::json!({ "taskBoard": saved }))+ })+}++pub(super) fn handle_token_usage(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ops::ThreadTokenUsageRequest>(params)?;+ to_json(ops::token_usage(p).await?)+ })+}++pub(super) fn handle_transcript_get(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = parse::<ops::TranscriptGetRequest>(params)?;+ to_json(ops::transcript_get(p).await?)+ })+}++// ── Helpers ──────────────────────────────────────────────────────────++fn parse<T: DeserializeOwned>(params: Map<String, Value>) -> Result<T, String> {+ serde_json::from_value(Value::Object(params)).map_err(|e| format!("invalid params: {e}"))+}++fn to_json<T: serde::Serialize>(outcome: crate::rpc::RpcOutcome<T>) -> Result<Value, String> {+ outcome.into_cli_compatible_json()+}diff --git a/crates/openhuman-core/src/web_chat/ops_part_01.rs b/crates/openhuman-core/src/web_chat/ops_part_01.rsdeleted file mode 100644index 4a0cf0cce4..0000000000--- a/crates/openhuman-core/src/web_chat/ops_part_01.rs+++ /dev/null@@ -1,429 +0,0 @@-use std::collections::HashMap;-use std::time::{Duration, Instant};--use once_cell::sync::Lazy;-use serde_json::{json, Value};-use tokio::sync::Mutex;-use tokio_util::sync::CancellationToken;-use uuid::Uuid;--use crate::core::events::DomainEvent;-use crate::core::socketio::WebChannelEvent;-use crate::security::prompt_injection::{- enforce_prompt_input, PromptEnforcementAction, PromptEnforcementContext,-};-use crate::rpc::RpcOutcome;--use super::event_bus::publish_web_channel_event;-use super::run_task::run_chat_task;-use super::types::{ChatRequestMetadata, InFlightEntry, ParallelEntry, SessionEntry};-use super::web_errors::classify_inference_error;--pub(crate) static THREAD_SESSIONS: Lazy<Mutex<HashMap<String, SessionEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));--/// A recorded budget-exhausted signal: when it happened, and which provider-/// binding it happened on. The binding scopes the signal so a managed-/// out-of-credits error never mislabels a later empty turn the user has-/// re-routed to a different provider (local / BYO), whose balance is unrelated.-#[derive(Debug, Clone)]-struct BudgetSignal {- provider_binding: String,- at: Instant,-}--/// Per-thread "recent budget-exhausted" signal (issue #3386).-///-/// Set when a turn terminates with an inference budget-exhausted error; read by-/// a *later* turn on the same thread whose provider returned an empty 200. The-/// managed route closes the SSE cleanly under credit exhaustion (the response-/// already flushed HTTP 200, so there is no error frame and no inline budget-/// marker — `OpenHumanBilling` carries only `charged_amount_usd`). Without this-/// correlator such a budget-caused empty turn surfaces as the generic "empty-/// response" copy instead of the actionable out-of-credits copy.-///-/// The signal is scoped to the provider binding it was recorded on: budget is a-/// per-provider fact, so a managed-route exhaustion must not reclassify an empty-/// turn the thread has since re-routed to a local / BYO provider.-///-/// Kept in a sibling map rather than on `SessionEntry` so the signal survives-/// the de-poison session drop (an empty turn is not poisoned, but cold-boot-/// reseeds would otherwise be the wrong lifetime to hang this on).-static THREAD_BUDGET_SIGNALS: Lazy<Mutex<HashMap<String, BudgetSignal>>> =- Lazy::new(|| Mutex::new(HashMap::new()));--/// How long a recorded budget-exhausted signal stays eligible to reclassify a-/// later empty turn on the same thread. Five minutes: long enough to bridge a-/// user retry after the first out-of-credits turn, short enough that a genuine-/// empty response well after the fact isn't mislabeled. A successful turn clears-/// the signal regardless (the balance is evidently usable again). See #3386.-const BUDGET_SIGNAL_TTL: Duration = Duration::from_secs(5 * 60);--/// Default wall-clock backstop for a single web chat turn, in seconds.-///-/// This is the OUTER safety net (issue #4746). The primary, root-cause guard is-/// the harness policy's `max_wall_clock_ms` (`tinyagents::run_policy_for`,-/// default 600s), which interrupts a hung/slow model or tool/sub-agent call-/// mid-flight and returns a proper `Timeout` → `chat_error`. This channel-level-/// backstop sits ABOVE that (900s) and only fires if a turn wedges OUTSIDE the-/// harness run entirely (e.g. session assembly / persistence plumbing), so the-/// client still always gets a terminal event instead of an empty reply / an-/// endless `inference_heartbeat` stream. Deliberately generous — a hang-/// backstop, not a UX deadline. Override via `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`;-/// set it to `0` to disable the backstop.-const DEFAULT_WEB_TURN_TIMEOUT_SECS: u64 = 900;--/// Resolve the per-turn wall-clock backstop. Returns `None` when disabled-/// (env `OPENHUMAN_WEB_TURN_TIMEOUT_SECS=0`).-fn web_turn_deadline() -> Option<Duration> {- let secs = std::env::var("OPENHUMAN_WEB_TURN_TIMEOUT_SECS")- .ok()- .and_then(|v| v.trim().parse::<u64>().ok())- .unwrap_or(DEFAULT_WEB_TURN_TIMEOUT_SECS);- (secs > 0).then(|| Duration::from_secs(secs))-}--/// Drive a chat-turn future under the wall-clock backstop.-///-/// On elapse the inner future is dropped (cooperative teardown at its next-/// await point) and a synthetic `turn_timeout` error is returned, so the-/// caller's existing `chat_error` emission path fires. This is the outermost-/// guarantee that a wedged turn always ends in a terminal event rather than an-/// empty reply / an endless `inference_heartbeat` stream (issue #4746).-async fn drive_turn_with_deadline<F>(- deadline: Option<Duration>,- fut: F,-) -> Result<super::types::WebChatTaskResult, String>-where- F: std::future::Future<Output = Result<super::types::WebChatTaskResult, String>>,-{- match deadline {- Some(d) => match tokio::time::timeout(d, fut).await {- Ok(res) => res,- Err(_elapsed) => {- log::warn!(- "[web-channel] turn wall-clock backstop fired after {}s with no terminal event; \- emitting graceful turn_timeout chat_error (issue #4746)",- d.as_secs()- );- Err(super::web_errors::turn_timeout_error_message(d.as_secs()))- }- },- None => fut.await,- }-}--/// Run a chat-turn future under the two standard web-channel guards, inside the-/// shared origin + approval-context scope: the cooperative cancel token-/// (interrupt/cancel paths tear the turn down at its next await point) and the-/// wall-clock backstop ([`drive_turn_with_deadline`]).-///-/// Returns `None` when the turn was cancelled cooperatively before producing a-/// result — the cancelling side already emitted the user-facing `chat_error`,-/// so the caller just unwinds quietly. Otherwise `Some(res)` carries the turn's-/// `Result`. Extracted so `start_chat` and `spawn_parallel_turn` share one copy-/// of this wiring and can't drift apart (issue #4746 review); the only per-site-/// differences are the `fork` flag and run-queue handle passed to-/// `run_chat_task` when building `fut`.-async fn run_turn_under_cancel_and_deadline<F>(- cancel_token: CancellationToken,- origin: crate::agent::turn_origin::AgentTurnOrigin,- approval_ctx: crate::security::approval::ApprovalChatContext,- fut: F,-) -> Option<Result<super::types::WebChatTaskResult, String>>-where- F: std::future::Future<Output = Result<super::types::WebChatTaskResult, String>>,-{- tokio::select! {- biased;- _ = cancel_token.cancelled() => None,- res = drive_turn_with_deadline(- web_turn_deadline(),- crate::agent::turn_origin::with_origin(- origin,- crate::security::approval::APPROVAL_CHAT_CONTEXT.scope(approval_ctx, fut),- ),- ) => Some(res),- }-}--/// Reason a terminal `run_chat_task` error should be kept OUT of Sentry, or-/// `None` when it is a genuine defect that must page.-///-/// A suppressed case is a deterministic, user-surfaced, retryable agent-loop-/// outcome — a terminal `chat_error` already reaches the client, so a Sentry-/// event is pure noise (same tier as `MaxIterationsExceeded` /-/// `EmptyProviderResponse`, which are demoted the same way):-///-/// - the max-iteration cap (`is_max_iterations_error`), and-/// - the **outer** web-turn wall-clock backstop (`is_outer_backstop_timeout`,-/// issue #4746) — the turn wedged outside the harness and produced no-/// terminal event, so without this arm every such turn would emit a spurious-/// Sentry event, contradicting the graceful `turn_timeout` framing.-///-/// **Not suppressed: the harness's own `Timeout` (#5804).** This arm used to-/// cover both, via `is_turn_timeout_error`, because the two are hard to tell-/// apart once stringified. They are not the same event. The outer backstop-/// fires with *nothing in flight*; the harness `Timeout` fires while bounding-/// a real model or tool call, which means the run spent its budget doing work-/// — and every result that work produced is discarded along with the turn. A-/// turn that lost eighteen sub-agents' worth of accumulated work was reported-/// here as `suppressed Sentry emission for turn wall-clock backstop` and-/// reached telemetry as nothing at all, which is why the defect survived. See-/// [`is_outer_backstop_timeout`](super::web_errors::is_outer_backstop_timeout)-/// for the structural argument.-///-/// The user-facing classification is deliberately untouched: both still render-/// the graceful `turn_timeout` copy via `is_turn_timeout_error`. Only the-/// telemetry decision splits.-///-/// Kept as a pure predicate over the already-formatted error string so the-/// suppression policy is unit-testable without a Sentry harness.-pub(crate) fn sentry_suppression_reason(detailed: &str) -> Option<&'static str> {- if crate::agent::error::is_max_iterations_error(detailed) {- Some("max-iteration cap")- } else if super::web_errors::is_outer_backstop_timeout(detailed) {- Some("turn wall-clock backstop (no terminal event)")- } else {- None- }-}--/// Which wall-clock bound a reported timeout hit, as a Sentry tag value.-///-/// Only meaningful once [`sentry_suppression_reason`] has decided to report —-/// i.e. for a harness `Timeout`, never for the suppressed outer backstop. The-/// crate names the bound in the message (`RUN_BOUND_LABEL` vs-/// `PER_CALL_BOUND_LABEL`), and the two are different triage paths: a run that-/// spent its whole budget doing real work is a capacity/planning problem, while-/// one call that blew a per-call ceiling is a wedged provider. Emitting them-/// under one tag would rebuild, in the dashboard, exactly the conflation this-/// change removed from the code (#5804).-///-/// Pure over the formatted error string, for the same reason its neighbour is.-pub(crate) fn timeout_bound_tag(detailed: &str) -> &'static str {- if detailed.contains("per-model-call ceiling") {- "per_model_call"- } else if detailed.contains("remaining wall-clock budget") {- "run_remaining"- } else if super::web_errors::is_turn_timeout_error(detailed) {- "unclassified_timeout"- } else {- "none"- }-}--/// What the budget-correlator should do with a terminated turn (#3386).-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub(super) enum BudgetCorrelation {- /// The terminal error is itself an inference budget-exhausted error:- /// record the signal and surface the budget copy.- BudgetExhausted,- /// An empty provider response coincided with a fresh same-thread budget- /// signal: surface the budget copy in place of the "empty response" copy.- UpgradeEmptyToBudget,- /// No budget correlation — pass the error through unchanged.- PassThrough,-}--/// Pure decision for the budget-correlator, split out so the branch matrix is-/// unit-testable without a clock or the full `run_chat_task` frame. The async-/// helpers below supply `has_fresh_signal`.-pub(super) fn classify_budget_correlation(- is_budget_error: bool,- is_empty_response: bool,- has_fresh_signal: bool,-) -> BudgetCorrelation {- if is_budget_error {- BudgetCorrelation::BudgetExhausted- } else if is_empty_response && has_fresh_signal {- BudgetCorrelation::UpgradeEmptyToBudget- } else {- BudgetCorrelation::PassThrough- }-}--/// Pure freshness predicate (age vs TTL), split out for clock-free testing.-fn budget_signal_is_fresh(age: Duration, ttl: Duration) -> bool {- age <= ttl-}--/// Drop every expired entry from the map, not just the one being queried.-/// Without this, a thread that hits budget exhaustion and then never retries or-/// succeeds would leak its entry for the process lifetime. Called on the write-/// path so each new budget event sweeps the map.-fn prune_stale_budget_signals(signals: &mut HashMap<String, BudgetSignal>) {- signals.retain(|_, sig| budget_signal_is_fresh(sig.at.elapsed(), BUDGET_SIGNAL_TTL));-}--/// Record that this thread just hit an inference budget-exhausted error on the-/// given provider binding.-pub(super) async fn record_budget_signal(thread_id: &str, provider_binding: &str) {- let mut signals = THREAD_BUDGET_SIGNALS.lock().await;- prune_stale_budget_signals(&mut signals);- signals.insert(- key_for(thread_id),- BudgetSignal {- provider_binding: provider_binding.to_string(),- at: Instant::now(),- },- );-}--/// Clear any recorded budget signal for this thread — called on a successful-/// turn, where the balance is evidently usable again.-pub(super) async fn clear_budget_signal(thread_id: &str) {- let mut signals = THREAD_BUDGET_SIGNALS.lock().await;- signals.remove(&key_for(thread_id));-}--/// Whether this thread has a budget signal recorded within `BUDGET_SIGNAL_TTL`-/// **on the same provider binding** as the current turn. A binding mismatch or-/// an expired entry evicts it and reads as not-fresh, so a re-routed turn never-/// inherits the prior provider's exhaustion.-pub(super) async fn has_fresh_budget_signal(thread_id: &str, provider_binding: &str) -> bool {- let mut signals = THREAD_BUDGET_SIGNALS.lock().await;- let key = key_for(thread_id);- match signals.get(&key) {- Some(sig)- if sig.provider_binding == provider_binding- && budget_signal_is_fresh(sig.at.elapsed(), BUDGET_SIGNAL_TTL) =>- {- true- }- Some(_) => {- signals.remove(&key);- false- }- None => false,- }-}--/// Test-only seeder: record a budget signal on `provider_binding` aged `age`-/// into the past so expiry can be exercised without sleeping.-#[cfg(test)]-pub(super) async fn record_budget_signal_aged(- thread_id: &str,- provider_binding: &str,- age: Duration,-) {- let mut signals = THREAD_BUDGET_SIGNALS.lock().await;- let when = Instant::now().checked_sub(age).unwrap_or_else(Instant::now);- signals.insert(- key_for(thread_id),- BudgetSignal {- provider_binding: provider_binding.to_string(),- at: when,- },- );-}--pub(super) static IN_FLIGHT: Lazy<Mutex<HashMap<String, InFlightEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));--/// Parallel (forked) turns, keyed by `request_id`. A separate lane from-/// `IN_FLIGHT` (which holds one primary, interrupt-able turn per thread) so any-/// number of concurrent `QueueMode::Parallel` turns can run on the same thread-/// without touching interrupt/steer/queue semantics. See `QueueMode::Parallel`.-pub(super) static PARALLEL_IN_FLIGHT: Lazy<Mutex<HashMap<String, ParallelEntry>>> =- Lazy::new(|| Mutex::new(HashMap::new()));--#[cfg(any(test, debug_assertions))]-pub(super) static TEST_FORCED_RUN_CHAT_TASK_ERROR: Lazy<Mutex<Option<String>>> =- Lazy::new(|| Mutex::new(None));--/// Test hook handles: when set, `run_chat_task` parks on a long sleep instead-/// of doing real work, keeping the turn in-flight so concurrency / cancellation-/// can be observed. `started` is flipped once the turn has actually parked (so-/// a test can cancel only after the turn future is live), and a `Drop` guard-/// inside the parked future flips `dropped`, proving cooperative cancellation-/// tears the turn future down (vs. a hard `abort()` that never runs the Drop).-#[cfg(any(test, debug_assertions))]-#[derive(Clone)]-pub struct TestRunChatTaskBlock {- pub started: std::sync::Arc<std::sync::atomic::AtomicBool>,- pub dropped: std::sync::Arc<std::sync::atomic::AtomicBool>,-}--#[cfg(any(test, debug_assertions))]-pub(super) static TEST_RUN_CHAT_TASK_BLOCK: Lazy<Mutex<Option<TestRunChatTaskBlock>>> =- Lazy::new(|| Mutex::new(None));--/// Process-wide lock serializing every test that drives the global-/// `run_chat_task` test hooks (`set_test_run_chat_task_block`,-/// `set_test_forced_run_chat_task_error`) or the `OPENHUMAN_WEB_TURN_TIMEOUT_SECS`-/// turn-timeout override.-///-/// All of those toggles are process-global, so a `start_chat` / `run_chat_task`-/// call in ANY test — not just those in `web_tests.rs` — can observe another-/// test's forced block/error/timeout unless every such test holds this one lock-/// for its whole body. It lives here at the hook boundary (rather than as a-/// file-local lock in `web_tests.rs`) precisely so tests in other modules that-/// exercise `start_chat`/`run_chat_task` can serialize against the same lock-/// (CodeRabbit review on #4746).-#[cfg(any(test, debug_assertions))]-pub static RUN_CHAT_TASK_TEST_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));--/// Cooperatively cancel an in-flight turn, with a hard `abort()` backstop.-///-/// Cancelling the token makes the turn's `tokio::select!` arm fire, dropping-/// the turn future at its next await point (cancelling the in-flight LLM-/// request and releasing locks cleanly). The detached backstop hard-aborts the-/// task only if it has not finished unwinding within a short grace period, so a-/// wedged turn can never leak. Returns the cancelled turn's request id.-fn cancel_in_flight_gracefully(entry: InFlightEntry) -> String {- let request_id = entry.request_id.clone();- entry.cancel_token.cancel();- let mut handle = entry.handle;- tokio::spawn(async move {- tokio::select! {- _ = &mut handle => {}- _ = tokio::time::sleep(Duration::from_secs(5)) => {- log::warn!(- "[web-channel] cooperative cancel did not finish within grace period — hard-aborting backstop"- );- handle.abort();- }- }- });- request_id-}--pub(crate) fn key_for(thread_id: &str) -> String {- thread_id.to_string()-}--pub(crate) fn event_session_id_for(client_id: &str, thread_id: &str) -> String {- json!({- "client_id": client_id,- "thread_id": thread_id,- })- .to_string()-}--fn prompt_guard_user_message(action: PromptEnforcementAction) -> &'static str {- match action {- PromptEnforcementAction::Allow => "Message accepted.",- PromptEnforcementAction::Blocked => {- "Your message was blocked by a security policy. Please rephrase and remove instruction-override or secret-exfiltration requests."- }- PromptEnforcementAction::ReviewBlocked => {- "Your message was flagged for security review and was not processed. Please rephrase the request in a direct, task-focused way."- }- }-}--#[cfg(any(test, debug_assertions))]-pub async fn set_test_forced_run_chat_task_error(message: Option<&str>) {- let mut slot = TEST_FORCED_RUN_CHAT_TASK_ERROR.lock().await;- *slot = message.map(str::to_string);-}--/// Test hook: when `block` is `Some`, the next `run_chat_task` invocations park-/// on a long sleep (staying in-flight), flip `started` once parked, and flip-/// `dropped` when their future is torn down. Pass `None` to clear.-#[cfg(any(test, debug_assertions))]-pub async fn set_test_run_chat_task_block(block: Option<TestRunChatTaskBlock>) {- let mut slot = TEST_RUN_CHAT_TASK_BLOCK.lock().await;- *slot = block;-}diff --git a/crates/openhuman-core/src/web_chat/ops_part_02.rs b/crates/openhuman-core/src/web_chat/ops_part_02.rsdeleted file mode 100644index bcb8ed856f..0000000000--- a/crates/openhuman-core/src/web_chat/ops_part_02.rs+++ /dev/null@@ -1,531 +0,0 @@--pub async fn start_chat(- client_id: &str,- thread_id: &str,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- profile_id: Option<String>,- locale: Option<String>,- queue_mode: Option<String>,- metadata: ChatRequestMetadata,-) -> Result<String, String> {- let client_id = client_id.trim().to_string();- let thread_id = thread_id.trim().to_string();- let message = message.trim().to_string();-- if client_id.is_empty() {- return Err("client_id is required".to_string());- }- if thread_id.is_empty() {- return Err("thread_id is required".to_string());- }- if message.is_empty() {- return Err("message is required".to_string());- }-- // [pdf/image-attach fix] Process attachments at ingress, BEFORE the message is- // injection-scanned, persisted to history/JSONL, or auto-saved to the memory- // store. Otherwise a multi-MB base64 data URI floods every upstream stage- // (N-chunk embed → Voyage 400, cross-thread index) and stalls the turn.- // [FILE:data:…] → [FILE-EXTRACTED]text (or [FILE-ATTACHED] placeholder)- // [IMAGE:data:…] → [Image: … #att:<id>] placeholder + out-of-band stash- // Images are rehydrated to a data URI at provider dispatch for vision-capable- // models only.- let mut message = if message.contains("[FILE:") || message.contains("[IMAGE:") {- let before_chars = message.chars().count();- log::debug!(- "[web-channel][ingress] preprocessing attachment markers thread_id={} client_id={} chars={}",- thread_id,- client_id,- before_chars- );- // Fail CLOSED on a config-load error: process with default limits rather- // 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- {- Ok(cfg) => {- log::debug!(- "[web-channel][ingress] using configured multimodal limits thread_id={}",- thread_id- );- (cfg.multimodal_files, cfg.multimodal)- }- Err(err) => {- log::warn!(- "[web-channel][ingress] config load failed; using default limits (fail-closed) thread_id={} err={err}",- thread_id- );- (- crate::config::MultimodalFileConfig::default(),- crate::config::MultimodalConfig::default(),- )- }- };- let extracted =- crate::agent::multimodal::inline_file_attachments(&message, &file_cfg).await;- let processed =- 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,- before_chars,- processed.chars().count()- );- processed- } else {- message- };-- let request_id = Uuid::new_v4().to_string();- let prompt_decision = enforce_prompt_input(- &message,- PromptEnforcementContext {- source: "web_chat.start_chat",- request_id: Some(&request_id),- user_id: Some(&client_id),- session_id: Some(&thread_id),- },- );- if !matches!(prompt_decision.action, PromptEnforcementAction::Allow) {- log::warn!(- "[web-channel] prompt rejected client_id={} thread_id={} request_id={} action={} score={:.2} reasons={} hash={} chars={}",- client_id,- thread_id,- request_id,- match prompt_decision.action {- PromptEnforcementAction::Allow => "allow",- PromptEnforcementAction::Blocked => "block",- PromptEnforcementAction::ReviewBlocked => "review_blocked",- },- prompt_decision.score,- prompt_decision- .reasons- .iter()- .map(|r| r.code.as_str())- .collect::<Vec<_>>()- .join(","),- prompt_decision.prompt_hash,- prompt_decision.prompt_chars,- );- return Err(prompt_guard_user_message(prompt_decision.action).to_string());- }-- // Chat-native approval: if this thread has a parked approval and the message- // 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)- {- match gate.decide(&request_id, decision) {- Ok(Some(_)) => {- log::info!(- "[web-channel] routed chat reply to approval gate thread_id={} request_id={} decision={}",- thread_id,- request_id,- decision.as_str()- );- return Ok(request_id);- }- Ok(None) => {- log::warn!(- "[web-channel] approval reply targeted a non-pending/already-decided request thread_id={} request_id={} decision={} — dispatching as fresh turn",- thread_id,- request_id,- decision.as_str()- );- }- Err(err) => {- log::warn!(- "[web-channel] failed to route chat reply to approval gate thread_id={} request_id={} decision={} err={}",- thread_id,- request_id,- decision.as_str(),- err- );- }- }- }- }- }-- // Configured `beforeSubmitPrompt` hooks. Deliberately after the- // approval-reply routing above: a bare "yes" answering a parked approval is- // not a prompt the user is submitting to the model, and handing it to a- // prompt hook would let a hook that blocks short messages strand a turn- // waiting for an approval it can no longer receive.- //- // The message here is post-attachment-processing, so a hook sees extracted- // text and placeholders rather than a multi-megabyte data URI on stdin.- match crate::hooks::ops::prompt_submitted(- crate::hooks::context::TurnIdentity {- conversation_id: Some(thread_id.clone()),- ..Default::default()- },- &message,- Vec::new(),- )- .await- {- crate::hooks::PromptVerdict::Submit { additional_context } => {- if let Some(context) = additional_context {- log::debug!(- "[web-channel] beforeSubmitPrompt hook added {} chars of context thread_id={}",- context.chars().count(),- thread_id- );- message = format!("{message}\n\n{context}");- }- }- crate::hooks::PromptVerdict::Block(reason) => {- log::info!(- "[web-channel] prompt blocked by a configured hook thread_id={thread_id}: {reason}"- );- return Err(reason);- }- }-- let map_key = key_for(&thread_id);-- let parsed_mode = match queue_mode.as_deref() {- Some("steer") => crate::agent::harness::run_queue::QueueMode::Steer,- Some("followup") => crate::agent::harness::run_queue::QueueMode::Followup,- Some("collect") => crate::agent::harness::run_queue::QueueMode::Collect,- Some("parallel") => crate::agent::harness::run_queue::QueueMode::Parallel,- _ => crate::agent::harness::run_queue::QueueMode::Interrupt,- };-- // Parallel mode: spawn an independent forked turn that runs alongside any- // in-flight turn for this thread. It does not touch IN_FLIGHT (no- // interrupt/steer/queue) — it lives in its own request-keyed lane.- if matches!(- parsed_mode,- crate::agent::harness::run_queue::QueueMode::Parallel- ) {- log::info!(- "[web-channel] starting PARALLEL forked turn thread_id={} request_id={}",- thread_id,- request_id- );- spawn_parallel_turn(- &client_id,- &thread_id,- request_id.clone(),- &message,- model_override,- temperature,- profile_id,- locale,- metadata,- )- .await;- return Ok(request_id);- }-- // Non-interrupt modes: push into the running turn's queue and return.- if !matches!(- parsed_mode,- crate::agent::harness::run_queue::QueueMode::Interrupt- ) {- let in_flight = IN_FLIGHT.lock().await;- if let Some(existing) = in_flight.get(&map_key) {- let queued_msg = crate::agent::harness::run_queue::QueuedMessage {- text: message.clone(),- mode: parsed_mode,- client_id: client_id.clone(),- thread_id: thread_id.clone(),- queued_at_ms: std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap_or_default()- .as_millis() as u64,- model_override: model_override.clone(),- temperature,- profile_id: profile_id.clone(),- locale: locale.clone(),- };- existing.run_queue.push(queued_msg).await;- let status = existing.run_queue.status().await;- log::info!(- "[web-channel] queued {} message thread_id={} request_id={} queue_depth={}",- parsed_mode,- thread_id,- request_id,- status.total- );- crate::core::bus::BUS.publish(DomainEvent::RunQueueMessageQueued {- thread_id: thread_id.clone(),- mode: parsed_mode.to_string(),- queue_depth: status.total,- });- return Ok(json!({- "queued": true,- "queue_mode": parsed_mode.to_string(),- "client_id": client_id,- "thread_id": thread_id,- "request_id": request_id,- "queue_depth": status.total,- })- .to_string());- }- log::info!(- "[web-channel] no in-flight turn for {} mode thread_id={} — starting fresh",- parsed_mode,- thread_id- );- }-- {- let mut in_flight = IN_FLIGHT.lock().await;-- if let Some(existing) = in_flight.remove(&map_key) {- let cancelled_id = cancel_in_flight_gracefully(existing);- log::info!(- "[web-channel] interrupted in-flight turn thread_id={} cancelled_request_id={}",- thread_id,- cancelled_id- );- crate::core::bus::BUS.publish(DomainEvent::RunQueueInterrupted {- thread_id: thread_id.clone(),- cancelled_request_id: cancelled_id.clone(),- });- publish_web_channel_event(WebChannelEvent {- event: "chat_error".to_string(),- client_id: client_id.clone(),- thread_id: thread_id.clone(),- request_id: cancelled_id,- message: Some("Cancelled by newer request".to_string()),- error_type: Some("cancelled".to_string()),- ..Default::default()- });- }- }-- let turn_run_queue = crate::agent::harness::run_queue::RunQueue::new();- let turn_run_queue_task = turn_run_queue.clone();-- let client_id_task = client_id.clone();- let thread_id_task = thread_id.clone();- let request_id_task = request_id.clone();- let map_key_task = map_key.clone();-- // Cooperative cancellation for this turn. The token lives in the- // `InFlightEntry`; interrupt / cancel paths cancel it to tear the turn- // future down gracefully at the next await point.- let cancel_token = CancellationToken::new();- let task_cancel_token = cancel_token.clone();-- 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 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);- }- }- 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!(- "[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)),- ],- );- }- 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- } else {- Vec::new()- }- } else {- Vec::new()- };- 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);- }- },- ));-- {- let mut in_flight = IN_FLIGHT.lock().await;- in_flight.insert(- map_key,- InFlightEntry {- request_id: request_id.clone(),- handle,- run_queue: turn_run_queue,- cancel_token,- },- );- }-- Ok(request_id)-}--fn dispatch_followups(followups: Vec<crate::agent::harness::run_queue::QueuedMessage>) {- for 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- );- }- },- ));- }-}diff --git a/crates/openhuman-core/src/web_chat/ops_part_03.rs b/crates/openhuman-core/src/web_chat/ops_part_03.rsdeleted file mode 100644index 9a7ec01485..0000000000--- a/crates/openhuman-core/src/web_chat/ops_part_03.rs+++ /dev/null@@ -1,513 +0,0 @@--/// Spawn an independent, forked (`QueueMode::Parallel`) turn. It snapshots the-/// thread's history-at-start (inside `run_chat_task` with `fork = true`), runs-/// concurrently with any other turn on the thread, and on completion delivers-/// its response (append-only) and removes itself from `PARALLEL_IN_FLIGHT`.-/// Emits the same per-`request_id` stream events as a primary turn, so the UI-/// can render it as an interleaved branch.-#[allow(clippy::too_many_arguments)]-async fn spawn_parallel_turn(- client_id: &str,- thread_id: &str,- request_id: String,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- profile_id: Option<String>,- locale: Option<String>,- metadata: ChatRequestMetadata,-) {- let cancel_token = CancellationToken::new();- let task_cancel_token = cancel_token.clone();-- let client_id_task = client_id.to_string();- let thread_id_task = thread_id.to_string();- let request_id_task = request_id.clone();- let user_message = message.to_string();- // Forked turns don't participate in the steer/followup/collect queue, but- // `run_chat_task` requires a queue handle — give each its own.- let run_queue = crate::agent::harness::run_queue::RunQueue::new();-- let handle = tokio::spawn(crate::core::runtime::context::CoreContext::propagate(- async move {- let approval_ctx = crate::security::approval::ApprovalChatContext {- thread_id: thread_id_task.clone(),- client_id: client_id_task.clone(),- };- 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(- &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!(- "parallel run_chat_task failed client_id={} thread_id={} request_id={} error={}",- client_id_task, thread_id_task, request_id_task, err- );- let classified = classify_inference_error(&err);- let classified_type = classified.error_type;-- // A parallel turn runs under the same deadline wrapper as the- // serial one and dies the same way, but this branch reported- // NOTHING to Sentry — not merely the timeouts this PR- // un-suppresses, but every error type, since the parallel path- // was added. So a discarded turn was invisible here even- // before the suppression arm existed, and fixing only- // `start_chat` would have left `QueueMode::Parallel` exactly- // as blind as it was (#5804 review).- //- // Same policy as the serial site, deliberately sharing- // `sentry_suppression_reason` rather than restating it: the- // outer backstop stays suppressed, a harness `Timeout` reports- // with the ceiling that fired.- if let Some(reason) = sentry_suppression_reason(&detailed) {- log::info!(- target: "web_channel",- "[web_channel.spawn_parallel_turn] suppressed Sentry emission for {} \- client_id={} thread_id={} request_id={} error_type={} message={}",- reason,- client_id_task,- thread_id_task,- request_id_task,- classified_type,- detailed- );- } else {- crate::core::observability::report_error_or_expected(- detailed.as_str(),- "web_channel",- "spawn_parallel_turn",- &[- ("channel", "web"),- ("error_type", classified_type),- ("thread_id", thread_id_task.as_str()),- ("request_id", request_id_task.as_str()),- ("queue_mode", "parallel"),- ("timeout_bound", timeout_bound_tag(&detailed)),- ],- );- }-- publish_web_channel_event(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.insert(- request_id,- ParallelEntry {- thread_id: thread_id.to_string(),- handle,- cancel_token,- },- );-}--/// Cooperatively cancel every parallel turn on a thread. Returns the cancelled-/// request ids. Used by the thread-level cancel paths so a cancel/stop also-/// tears down any concurrent forked turns, not just the primary turn.-async fn cancel_parallel_turns_for_thread(thread_id: &str) -> Vec<String> {- let mut cancelled = Vec::new();- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;- let request_ids: Vec<String> = parallel- .iter()- .filter(|(_, entry)| entry.thread_id == thread_id)- .map(|(request_id, _)| request_id.clone())- .collect();- for request_id in request_ids {- if let Some(entry) = parallel.remove(&request_id) {- entry.cancel_token.cancel();- let mut handle = entry.handle;- tokio::spawn(async move {- tokio::select! {- _ = &mut handle => {}- _ = tokio::time::sleep(Duration::from_secs(5)) => {- handle.abort();- }- }- });- cancelled.push(request_id);- }- }- cancelled-}--pub async fn invalidate_thread_sessions(thread_id: &str) {- let mut sessions = THREAD_SESSIONS.lock().await;- let keys_to_remove: Vec<String> = sessions- .keys()- .filter(|k| k.as_str() == thread_id || k.ends_with(&format!("::{thread_id}")))- .cloned()- .collect();- for key in &keys_to_remove {- sessions.remove(key);- }- if !keys_to_remove.is_empty() {- log::debug!(- "[web-channel] invalidated {} cached session(s) for thread_id={}",- keys_to_remove.len(),- thread_id- );- }-}--pub async fn in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = IN_FLIGHT.lock().await;- guard- .iter()- .map(|(k, v)| (k.clone(), v.request_id.clone()))- .collect()-}--/// Test accessor: `(request_id, thread_id)` for every in-flight parallel turn.-#[cfg(any(test, debug_assertions))]-pub async fn parallel_in_flight_entries_for_test() -> Vec<(String, String)> {- let guard = PARALLEL_IN_FLIGHT.lock().await;- guard- .iter()- .map(|(request_id, entry)| (request_id.clone(), entry.thread_id.clone()))- .collect()-}--/// Whether a cancel request should tear down the turn currently in flight for a-/// thread.-///-/// `requested` is the `request_id` the caller is cancelling; `None` means an-/// unscoped stop ("cancel whatever is running", e.g. a Stop button or a session-/// teardown). `in_flight` is the `request_id` currently registered for the-/// thread.-///-/// A *scoped* cancel matches only its own request. This is the fix for #4760: a-/// client that times out on request A and then sends request B — which-/// supersedes A on the same thread — must not have A's late-arriving cancel tear-/// down B. Scoping the cancel to A makes it a no-op once B is in flight, so the-/// newer turn survives instead of being killed at t=0.-pub fn cancel_should_target(requested: Option<&str>, in_flight: &str) -> bool {- match requested {- Some(rid) => rid == in_flight,- None => true,- }-}--/// Cancel a single parallel (forked) turn identified by `request_id`, but only-/// when it belongs to `thread_id`. Returns the cancelled id (as a one-element-/// vec, mirroring [`cancel_parallel_turns_for_thread`]) or empty when no such-/// parallel turn exists. Request-scoped cancel path (#4760).-async fn cancel_parallel_turn_by_request_id(thread_id: &str, request_id: &str) -> Vec<String> {- let mut parallel = PARALLEL_IN_FLIGHT.lock().await;- let matches = parallel- .get(request_id)- .map(|entry| entry.thread_id == thread_id)- .unwrap_or(false);- if !matches {- return Vec::new();- }- if let Some(entry) = parallel.remove(request_id) {- entry.cancel_token.cancel();- let mut handle = entry.handle;- tokio::spawn(async move {- tokio::select! {- _ = &mut handle => {}- _ = tokio::time::sleep(Duration::from_secs(5)) => {- handle.abort();- }- }- });- return vec![request_id.to_string()];- }- Vec::new()-}--/// Cancel whatever turn is currently running on a thread (unscoped stop).-///-/// Back-compat entry point (Stop button / session teardown). For a cancel that-/// must only affect a specific turn — so a stale cancel can't kill a newer turn-/// on the same thread — use [`cancel_chat_scoped`] with the target `request_id`-/// (#4760).-pub async fn cancel_chat(client_id: &str, thread_id: &str) -> Result<Option<String>, String> {- cancel_chat_scoped(client_id, thread_id, None).await-}--/// Cancel the in-flight turn(s) for a thread.-///-/// When `request_id` is `Some`, the cancel is **scoped**: it only tears down the-/// primary turn if that exact request is still running (and only the matching-/// parallel turn), so a stale cancel for a superseded request can't kill the-/// newer turn that replaced it (#4760). When `request_id` is `None`, it stops-/// whatever is running on the thread (primary + every parallel) — the "stop-/// everything" behaviour used by session teardown / a Stop button.-pub async fn cancel_chat_scoped(- client_id: &str,- thread_id: &str,- request_id: Option<&str>,-) -> Result<Option<String>, String> {- let client_id = client_id.trim();- let thread_id = thread_id.trim();-- if client_id.is_empty() {- return Err("client_id is required".to_string());- }- if thread_id.is_empty() {- return Err("thread_id is required".to_string());- }-- let map_key = key_for(thread_id);- let mut removed_request_id: Option<String> = None;-- {- let mut in_flight = IN_FLIGHT.lock().await;- // #4760: only tear down the primary turn when the cancel is unscoped OR- // targets exactly the request that is running. A stale cancel for an- // already-superseded request must be a no-op so the newer turn lives.- let should_cancel_primary = in_flight- .get(&map_key)- .map(|entry| cancel_should_target(request_id, &entry.request_id))- .unwrap_or(false);- if should_cancel_primary {- if let Some(existing) = in_flight.remove(&map_key) {- removed_request_id = Some(cancel_in_flight_gracefully(existing));- }- } else if let Some(rid) = request_id {- log::info!(- "[web-channel] ignoring stale cancel request_id={} for thread_id={} — current in-flight is {:?}; newer turn preserved",- rid,- thread_id,- in_flight.get(&map_key).map(|e| e.request_id.as_str())- );- }- }-- // Also tear down concurrent parallel (forked) turns. A scoped cancel targets- // only the named parallel turn (if it is one); an unscoped cancel/stop- // covers every parallel turn on the thread, not just the primary one.- let cancelled_parallel = match request_id {- Some(rid) => cancel_parallel_turn_by_request_id(thread_id, rid).await,- None => cancel_parallel_turns_for_thread(thread_id).await,- };-- // #4760: a scoped cancel that matched only a parallel (forked) turn — not the- // primary — still genuinely tore a turn down and emitted its cancelled event.- // Surface that id so `channel_web_cancel` reports `cancelled: true` with the- // right request_id instead of misreporting a no-op just because the primary- // turn wasn't the one cancelled.- let cancelled_any = removed_request_id- .clone()- .or_else(|| cancelled_parallel.first().cloned());-- // Emit a cancelled chat_error for each cancelled turn (primary + parallels)- // so every interleaved branch's UI is resolved.- for request_id in removed_request_id.into_iter().chain(cancelled_parallel) {- publish_web_channel_event(WebChannelEvent {- event: "chat_error".to_string(),- client_id: client_id.to_string(),- thread_id: thread_id.to_string(),- request_id,- message: Some("Cancelled".to_string()),- error_type: Some("cancelled".to_string()),- ..Default::default()- });- }-- Ok(cancelled_any)-}--pub async fn channel_web_chat(- client_id: &str,- thread_id: &str,- message: &str,- model_override: Option<String>,- temperature: Option<f64>,- profile_id: Option<String>,- locale: Option<String>,- queue_mode: Option<String>,- metadata: ChatRequestMetadata,-) -> Result<RpcOutcome<Value>, String> {- let result = start_chat(- client_id,- thread_id,- message,- model_override,- temperature,- profile_id,- locale,- queue_mode,- metadata,- )- .await?;-- if let Ok(parsed) = serde_json::from_str::<Value>(&result) {- return Ok(RpcOutcome::single_log(parsed, "web channel message queued"));- }-- Ok(RpcOutcome::single_log(- json!({- "accepted": true,- "client_id": client_id.trim(),- "thread_id": thread_id.trim(),- "request_id": result,- }),- "web channel request accepted",- ))-}--pub async fn channel_web_queue_status(thread_id: &str) -> Result<RpcOutcome<Value>, String> {- let map_key = key_for(thread_id);- let in_flight = IN_FLIGHT.lock().await;- if let Some(entry) = in_flight.get(&map_key) {- let status = entry.run_queue.status().await;- Ok(RpcOutcome::single_log(- json!({- "thread_id": thread_id.trim(),- "active": true,- "request_id": entry.request_id,- "steers": status.steers,- "followups": status.followups,- "collects": status.collects,- "total": status.total,- }),- "queue status retrieved",- ))- } else {- Ok(RpcOutcome::single_log(- json!({- "thread_id": thread_id.trim(),- "active": false,- "steers": 0,- "followups": 0,- "collects": 0,- "total": 0,- }),- "no active turn for thread",- ))- }-}--pub async fn channel_web_queue_clear(thread_id: &str) -> Result<RpcOutcome<Value>, String> {- let map_key = key_for(thread_id);- let in_flight = IN_FLIGHT.lock().await;- if let Some(entry) = in_flight.get(&map_key) {- let dropped = entry.run_queue.clear().await;- log::info!(- "[web-channel] cleared queue thread_id={} dropped={}",- thread_id,- dropped- );- Ok(RpcOutcome::single_log(- json!({- "thread_id": thread_id.trim(),- "cleared": true,- "dropped": dropped,- }),- "queue cleared",- ))- } else {- Ok(RpcOutcome::single_log(- json!({- "thread_id": thread_id.trim(),- "cleared": false,- "dropped": 0,- }),- "no active turn for thread",- ))- }-}--pub async fn channel_web_cancel(- client_id: &str,- thread_id: &str,- request_id: Option<&str>,-) -> Result<RpcOutcome<Value>, String> {- let cancelled_request_id = cancel_chat_scoped(client_id, thread_id, request_id).await?;-- // No web-channel turn matched. Fall through to the task-dispatcher registry,- // which holds autonomous runs that are NOT web-channel turns (so they never- // appear in IN_FLIGHT and can only be reached here). The fallback is itself- // request-scoped: a scoped cancel aborts the run only when its run_id- // matches, so a stale cancel for a superseded request can't tear down a newer- // run on the thread (#4760); an unscoped stop aborts whatever run is running.- let cancelled = if cancelled_request_id.is_some() {- true- } else {- crate::agent::task_dispatcher::cancel_session_scoped(- thread_id.trim(),- request_id,- )- .await- };-- Ok(RpcOutcome::single_log(- json!({- "cancelled": cancelled,- "client_id": client_id.trim(),- "thread_id": thread_id.trim(),- "request_id": cancelled_request_id,- }),- "web channel cancellation processed",- ))-}