Skip to content

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

chore: replace placeholder test module with real observability tests

Steven Enamakelde574e7d6102
diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rs
index 2fe5f20643..47226f9e0e 100644
--- a/crates/openhuman-core/src/core/observability.rs
+++ b/crates/openhuman-core/src/core/observability.rs
@@ -3709,4324 +3709,7 @@ fn parse_version(version: &str) -> Option<(u32, u32)> {
Some((major, minor))
}
+
#[cfg(test)]
-#[path = "obs_tests_placeholder.rs"]
+#[path = "observability_tests.rs"]
mod tests;
-
-
- #[test]
- fn classifies_embedding_backend_auth_failure() {
- // TAURI-RUST-T (~4k events) — companion of TAURI-RUST-4K5: the
- // OpenHuman backend rejected the embeddings worker's bearer
- // token. Both the bare-status and parenthesised wire shapes
- // must classify as SessionExpired so the FE re-login prompt
- // fires (matches the contract introduced by #2786 and
- // exercised by classifies_embedding_api_invalid_token_401_as_session_expired).
- for raw in [
- r#"Embedding API error 401 Unauthorized: {"success":false,"error":"Invalid token"}"#,
- r#"Embedding API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#,
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::SessionExpired),
- "should classify embedding backend auth failure as SessionExpired: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_embedding_model_does_not_exist_400_as_config_rejection() {
- // TAURI-RUST-9SK (~2205 events / 1 user) — a chat model id pasted as the
- // embeddings model. Verbatim OpenRouter wire body (bare "does not exist"
- // + integer "code":400), plus the enriched form after the emit site
- // appends the actionable remediation. Both must demote so the per-embed
- // flood stays out of Sentry.
- for raw in [
- r#"Embedding API error (400 Bad Request): {"error":{"message":"Model nvidia/nemotron-3-super-120b-a12b does not exist","code":400}}"#,
- "Embedding API error (400 Bad Request): {\"error\":{\"message\":\"Model nvidia/nemotron-3-super-120b-a12b does not exist\",\"code\":400}} — this model isn't an embeddings model; pick an embeddings-capable model in Settings → Memory",
- r#"Embedding API error (400 Bad Request): {"error":{"message":"this model does not support embeddings"}}"#,
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderConfigRejection),
- "should classify embedding model-rejection 400 as config rejection: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_gemini_model_format_400_as_config_rejection() {
- // TAURI-RUST-4SA (~4,494 events / 1 user) — a bare model id sent to
- // Gemini's OpenAI-compat shim, which maps `/v1/embeddings` →
- // `BatchEmbedContents` and demands `models/<name>`. Verbatim Gemini wire
- // body plus the enriched form after the emit site appends the Gemini
- // remediation, and the alternate `INVALID_ARGUMENT` + field-path shape.
- // All must demote so the per-embed flood stays out of Sentry.
- for raw in [
- r#"Embedding API error (400 Bad Request): {"error":{"code":400,"message":"BatchEmbedContentsRequest.model: unexpected model name format","status":"INVALID_ARGUMENT"}}"#,
- "Embedding API error (400 Bad Request): {\"error\":{\"code\":400,\"message\":\"BatchEmbedContentsRequest.model: unexpected model name format\",\"status\":\"INVALID_ARGUMENT\"}} — Gemini needs the embeddings model id in `models/<name>` form (e.g. `models/text-embedding-004`); fix it in Settings → Memory",
- r#"Embedding API error (400 Bad Request): {"error":{"code":400,"message":"Invalid value at 'model'","status":"INVALID_ARGUMENT","details":[{"field":"BatchEmbedContentsRequest.model"}]}}"#,
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderConfigRejection),
- "should classify Gemini model-format 400 as config rejection: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_unrelated_embedding_400s() {
- // Polarity: a 400 that is NOT a model-rejection (e.g. oversized input)
- // and any non-400 must keep reaching Sentry.
- assert_eq!(
- expected_error_kind(
- r#"Embedding API error (400 Bad Request): {"error":{"message":"input exceeds the maximum number of tokens"}}"#
- ),
- None
- );
- assert_eq!(
- expected_error_kind(
- r#"Embedding API error (500 Internal Server Error): {"error":"model does not exist"}"#
- ),
- None
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_invalid_token_messages() {
- // Provider 401s with "invalid token" in the body but no
- // `Embedding API error` prefix must keep reaching Sentry — they're
- // not the same wire shape and may indicate real provider bugs.
- assert_eq!(
- expected_error_kind(r#"openai chat failed 401: {"error":"invalid token"}"#),
- None
- );
- // Embedding error without 401 must not be silenced.
- assert_eq!(
- expected_error_kind(
- r#"Embedding API error 500 Internal Server Error: {"error":"invalid token signature service down"}"#
- ),
- None
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_ollama_errors_as_user_config() {
- // Unrelated 500 — server-side ollama bug must still reach Sentry.
- assert_eq!(
- expected_error_kind("ollama embed failed with status 500"),
- None
- );
- // Parse-failure on the response — real bug in either the server
- // or our deserializer, must still reach Sentry.
- assert_eq!(
- expected_error_kind(
- "ollama embed response parse failed: invalid type: expected sequence"
- ),
- None
- );
- // Dimension mismatch — real bug (model dims don't match what we
- // recorded), must still reach Sentry.
- assert_eq!(
- expected_error_kind(
- "ollama embed dimension mismatch at index 0: expected 768, got 1024"
- ),
- None
- );
- // Unrelated `invalid model name` outside Ollama embed call —
- // anchor on the `ollama embed` prefix keeps this from being silenced.
- assert_eq!(
- expected_error_kind("provider config validation failed: invalid model name"),
- None
- );
- // Unrelated `model "…" not found` text without the `ollama embed`
- // prefix — anchor keeps this from being silenced even when the
- // exact MA/KM wire-shape substring appears in another context.
- assert_eq!(
- expected_error_kind(r#"provider listing failed: model \"foo\" not found in registry"#),
- None
- );
- }
-
- #[test]
- fn classifies_local_ai_capability_unavailable_errors() {
- // OPENHUMAN-TAURI-3B: surfaced by `local_ai_download_asset` when a
- // user on a 0–4 GB RAM tier requests a vision asset. Both canonical
- // wire shapes — emitted from `assets.rs` and `vision_embed.rs` —
- // must classify as expected so they stop reaching Sentry.
- for raw in [
- "Vision is disabled for this RAM tier. Switch to the 4-8 GB tier or above to enable it.",
- "vision summaries are unavailable for this RAM tier. Use OCR-only summarization or switch to a higher local AI tier.",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::LocalAiCapabilityUnavailable),
- "should classify as local-ai capability unavailable: {raw}"
- );
- }
-
- // Wrapped by the RPC dispatch layer as it reaches `report_error_or_expected`
- // — the classifier is substring-based, so caller context must not defeat it.
- assert_eq!(
- expected_error_kind(
- "rpc.invoke_method failed: Vision is disabled for this RAM tier. Switch to the 4-8 GB tier or above to enable it."
- ),
- Some(ExpectedErrorKind::LocalAiCapabilityUnavailable)
- );
- }
-
- #[test]
- fn classifies_prompt_injection_blocked_errors() {
- // OPENHUMAN-TAURI-140: ~1 480 events from `openhuman.agent_chat` where
- // users' messages scored ≥ 0.45 on the injection heuristic. Both
- // enforcement wire shapes must be classified as expected so they stop
- // reaching Sentry.
- for raw in [
- "Prompt flagged for security review and was not processed. Please rephrase clearly.",
- "Prompt blocked by security policy. Please rephrase without instruction overrides or exfiltration requests.",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::PromptInjectionBlocked),
- "should classify as prompt-injection blocked: {raw}"
- );
- }
-
- // Wrapped by the RPC dispatch layer — substring match must survive the prefix.
- assert_eq!(
- expected_error_kind(
- "rpc.invoke_method failed: Prompt flagged for security review and was not processed. Please rephrase clearly."
- ),
- Some(ExpectedErrorKind::PromptInjectionBlocked)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_messages_as_prompt_injection_blocked() {
- // Must not silently swallow real security errors or generic "prompt" mentions.
- assert_eq!(
- expected_error_kind("prompt injection detected in tool arguments"),
- None
- );
- assert_eq!(
- expected_error_kind("security review required for deploy"),
- None
- );
- }
-
- // ── ContextWindowExceeded (TAURI-RUST-501) ─────────────────────────────
-
- #[test]
- fn classifies_context_window_exceeded_rereport() {
- // TAURI-RUST-501: the custom-provider 500 body that escapes the
- // provider api_error cascade's own status-gated checks. When the
- // error is re-raised by `agent.run_single` / `web_channel.
- // run_chat_task`, `report_error_or_expected` runs the classifier on
- // the full message — this arm must catch the new phrasing.
- assert_eq!(
- expected_error_kind(
- "custom API error (500 Internal Server Error): \
- {\"error\":{\"code\":500,\"message\":\"Context size has been exceeded.\",\"type\":\"server_error\"}}"
- ),
- Some(ExpectedErrorKind::ContextWindowExceeded)
- );
-
- // The established phrasings the provider/reliable layer already
- // recognized must classify here too (single-source matcher).
- for raw in [
- "OpenAI API error (400): This model's maximum context length is 8192 tokens",
- "request exceeds the context window of this model",
- "context length exceeded",
- "prompt is too long",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ContextWindowExceeded),
- "should classify as context-window-exceeded: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_lmstudio_n_keep_exceeds_n_ctx_rereport() {
- // TAURI-RUST-6V0: the verbatim LM Studio 400 body — the un-evictable
- // prefix (`n_keep`) is larger than the model's loaded context
- // (`n_ctx`). When this 400 slips past the pre-dispatch guard and is
- // re-raised by the agent/web_channel, `report_error_or_expected` must
- // classify it as expected user-state so it stays out of Sentry.
- assert_eq!(
- expected_error_kind(
- "lmstudio API error (400 Bad Request): {\"error\":\"The number of tokens to keep from the initial prompt is greater than the context length (n_keep: 10978 >= n_ctx: 8192). Try to load the model with a larger context length, or provide a shorter input.\"}"
- ),
- Some(ExpectedErrorKind::ContextWindowExceeded)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_messages_as_context_window_exceeded() {
- // Anchors are context-overflow specific. A generic "window" or
- // "context" mention, or an unrelated rate-limit "exceeded", must
- // not classify.
- for raw in [
- "rate limit exceeded, retry after 30s",
- "failed to open context menu window",
- "tool call exceeded the allowed budget",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "must NOT classify as context-window-exceeded: {raw}"
- );
- }
- }
-
- // ── ProviderUserState: permanent TPM rate cap (TAURI-RUST-HXF) ─────────
-
- #[test]
- fn classifies_provider_rate_cap_413_tpm_rereport_as_provider_user_state() {
- // TAURI-RUST-HXF: verbatim groq `on_demand` free-tier body — a single
- // subconscious request (42084 tokens) exceeds the 8000 tokens-per-minute
- // cap, so groq returns 413 and no retry can ever fit it. When re-raised
- // by `agent.run_single` under `domain=agent`, `report_error_or_expected`
- // must demote it to expected user-config state (the user's account tier
- // is not a lever OpenHuman controls) instead of paging Sentry.
- assert_eq!(
- expected_error_kind(
- "groq API error (413 Payload Too Large): {\"error\":{\"message\":\"Request too large \
- for model `openai/gpt-oss-120b` in organization `org_01k48ewn75ez7tsgw5hmd72px2` \
- service tier `on_demand` on tokens per minute (TPM): Limit 8000, Requested 42084. \
- Please try again later.\",\"type\":\"tokens\",\"code\":\"rate_limit_exceeded\"}}"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- #[test]
- fn managed_backend_payload_too_large_still_pages_despite_rate_cap_arm() {
- // Regression pin: a *managed-backend* `PAYLOAD_TOO_LARGE` is a
- // client-guard leak (the client was supposed to bound the request) and
- // MUST keep paging. The guard-leak arm returns `None` before the
- // ProviderUserState matcher runs, so the new TPM arm cannot demote it.
- assert_eq!(
- expected_error_kind(
- "OpenHuman API error (413 Payload Too Large): \
- {\"error\":{\"errorCode\":\"PAYLOAD_TOO_LARGE\",\"message\":\"request too big\"}}"
- ),
- None,
- "managed PAYLOAD_TOO_LARGE guard-leak must still page"
- );
- }
-
- #[test]
- fn transient_tpm_burst_and_bare_413_do_not_demote_as_rate_cap() {
- // The arm requires BOTH "request too large" (single-request permanence)
- // AND a per-minute-tokens marker. A transient burst ("try again in Ns")
- // and a bare 413 lacking those anchors must NOT be demoted to
- // ProviderUserState — they stay retryable / Sentry-visible.
- for raw in [
- "groq API error (429 Too Many Requests): Rate limit reached for model \
- `openai/gpt-oss-120b`. Please try again in 2.5s.",
- "openai API error (413 Payload Too Large): request entity too large",
- ] {
- assert_ne!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderUserState),
- "must NOT demote as permanent rate-cap: {raw}"
- );
- }
- }
-
- // ── FilesystemUserPathInvalid (TAURI-RUST-4QH) ─────────────────────────
-
- #[test]
- fn classifies_vault_create_root_path_not_a_directory_as_filesystem_user_path_invalid() {
- // TAURI-RUST-4QH: verbatim wire shape from
- // `openhuman::vault::ops::vault_create` line 37 when the
- // user-picked vault folder doesn't resolve to an existing
- // directory. Bubbles up as the RPC dispatcher's
- // `display_message` and reaches `report_error_or_expected` —
- // must classify so no Sentry event fires.
- assert_eq!(
- expected_error_kind(
- "root_path is not a directory: /Users/zadam/Documents/SndBrainOpenHuman"
- ),
- Some(ExpectedErrorKind::FilesystemUserPathInvalid)
- );
-
- // The same body wrapped by the JSON-RPC dispatcher's `display_message`
- // prefix (`rpc.invoke_method` re-emit shape from `crates/openhuman-core/src/core/jsonrpc.rs`).
- // Must still classify so the dispatch-site re-report doesn't escape
- // the matcher even if a future caller layers more context.
- assert_eq!(
- expected_error_kind(
- "rpc.invoke_method failed: root_path is not a directory: /Users/alice/openhuman-data"
- ),
- Some(ExpectedErrorKind::FilesystemUserPathInvalid)
- );
- }
-
- #[test]
- fn classifies_http_host_hosted_path_not_a_directory_as_filesystem_user_path_invalid() {
- // Preempt the symmetric shape from
- // `openhuman::http_host::path_utils:23` —
- // `"hosted path is not a directory: <path>"`. Not yet observed
- // in Sentry but shares the same RPC validation polarity as
- // vault_create's `root_path` check. Anchoring on
- // `"path is not a directory:"` (with trailing colon) covers
- // both without two separate matchers.
- assert_eq!(
- expected_error_kind("hosted path is not a directory: /var/www/static-site"),
- Some(ExpectedErrorKind::FilesystemUserPathInvalid)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_path_messages_as_filesystem_user_path_invalid() {
- // Polarity contract — the anchor requires a trailing colon
- // after `"is not a directory"`, which discriminates user input
- // (path follows the colon) from other shapes:
- //
- // 1. The `skills::ops_install:475` SAFETY GUARD —
- // `"<path> is not a directory — refusing to remove"` — must
- // stay actionable. It catches an `rm -rf` invariant violation
- // (the target should have been a directory but wasn't),
- // which is a code bug, not user input.
- // 2. A narrative log line that happens to mention the phrase
- // without the user-path colon suffix is not a validation
- // failure and must not be silenced.
- // 3. The dot-prefix variant from POSIX `EISDIR`/`ENOTDIR`
- // renderings (`"Is a directory (os error 21)"`) is the
- // inverse condition — different code path entirely.
- for raw in [
- // Safety guard — must NOT classify.
- "/tmp/openhuman-cache is not a directory — refusing to remove",
- // Narrative log line — must NOT classify.
- "checked that path is not a directory before mkdir",
- // Inverse condition (os error 21: EISDIR) — must NOT classify.
- "open /etc/passwd failed: Is a directory (os error 21)",
- // Bare path with no `directory` mention — must NOT classify.
- "root_path must be absolute: ./relative/path",
- // Generic body with the trailing colon but no known vault/http_host
- // prefix — must NOT classify (future provider/storage errors that
- // happen to embed "path is not a directory: ..." should reach Sentry).
- "input config path is not a directory: /etc/foo",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "polarity contract: must NOT classify as FilesystemUserPathInvalid: {raw}"
- );
- }
- }
-
- // ── EmptyProviderResponse (TAURI-RUST-4Z1) ─────────────────────────────
-
- #[test]
- fn classifies_empty_provider_response_web_channel_rereport() {
- // TAURI-RUST-4Z1: the web-channel re-report of the agent harness's
- // empty-provider-response bail. `run_chat_task` wraps the flattened
- // string and routes it through `report_error_or_expected` — the
- // agent-layer typed suppression (PR #2790) can't reach it, so this
- // string classifier must.
- assert_eq!(
- expected_error_kind(
- "run_chat_task failed client_id=l1uxaLd20_1mAdhp \
- thread_id=thread-8f03e7f7-3477-42cd-9283-f0bacd4bfbca \
- request_id=a73716a3-a85a-4045-984b-315772c5b3b8 \
- error=The model returned an empty response. Please try again."
- ),
- Some(ExpectedErrorKind::EmptyProviderResponse)
- );
-
- // Bare user-facing string (the verbatim `turn.rs` emission), in case
- // a different call site re-reports it without the run_chat_task wrap.
- assert_eq!(
- expected_error_kind("The model returned an empty response. Please try again."),
- Some(ExpectedErrorKind::EmptyProviderResponse)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_empty_response_phrases() {
- // Polarity contract: the anchor is `"model returned an empty
- // response"`, NOT the looser `"empty response"`. The sibling paths
- // below use different subjects or phrasings and are not user-facing
- // failures — they must stay out of this bucket so a real regression
- // in those paths still reaches Sentry.
- for raw in [
- // payload_summarizer.rs:261 — internal fall-through, not a failure.
- "[payload_summarizer] summarizer returned empty response, falling through",
- // subagent_runner/extract_tool.rs:379 — graceful empty extraction.
- "[extract_from_result] provider returned an empty response; returning empty extraction",
- // Generic mention without the model-subject anchor.
- "warning: empty response body from health probe",
- // channels/bus.rs:185 — channel-inbound graceful fallback (routes
- // through report_error_or_expected; subject is "agent", not "model").
- "[channel-inbound] agent returned empty response — finalizing draft with fallback",
- // memory/query/walk.rs:292 — debug-level memory walk, not a failure.
- "[memory_tree_walk] turn=3 LLM gave up (empty response)",
- // learning/reflection.rs:576 — reflection skip, not a failure.
- "[learning] reflection skipped (empty response — gate off or local AI unavailable)",
- // agent/harness/session/turn.rs:811 — "provider returned an empty
- // final response" uses subject "provider", not "model"; must not match.
- "[agent_loop] provider returned an empty final response (i=2, no text, no tool calls)",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "must NOT classify as EmptyProviderResponse: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_memory_store_breaker_open() {
- // TAURI-RUST-52X (~455 events on self-hosted Sentry): the chunk-store
- // per-path circuit breaker tripped after consecutive SQLite init
- // failures. The Windows wire shape is wrapped by
- // `memory_tree::tree::rpc::pipeline_status_rpc`'s `chunk aggregates: …`
- // context so the substring matcher must survive that prefix.
- for raw in [
- // Canonical wire shape from `get_or_init_connection`.
- "[memory_tree] circuit breaker open for /home/u/.openhuman/workspace/memory_tree/chunks.db: too many consecutive init failures",
- // Canonical wire shape wrapped by the RPC handler's
- // `format!("chunk aggregates: {e:#}")` context.
- r"chunk aggregates: [memory_tree] circuit breaker open for C:\Users\u\.openhuman\users\6a09\workspace\memory_tree\chunks.db: too many consecutive init failures",
- // Wrapped further by the JSON-RPC dispatch layer before reaching
- // `report_error_or_expected`.
- r"rpc.invoke_method failed: chunk aggregates: [memory_tree] circuit breaker open for /home/u/.openhuman/workspace/memory_tree/chunks.db: too many consecutive init failures",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::MemoryStoreBreakerOpen),
- "should classify memory-store breaker-open: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_disk_full_errors() {
- for raw in [
- // Canonical POSIX errno 28 rendering from `std::io::Error`.
- "Failed to create auth profile lock: open lock file: No space left on device (os error 28)",
- // Same shape from a different call site — `tokio::fs::write`
- // for a state snapshot.
- "state snapshot write failed: No space left on device (os error 28)",
- // Windows ERROR_DISK_FULL (112) rendering.
- "log rotation failed: There is not enough space on the disk. (os error 112)",
- // Outer-only `{}` wire shape that production actually emits for the
- // auth-profile lock-create failure (Sentry TAURI-RUST-4SZ): the
- // inner io::Error Display is flattened away at the RPC boundary, so
- // only the `ErrorKind` debug + os_code survive — no "no space left
- // on device" text. Must still classify via the StorageFull anchor.
- "Failed to create auth profile lock (kind=Some(StorageFull), os_code=Some(28))",
- // SQLITE_FULL rendering from rusqlite — engine-level disk-full
- // detection during page-bookkeeping (journal/WAL extension) that
- // beats the next syscall to the errno. Production hit at
- // `memory_store::namespace_store::documents::tx.commit()` during
- // `openhuman.memory_doc_ingest`, in the same burst that emits
- // os-error-112 siblings (Sentry TAURI-RUST-B6N).
- "commit tx: database or disk is full",
- // SQLITE_FULL **extended** rendering — the full error-code envelope
- // where the canonical phrase is mid-string, not a suffix (Sentry
- // TAURI-RUST-4R8, `memory_queue::store::claim_next` on
- // `mem_tree_jobs`). Caught via the `code_to_str` token arm.
- "Failed to claim next mem_tree_jobs row: database or disk is full: \
- Error code 13: Insertion failed because database is full",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::DiskFull),
- "should classify disk-full: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_unrelated_space_messages() {
- // Generic "space" prose without the errno-text anchor must not be
- // silenced — the matcher pins to the platform-stable errno
- // renderings only.
- assert_eq!(
- expected_error_kind("workspace path is invalid: contains a space character"),
- None
- );
- assert_eq!(
- expected_error_kind("not enough memory to allocate buffer"),
- None
- );
- // The SQLite anchor pins to the exact `"database or disk is full"`
- // phrase. Generic prose that mentions a full database for unrelated
- // reasons (e.g. duplicate-row complaints, application-level capacity
- // talk) must not be silenced.
- assert_eq!(
- expected_error_kind("upsert failed: database is full of duplicates"),
- None
- );
- assert_eq!(
- expected_error_kind("user quota: database is full for this tier"),
- None
- );
- // A non-2xx backend body whose payload contains the SQLITE_FULL phrase
- // (e.g. `api.tinyhumans.ai` server-side SQLite is full) is an
- // operator-actionable storage failure, not the user's local disk —
- // must still surface to Sentry. `integrations::client::post` frames
- // these as `"Backend returned <status> <reason> for POST <url>:
- // <detail>"` (codex CR on #3672). The suffix anchor excludes the
- // embedded-in-JSON case; the negative `"backend returned "` guard
- // covers the rare case where the body itself ends with the phrase.
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/list: \
- {\"error\":\"database or disk is full\"}"
- ),
- None,
- "remote-backend body must surface"
- );
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/list: \
- database or disk is full"
- ),
- None,
- "remote-backend body must surface even when the body itself ends with the phrase"
- );
- // Same guard for the extended-code token: a backend body that quotes
- // the SQLITE_FULL `code_to_str` string is still operator-actionable
- // and must surface (TAURI-RUST-4R8 token arm + `"backend returned "`
- // exclusion).
- assert_eq!(
- expected_error_kind(
- "Backend returned 507 Insufficient Storage for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/list: \
- Error code 13: Insertion failed because database is full"
- ),
- None,
- "remote-backend body carrying the extended SQLITE_FULL token must surface"
- );
- // A remote OpenAI-compatible embeddings 500 whose server-side SQLite is
- // full is wrapped by `OpenAiEmbedding::embed` as `"Embedding API error
- // (…)"` — no `"backend returned "` prefix and no local `"database or
- // disk is full"` phrase, just the `code_to_str` half. Requiring BOTH
- // local fragments for the extended shape keeps this operator-actionable
- // server fault reportable (codex CR on #3911).
- assert_eq!(
- expected_error_kind(
- "Embedding API error (status 500): Error code 13: \
- Insertion failed because database is full"
- ),
- None,
- "remote embedding-API body quoting only the code_to_str token must surface"
- );
- // Non-suffix occurrences in other body framings (no `"Backend
- // returned"` prefix) are also excluded by the suffix anchor — locks
- // in the primary defense layer.
- assert_eq!(
- expected_error_kind(
- "Embedding API error (500 Internal Server Error): \
- {\"error\":\"database or disk is full\",\"retry\":true}"
- ),
- None,
- "embedded-in-JSON body must surface"
- );
- }
-
- #[test]
- fn classifies_config_load_timed_out() {
- // Canonical wire string emitted by `load_config_with_timeout` and
- // `reload_config_snapshot_with_timeout` in
- // `crates/openhuman-core/src/config/ops.rs`. Drops TAURI-RUST-5X.
- assert_eq!(
- expected_error_kind("Config loading timed out"),
- Some(ExpectedErrorKind::ConfigLoadTimedOut),
- );
- // Same shape after the RPC dispatch wraps it for display — the
- // matcher is substring-anchored, so a context prefix does not
- // break it.
- assert_eq!(
- expected_error_kind("rpc.invoke_method failed: Config loading timed out"),
- Some(ExpectedErrorKind::ConfigLoadTimedOut),
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_timeouts_as_config_load_timed_out() {
- // Network / HTTP timeouts go to `NetworkUnreachable` /
- // `TransientUpstreamHttp`, not the config-load bucket. The
- // anchor is the full literal phrase, so a bare "timed out" or
- // "operation timed out" body cannot trip this matcher.
- assert_ne!(
- expected_error_kind(
- "Channel discord error: IO error: Operation timed out (os error 60); restarting"
- ),
- Some(ExpectedErrorKind::ConfigLoadTimedOut),
- );
- assert_ne!(
- expected_error_kind("OpenHuman API error (504 Gateway Timeout): error code: 504"),
- Some(ExpectedErrorKind::ConfigLoadTimedOut),
- );
- // Bare "timed out" without the config-load phrase must not match.
- assert_eq!(expected_error_kind("cron job timed out after 30s"), None,);
- }
-
- #[test]
- fn classifies_config_read_io_failure_for_os_denial_kinds() {
- // TAURI-RUST-DME shape once the loader surfaces the full io chain
- // (#3962): Windows access-denied on an existing config.toml.
- assert_eq!(
- expected_error_kind(
- "Failed to read config file: C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml: Access is denied. (os error 5)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // Sharing-violation: file held open by another process (antivirus /
- // backup agent).
- assert_eq!(
- expected_error_kind(
- "Failed to read config file: C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml: The process cannot access the file because it is being used by another process. (os error 32)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // Unix permission-denied wording.
- assert_eq!(
- expected_error_kind(
- "Failed to read config file: /home/u/.openhuman/users/local/config.toml: Permission denied (os error 13)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // Snapshot-reload context anchor (`load_from_config_path`) must demote
- // the same OS-denial family so a long-lived reloader can't leak either.
- assert_eq!(
- expected_error_kind(
- "reading config.toml from C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml: Access is denied. (os error 5)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- }
-
- /// A denial caused by the config being owned by a *different uid than the
- /// process reading it* is an OpenHuman defect, not user-environment state:
- /// we pick the container runtime uid and we write the file at 0600, and the
- /// entrypoint historically chowned only the workspace directory — so a
- /// reused volume denied every config RPC (including the sign-in
- /// `auth_store_session`) while `/health` stayed green and Sentry saw
- /// nothing. It must keep paging.
- #[test]
- fn does_not_demote_config_read_denial_on_owner_mismatch() {
- let marker = crate::config::schema::CONFIG_OWNER_MISMATCH_MARKER;
- assert_ne!(
- expected_error_kind(&format!(
- "Failed to read config file: /home/openhuman/.openhuman/config.toml {marker} \
- (file uid=0 gid=0 mode=0600; process euid=10001 egid=10001): \
- Permission denied (os error 13)"
- )),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- }
-
- /// The complement: without the marker the file is ours and readable-in-
- /// principle, so the denial really is an ACL / antivirus / OneDrive
- /// condition with no local lever, and stays demoted. Guarding this pins
- /// that the exclusion above is keyed on the marker, not on "permission".
- #[test]
- fn still_demotes_config_read_denial_without_owner_mismatch() {
- assert_eq!(
- expected_error_kind(
- "Failed to read config file: /home/u/.openhuman/users/local/config.toml \
- (file uid=501 gid=20 mode=0000; process euid=501 egid=20): \
- Permission denied (os error 13)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- }
-
- #[test]
- fn does_not_demote_config_read_notfound_or_unkeyed_failures() {
- // NotFound AFTER the `exists()` gate is a TOCTOU race / app defect —
- // it MUST keep paging, never demote.
- assert_ne!(
- expected_error_kind(
- "Failed to read config file: C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml: The system cannot find the file specified. (os error 2)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // Bare top-context line with no io signal (pre-#3962 shape, or an io
- // kind we have not enumerated) must NOT demote — fail open to paging.
- assert_ne!(
- expected_error_kind(
- "Failed to read config file: C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // The access-denied signal alone, without the config-read anchor, must
- // not be hijacked into the config bucket.
- assert_ne!(
- expected_error_kind("opening keychain failed: Access is denied. (os error 5)"),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- // A directory at the config path is corruption — keep paging even though
- // it carries an access-denied / os-error-5 shape (Codex P2). Both the
- // unix wording and the Windows os-error-5 + read-site wording are
- // excluded by the `is a directory` / `not a file` guard.
- assert_ne!(
- expected_error_kind(
- "Failed to read config file: /home/u/.openhuman/users/local/config.toml: Is a directory (os error 21)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- assert_ne!(
- expected_error_kind(
- "Config path is a directory, not a file: C:\\Users\\u\\.openhuman\\users\\local-wb\\config.toml: Access is denied. (os error 5)"
- ),
- Some(ExpectedErrorKind::ConfigReadIoFailure),
- );
- }
-
- #[test]
- fn classifies_subconscious_schema_unavailable_errors() {
- for raw in [
- // SQLITE_IOERR_SHMMAP (4618) — the original escalating issue (#3231).
- "failed to run subconscious schema DDL: disk I/O error: Error code 4618: I/O error within the xShmMap method (trying to open a new shared-memory segment)",
- // SQLITE_CANTOPEN (14) — sibling variant from the user report.
- "failed to run subconscious schema DDL: unable to open database file: Error code 14: Unable to open the database file",
- // Failure surfaced at the open step rather than the DDL step.
- "failed to open subconscious DB: /home/u/.openhuman/subconscious/subconscious.db: unable to open the database file",
- // Wrapped in outer RPC context — classifier runs on the full chain.
- "rpc.invoke_method failed: failed to run subconscious schema DDL: disk I/O error: Error code 4618",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::SubconsciousSchemaUnavailable),
- "should classify subconscious schema DB-unavailable: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_subconscious_lock_or_unrelated_open_failures() {
- for raw in [
- // Transient busy/locked is retried by the store and, if persistent,
- // is a real contention signal — must NOT be demoted here.
- "failed to run subconscious schema DDL: database is locked",
- // Cant-open text without the subconscious envelope must not match.
- "failed to open memory DB: unable to open the database file",
- // Subconscious envelope but a non-FS error (e.g. malformed SQL) stays
- // a real bug worth reporting.
- "failed to run subconscious schema DDL: near \"CREAT\": syntax error",
- ] {
- assert_ne!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::SubconsciousSchemaUnavailable),
- "must not classify as subconscious schema unavailable: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_unrelated_breaker_messages() {
- // Generic "circuit breaker open" without the `[memory_tree]` anchor
- // must not be silenced — other domains may use the same phrase for
- // real bugs that need to reach Sentry.
- assert_eq!(
- expected_error_kind("provider reliability: circuit breaker open for openai"),
- None
- );
- // The `[memory_tree]` tag alone is not enough — must co-occur with
- // the `circuit breaker open` substring.
- assert_eq!(
- expected_error_kind("[memory_tree] failed to run schema DDL: disk full"),
- None
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_messages_as_capability_unavailable() {
- // The classifier anchors on the exact "for this RAM tier" substring.
- // Messages that talk about RAM in a different context (sizing the
- // tier list, doc references) must not be silenced.
- assert_eq!(expected_error_kind("ollama embed failed: out of RAM"), None);
- assert_eq!(
- expected_error_kind("local_ai_set_ram_tier failed: invalid tier value"),
- None
- );
- }
-
- #[test]
- fn classifies_network_unreachable_errors() {
- // OPENHUMAN-TAURI-32: reqwest's transport-level error wrapped by the
- // web_channel error site. The classifier must catch it even when
- // embedded in caller context, since `report_error_or_expected` runs
- // `expected_error_kind` on the full anyhow chain.
- assert_eq!(
- expected_error_kind(
- "run_chat_task failed client_id=abc thread_id=t1 request_id=r1 \
- error=error sending request for url (https://api.tinyhumans.ai/openai/v1/chat/completions)"
- ),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
- for raw in [
- "error sending request for url (https://api.example.com/x)",
- "provider failed: dns error: failed to lookup address information",
- "tcp connect: connection refused (os error 61)",
- "stream closed: connection reset by peer",
- "network is unreachable (os error 51)",
- "no route to host",
- "tls handshake eof",
- "certificate verify failed: unable to get local issuer certificate",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::NetworkUnreachable),
- "should classify as network-unreachable: {raw}"
- );
- }
- }
-
- #[test]
- fn custom_openai_ollama_timeout_fallback_chain_is_network_unreachable() {
- let chain =
- "custom_openai chat completions transport error: error sending request for url \
- (http://localhost:11434/v1/chat/completions): operation timed out \
- (responses fallback failed: custom_openai API error (404 Not Found): \
- {\"error\":\"not found\"})";
- assert_eq!(
- expected_error_kind(chain),
- Some(ExpectedErrorKind::NetworkUnreachable),
- "local Ollama timeout plus responses fallback failure must not page Sentry"
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_provider_errors_as_network() {
- // Status-bearing provider failures (404, 500, …) are surfaced via
- // their HTTP status path and must NOT be silenced by the
- // network-unreachable classifier — the body text doesn't hit any of
- // the transport-level markers.
- assert_eq!(
- expected_error_kind("OpenAI API error (404): model gpt-x not found"),
- None
- );
- assert_eq!(
- expected_error_kind("OpenAI API error (500): internal server error"),
- None
- );
- }
-
- #[test]
- fn classifies_wave4_socket_transport_wire_shapes() {
- // OPENHUMAN-TAURI-44 (~50 events): libc `getaddrinfo()` rendering
- // without the `dns error` token, wrapped by the socket emit site.
- // The Wave 4 matcher arms catch the literal resolver phrases that
- // the original `dns error` substring would miss when reqwest's
- // wrapper isn't in the chain (e.g. tungstenite IO errors).
- assert_eq!(
- expected_error_kind(
- "[socket] Connection failed (sustained outage after 5 attempts): \
- WebSocket connect: IO error: failed to lookup address information: \
- nodename nor servname provided, or not known"
- ),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
-
- // OPENHUMAN-TAURI-4P (~66 events): tungstenite renders a captive
- // portal / corporate proxy that intercepts the WS handshake as
- // `WsError::Http(200)` → `"HTTP error: 200 OK"`. Classify as
- // network-unreachable since no amount of app-side retry can pierce
- // an intercepting proxy.
- assert_eq!(
- expected_error_kind(
- "[socket] Connection failed (sustained outage after 5 attempts): \
- WebSocket connect: HTTP error: 200 OK"
- ),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
- }
-
- #[test]
- fn http_200_classifier_does_not_silence_unrelated_log_lines() {
- // The captive-portal arm anchors on `"http error: 200 ok"` (the
- // exact tungstenite `WsError::Http(200)` Display rendering).
- // Adjacent non-WebSocket log lines that mention `"HTTP/1.1 200 OK"`
- // or `"status: 200 OK"` MUST NOT classify — those are normal-flow
- // success traces, not failure events. Pin this precedence so a
- // future refactor doesn't broaden the substring.
- assert_eq!(expected_error_kind("HTTP/1.1 200 OK"), None);
- assert_eq!(
- expected_error_kind("upstream returned status: 200 OK after retry"),
- None
- );
- }
-
- #[test]
- fn classifies_tls_handshake_eof_as_network_unreachable() {
- // TAURI-RUST-4ZD (first seen on `[email protected]+e8968077aeb5`,
- // Windows): `native-tls` renders a peer / firewall / antivirus /
- // corporate-proxy TCP close mid-TLS-handshake as
- // `"TLS error: native-tls error: unexpected EOF during handshake"`,
- // which `socket::ws_loop::run_connection` wraps as
- // `"WebSocket connect: <inner>"` and the supervisor's
- // sustained-outage escalation wraps again. The existing
- // `"tls handshake"` arm misses it because the words are not
- // contiguous in this render (`"tls error"` … `"during handshake"`).
- // Same user-environment shape as the other handshake-stage entries:
- // the socket supervisor already retries with exponential backoff and
- // Sentry has no actionable signal beyond that.
- assert_eq!(
- expected_error_kind(
- "[socket] Connection failed (sustained outage after 5 attempts): \
- WebSocket connect: TLS error: native-tls error: unexpected EOF during handshake"
- ),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
-
- // Bare native-tls render (no socket-supervisor wrap) — fires when the
- // same handshake EOF escapes through a non-supervisor call site. The
- // classifier runs on the full anyhow chain, so the shorter form must
- // also match.
- assert_eq!(
- expected_error_kind("TLS error: native-tls error: unexpected EOF during handshake"),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
- }
-
- #[test]
- fn classifies_ws_protocol_wrong_http_version_as_network_unreachable() {
- // CORE-RUST-DP (~2 events / 24h on `[email protected]+e8968077aeb5`,
- // self-hosted `core-rust`): tungstenite renders
- // `ProtocolError::WrongHttpVersion` as
- // `"WebSocket protocol error: HTTP version must be 1.1 or higher"`,
- // wrapped by `socket::ws_loop::run_connection` as
- // `"WebSocket connect: <inner>"` and then by the supervisor's
- // sustained-outage escalation as
- // `"[socket] Connection failed (sustained outage after N attempts):
- // WebSocket connect: WebSocket protocol error: HTTP version must be
- // 1.1 or higher"`.
- //
- // The handshake requires HTTP/1.1; a server or intermediary proxy
- // that responds with HTTP/2+ to the upgrade is misconfigured
- // upstream — same shape as the existing `"tls handshake"` /
- // `"certificate verify failed"` user-environment entries. The
- // supervisor already retries with exponential backoff; Sentry has
- // no actionable signal to add.
- assert_eq!(
- expected_error_kind(
- "[socket] Connection failed (sustained outage after 5 attempts): \
- WebSocket connect: WebSocket protocol error: HTTP version must be 1.1 or higher"
- ),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
-
- // Bare tungstenite render (no socket-supervisor wrap) — fires when
- // the same protocol error escapes through a non-supervisor call
- // site. The classifier runs on the full anyhow chain, so the
- // shorter form must also match.
- assert_eq!(
- expected_error_kind("WebSocket protocol error: HTTP version must be 1.1 or higher"),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
- }
-
- #[test]
- fn tls_handshake_eof_anchor_does_not_silence_unrelated_log_lines() {
- // The anchor is the literal `"unexpected eof during handshake"`
- // phrase. A bare data-phase `"unexpected EOF"` (server closed
- // mid-stream, parser truncation, …) MUST NOT classify — those are
- // outside the handshake stage and may carry actionable signal. Pin
- // the rejection contract so a future refactor doesn't loosen the
- // substring into a generic `"unexpected eof"` matcher.
- for raw in [
- "stream closed: unexpected EOF",
- "reqwest: unexpected EOF while reading body",
- "json parser: unexpected EOF at byte 1024",
- "decoder hit unexpected eof mid-frame",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "non-handshake unexpected-EOF log line must NOT classify: {raw}"
- );
- }
- }
-
- #[test]
- fn wrong_http_version_anchor_does_not_silence_unrelated_log_lines() {
- // The anchor is the literal tungstenite Display string. Adjacent
- // log lines that mention HTTP version in any other context
- // (`"upgrading from HTTP/1.0 to HTTP/2"`, `"HTTP/1.1 only"`,
- // `"server requires HTTP version 2.0"`) MUST NOT classify — those
- // are unrelated transport / negotiation traces and may carry
- // actionable signal. Pin the rejection contract so a future
- // refactor doesn't loosen the substring into a generic
- // `"http version"` matcher.
- for raw in [
- "[transport] upgrading from HTTP/1.0 to HTTP/2",
- "server advertises HTTP version 2.0 (h2 alpn)",
- "client supports HTTP/1.1 only",
- "version mismatch: requires HTTP/1.2 or higher",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "unrelated HTTP-version log line must NOT classify: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_transient_upstream_http_errors() {
- // OPENHUMAN-TAURI-5Z: the canonical shape emitted by
- // `providers::ops::api_error` and re-raised through `agent.run_single`.
- assert_eq!(
- expected_error_kind("OpenHuman API error (504 Gateway Timeout): error code: 504"),
- Some(ExpectedErrorKind::TransientUpstreamHttp)
- );
-
- // Every transient code must classify, whether the status renders as
- // bare digits or "<digits> <reason>".
- for raw in [
- "OpenHuman API error (408): request timeout",
- "OpenAI API error (429 Too Many Requests): rate limit",
- "Anthropic API error (502 Bad Gateway): upstream unhealthy",
- "custom_openai API error (502 Bad Gateway): upstream gateway blip",
- "OpenHuman API error (503): service unavailable",
- "Provider API error (504): upstream timed out",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::TransientUpstreamHttp),
- "should classify as transient upstream HTTP: {raw}"
- );
- }
-
- // Wrapped in an anyhow chain (as it reaches the agent layer) must
- // still classify — `expected_error_kind` is substring-based.
- assert_eq!(
- expected_error_kind(
- "agent turn failed: OpenHuman API error (504 Gateway Timeout): \
- error code: 504"
- ),
- Some(ExpectedErrorKind::TransientUpstreamHttp)
- );
-
- // TAURI-RUST-H (~1360 events, 504) / TAURI-RUST-2T (~310 events, 502):
- // legacy no-paren wire shape from older `embeddings::openai` /
- // `embeddings::cohere` emit-site formats that predate the
- // parenthesised `({status})` rendering. Anchored on the trailing
- // space after the status code so unrelated digit runs don't match.
- for raw in [
- "Embedding API error 504 Gateway Timeout: error code: 504",
- "Embedding API error 502 Bad Gateway: error code: 502",
- "Cohere embed API error 503 Service Unavailable: error code: 503",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::TransientUpstreamHttp),
- "should classify legacy no-paren transient shape: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_unrelated_digit_runs_as_transient() {
- // The legacy no-paren matcher anchors `api error <code> ` with a
- // trailing space so adjacent digit runs (`api error 5042…`) and
- // non-transient codes (400/401/403/404) don't get silenced.
- assert_eq!(
- expected_error_kind("OpenHuman API error 400 Bad Request: malformed body"),
- None
- );
- assert_eq!(
- expected_error_kind("provider returned api error 5042 (custom internal sentinel)"),
- None
- );
- }
-
- #[test]
- fn integrations_post_composio_timeout_dropped() {
- // OPENHUMAN-TAURI-18 / -G regression guard. The integrations
- // client at `crate::integrations::client::IntegrationClient::post`
- // builds the reqwest error chain and routes it through
- // `report_error_or_expected(.., "integrations", "post", &[("failure",
- // "transport")])`. The chain text contains the
- // `"error sending request for url"` anchor so
- // `is_network_unreachable_message` matches first and demotes to
- // `NetworkUnreachable` (functionally equivalent to
- // `TransientUpstreamHttp` for Sentry suppression — both routes
- // skip the report path via `report_expected_message`).
- //
- // Pinning this exact wire shape catches a future refactor that
- // drops the URL anchor (e.g. a chain-flatten helper that strips
- // it for "PII safety"), which would silently re-open the leak.
- let chain = "error sending request for url \
- (https://api.tinyhumans.ai/agent-integrations/composio/execute) → \
- client error (SendRequest) → connection error → \
- Operation timed out (os error 60)";
- assert_eq!(
- expected_error_kind(chain),
- Some(ExpectedErrorKind::NetworkUnreachable),
- "TAURI-18 chain shape must classify as NetworkUnreachable"
- );
-
- // If the URL anchor is ever dropped, the transport-phrase
- // fallback (`operation timed out` from
- // `TRANSIENT_TRANSPORT_PHRASES`) catches it via the message
- // classifier helper used at upstream re-emit sites — confirm
- // both paths so the regression surface is fully pinned.
- assert!(
- is_transient_message_failure(chain),
- "TAURI-18 chain must also satisfy upstream message classifier \
- (defense-in-depth for sites that lose the URL anchor)"
- );
- }
-
- #[test]
- fn channel_supervisor_operation_timed_out_classifies_as_expected() {
- // OPENHUMAN-TAURI-EM (128 events) + TAURI-RUST-15/-BB: `channels::runtime::supervision`
- // wraps a channel listener failure as
- // `format!("Channel {} error: {e:#}; restarting", ch.name())` and
- // routes the message through `report_error_or_expected`. The
- // newer `ChannelSupervisorRestart` classifier (added for the
- // broader 11.4k-event Sentry leak) anchors on the supervisor
- // wrapper shape itself — `"Channel <name> error: …; restarting"`
- // — and takes precedence over `NetworkUnreachable`. That single
- // arm now covers every ETIMEDOUT / WSAETIMEDOUT / hyper-prose
- // shape the old narrower anchor pinned, plus OS-localized
- // variants the English-only `NetworkUnreachable` would miss.
- //
- // Demotion tier difference: `ChannelSupervisorRestart` emits at
- // `info!` (breadcrumb only, no Sentry event) where
- // `NetworkUnreachable` emitted at `warn!` (still captured as a
- // Sentry warn event). Sustained outages still page via
- // `health.bus` / `FAIL_ESCALATE_THRESHOLD`.
- for raw in [
- // macOS (os error 60 = ETIMEDOUT on BSD)
- "Channel discord error: IO error: Operation timed out (os error 60); restarting",
- // Linux (os error 110 = ETIMEDOUT)
- "Channel discord error: IO error: Operation timed out (os error 110); restarting",
- // Windows (os error 10060 = WSAETIMEDOUT)
- "Channel discord error: IO error: Operation timed out (os error 10060); restarting",
- // Same shape on other channels — supervisor wrapper is provider-agnostic.
- "Channel slack error: IO error: Operation timed out (os error 60); restarting",
- "Channel telegram error: IO error: Operation timed out (os error 110); restarting",
- // Bare prose form (no errno suffix) from hyper / tungstenite layers
- // that render `std::io::Error` without `raw_os_error()`.
- "Channel discord error: WebSocket connect: IO error: Operation timed out; restarting",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ChannelSupervisorRestart),
- "channel supervisor timeout shape must classify as ChannelSupervisorRestart \
- (precedence over NetworkUnreachable; got {:?} for {raw:?})",
- expected_error_kind(raw)
- );
- }
- }
-
- #[test]
- fn operation_timed_out_negative_cases_still_report() {
- // Counter-case: a configuration/validation message that mentions
- // "timeout" as a knob name (not transport state) and has no other
- // classifier anchor must still reach Sentry. The substring chosen
- // for the new matcher is `"operation timed out"`, not `"timeout"`,
- // precisely so unrelated mentions of the word do not collide.
- assert_eq!(
- expected_error_kind("config rejected: timeout must be a positive integer"),
- None,
- "config validation noise (no 'operation timed out' anchor) must still reach Sentry"
- );
- // Bare empty string — no anchors at all.
- assert_eq!(expected_error_kind(""), None);
- }
-
- #[test]
- fn channels_dispatch_re_emit_of_provider_502_classifies_as_transient() {
- // OPENHUMAN-TAURI-4F (~157 events) / -1C (~87 events) / -8F
- // (~39 events): the reliable provider layer retried 5xx, the
- // agent re-raised the error, and `channels::runtime::dispatch`
- // re-emitted it under `domain="channels", operation="dispatch_llm_error"`
- // via raw `report_error` (which skips classification). Switching
- // that site to `report_error_or_expected` routes the chain
- // through this classifier — but only works if the canonical
- // `"OpenHuman API error (NNN ...)"` substring still anchors the
- // match through the channels-layer wrapping.
- //
- // The wrapping shape at the dispatch site is the agent error
- // chain rendered via `format!("{e:#}")`. For a backend 502 from
- // `providers::ops::api_error`, that resolves to:
- // "OpenHuman API error (502 Bad Gateway): error code: 502"
- // possibly prepended with a runner / iteration prefix. Both
- // shapes must classify as transient so the dispatch re-emit
- // gets demoted.
- for raw in [
- "OpenHuman API error (502 Bad Gateway): error code: 502",
- "agent.provider_chat failed: OpenHuman API error (503 Service Unavailable): retry budget exhausted",
- "all providers exhausted: OpenHuman API error (504 Gateway Timeout): error code: 504",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::TransientUpstreamHttp),
- "channels.dispatch re-emit of {raw:?} must classify as transient"
- );
- }
- }
-
- #[test]
- fn classifies_socket_transient_http_errors() {
- // OPENHUMAN-TAURI-5P / -EZ: tungstenite's `WsError::Http(response)`
- // surfaces during the WebSocket upgrade handshake when the backend
- // load balancer returns 502 / 504. The socket reconnect loop wraps
- // it as `format!("WebSocket connect: {e}")`, producing
- // `"WebSocket connect: HTTP error: <status> <reason>"`. Each
- // sustained-outage threshold escalation routes the formatted reason
- // through `report_error_or_expected`, which must classify as
- // transient so the per-client noise stops reaching Sentry.
- for raw in [
- "WebSocket connect: HTTP error: 502 Bad Gateway",
- "WebSocket connect: HTTP error: 503 Service Unavailable",
- "WebSocket connect: HTTP error: 504 Gateway Timeout",
- "[socket] Connection failed (sustained outage after 5 attempts): \
- WebSocket connect: HTTP error: 502 Bad Gateway",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::TransientUpstreamHttp),
- "should classify as transient upstream HTTP (socket shape): {raw}"
- );
- }
-
- // Trailing-colon separator (chained error formatting).
- // Note: avoid words like "connection refused" or "timeout" in the
- // suffix — those would also match `is_network_unreachable_message` /
- // `TRANSIENT_TRANSPORT_PHRASES` and the order in `expected_error_kind`
- // would route through `NetworkUnreachable` first, defeating the
- // assertion. Both classifications silence the event so production
- // behavior is identical, but the test is anchored on the canonical
- // socket shape so a future regression in `is_transient_upstream_http_message`
- // surfaces here, not behind another classifier.
- assert_eq!(
- expected_error_kind(
- "WebSocket connect: HTTP error: 502: upstream returned bad gateway"
- ),
- Some(ExpectedErrorKind::TransientUpstreamHttp)
- );
-
- // Trailing-newline separator (multi-line error chain).
- assert_eq!(
- expected_error_kind("WebSocket connect: HTTP error: 504\nupstream gateway"),
- Some(ExpectedErrorKind::TransientUpstreamHttp)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_http_error_text_as_transient_socket() {
- // Bare numeric "HTTP error: 5023" (port number, runbook ID) without
- // a separator must NOT silence — pin the matcher to space/newline/colon.
- assert_eq!(expected_error_kind("HTTP error: 5023"), None);
- // Non-transient HTTP statuses must not match — `WsError::Http` for
- // a 401 / 403 / 404 is genuinely actionable (auth / routing bug).
- for raw in [
- "WebSocket connect: HTTP error: 401 Unauthorized",
- "WebSocket connect: HTTP error: 403 Forbidden",
- "WebSocket connect: HTTP error: 404 Not Found",
- "WebSocket connect: HTTP error: 500 Internal Server Error",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "must NOT silence actionable socket HTTP error: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_actionable_provider_errors_as_transient_upstream() {
- // 4xx (other than 408/429) and non-transient 5xx must continue to
- // reach Sentry — those are real bugs (wrong model name, malformed
- // request, internal exception) that need to be triaged.
- for raw in [
- "OpenAI API error (400): bad request",
- "OpenAI API error (401): unauthorized",
- "OpenAI API error (403): forbidden",
- "OpenAI API error (404): model not found",
- "OpenAI API error (500): internal server error",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "must NOT silence actionable provider error: {raw}"
- );
- }
-
- // A free-form message that merely mentions "504" without the
- // `api error (` prefix must not be classified — pin the match to
- // the canonical shape from `ops::api_error`.
- assert_eq!(
- expected_error_kind("see runbook for 504 handling at https://example.com/504"),
- None
- );
- }
-
- #[test]
- fn classifies_backend_user_error_responses() {
- // OPENHUMAN-TAURI-BC: SharePoint authorize 400 because the user
- // didn't fill in the required Tenant Name field. After the
- // ProviderUserState classifier was added (#1472 wave E), this
- // canonical shape now lands in the more specific
- // ProviderUserState bucket — `"missing required fields"` wins
- // over the generic 4xx matcher. Either expected-kind silences
- // Sentry; the dedicated bucket gives operators a finer-grained
- // `kind="provider_user_state"` info-log facet for triage.
- let bc = "Backend returned 400 Bad Request for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/authorize: \
- Composio authorization failed: 400 \
- {\"error\":{\"message\":\"Missing required fields: Tenant Name\",\
- \"slug\":\"ConnectedAccount_MissingRequiredFields\",\"status\":400}}";
- assert_eq!(
- expected_error_kind(bc),
- Some(ExpectedErrorKind::ProviderUserState),
- "OPENHUMAN-TAURI-BC wire shape must classify as ProviderUserState (the \
- more specific bucket once #1472 wave E added it)"
- );
-
- // Cover the rest of the 4xx surface produced by integrations /
- // composio clients — all user-input / auth-state failures that
- // Sentry can't action.
- for raw in [
- "Backend returned 400 Bad Request for POST https://api.example.com/x: bad input",
- "Backend returned 401 Unauthorized for GET https://api.example.com/x: token expired",
- "Backend returned 403 Forbidden for GET https://api.example.com/x: permission denied",
- "Backend returned 404 Not Found for GET https://api.example.com/x: missing",
- "Backend returned 422 Unprocessable Entity for POST https://api.example.com/x: validation failed",
- "Backend returned 451 Unavailable for Legal Reasons for GET https://api.example.com/x: blocked",
- // Lowercased context wrapping is irrelevant — substring match is case-insensitive.
- "[observability] integrations.post failed: Backend returned 400 Bad Request for POST https://api.tinyhumans.ai/x: detail",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::BackendUserError),
- "must classify as backend user-error: {raw}"
- );
- }
- }
-
- #[test]
- fn tool_execute_backend_401_invalid_token_does_not_hard_report() {
- // TAURI-RUST-84E: the integrations client demotes its backend 401 via
- // `report_error_or_expected`, but ALSO `anyhow::bail!`s it. The error
- // bubbles to the agent tool-execute loop
- // (`agent::harness::engine::tools::run_one_tool`'s `Ok(Err(e))` arm),
- // which previously called the unconditional `report_error` — a second,
- // hard Sentry event (domain=tool / operation=execute) for an
- // already-classified user-end invalid-token condition. The arm now
- // routes through `report_error_or_expected`; this test pins the exact
- // wire shape so a classifier regression that lets the 401 escape (and
- // resume double-reporting) fails CI.
- //
- // Mirror the tool-execute call path: the integrations client bails with
- // `anyhow::anyhow!("Backend returned {status} for POST {url}: {detail}")`,
- // the agent arm renders it with `{e:#}`, then `report_error_or_expected`
- // consults `expected_error_kind`. Assert that classifier returns the
- // expected user-state bucket (so the report is demoted, not hard).
- let e = anyhow::anyhow!(
- "Backend returned 401 Unauthorized for POST \
- https://api.tinyhumans.ai/agent-integrations/parallel/search: Invalid token"
- );
- assert_eq!(
- expected_error_kind(&format!("{e:#}")),
- Some(ExpectedErrorKind::BackendUserError),
- "the 84E tool-execute backend-401 wire shape must classify as expected \
- user-state so report_error_or_expected demotes it instead of firing a \
- hard tool/execute Sentry event"
- );
-
- // A genuine tool failure (no classifier arm) must keep surfacing as a
- // hard error — confirm routing ALL tool errors through
- // `report_error_or_expected` does not silently swallow real failures.
- assert_eq!(
- expected_error_kind("tool 'web_search' panicked: index out of bounds"),
- None,
- "a genuine tool failure must NOT be classified as expected — it still \
- reaches Sentry as a hard error"
- );
- }
-
- #[test]
- fn does_not_classify_transient_or_server_backend_errors_as_user_error() {
- // 408 / 429 are transient — they belong to the
- // upstream-transient bucket (or are retried at the caller), not
- // the user-error bucket. A sustained 429 (rate limit cliff) MUST
- // still surface so we can react.
- for raw in [
- "Backend returned 408 Request Timeout for POST https://api.example.com/x: timeout",
- "Backend returned 429 Too Many Requests for POST https://api.example.com/x: slow down",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "transient 4xx must NOT be classified as user-error: {raw}"
- );
- }
-
- // 5xx is always actionable — server bugs need to reach Sentry.
- for raw in [
- "Backend returned 500 Internal Server Error for POST https://api.example.com/x: oops",
- "Backend returned 502 Bad Gateway for POST https://api.example.com/x: upstream down",
- "Backend returned 503 Service Unavailable for POST https://api.example.com/x: maintenance",
- "Backend returned 504 Gateway Timeout for POST https://api.example.com/x: slow upstream",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "5xx must NOT be classified as user-error: {raw}"
- );
- }
-
- // A free-form message that mentions "400" but doesn't follow the
- // `Backend returned <status>` prefix from the integrations /
- // composio clients must not be silenced.
- assert_eq!(
- expected_error_kind("see HTTP 400 specification at https://example.com/400"),
- None
- );
- assert_eq!(
- expected_error_kind("OpenAI API error (400): bad request"),
- None,
- "provider-formatted 4xx must keep going through the provider classifier path"
- );
- }
-
- #[test]
- fn classifies_trigger_type_not_found_as_provider_user_state() {
- // OPENHUMAN-TAURI-3R / -3S: composio enable_trigger when the slug
- // isn't in the trigger registry. Backend wraps the upstream
- // composio 4xx as 500, so this would otherwise escape the
- // 4xx-only `is_backend_user_error_message` matcher.
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/triggers: \
- Trigger type GITHUB_PUSH_EVENT not found"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Wrapped by `rpc.invoke_method` / `[composio] sync(toolkit) failed: …`
- // — substring match must survive caller context.
- assert_eq!(
- expected_error_kind(
- "rpc.invoke_method failed: Backend returned 500 Internal Server Error \
- for POST /agent-integrations/composio/triggers: \
- Trigger type SLACK_NEW_MESSAGE not found"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Alternate phrasing observed from the same cluster.
- assert_eq!(
- expected_error_kind(
- "composio: Cannot enable trigger 'GITHUB_PUSH_EVENT': trigger not found in registry"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- #[test]
- fn classifies_toolkit_not_enabled_as_provider_user_state() {
- // OPENHUMAN-TAURI-34: 400 from composio because the user hasn't
- // enabled the toolkit. Must classify as ProviderUserState (more
- // specific) rather than the generic BackendUserError bucket — the
- // ordering in `expected_error_kind` enforces that.
- let msg = "Backend returned 400 Bad Request for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/execute: \
- Toolkit \"get\" is not enabled";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Wrapped variant (anyhow chain through the agent runtime).
- assert_eq!(
- expected_error_kind(
- "tool.invoke failed: Backend returned 400 Bad Request for POST \
- /agent-integrations/composio/execute: Toolkit \"linear\" is not enabled \
- for this account"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- #[test]
- fn classifies_custom_openai_upstream_bad_request_as_provider_user_state() {
- assert_eq!(
- expected_error_kind(
- "custom_openai API error (400 Bad Request): \
- {\"error\":{\"message\":\"Bad request to upstream provider\",\
- \"type\":\"upstream_error\",\"status\":400}}"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Wrapped by higher-level callers (`agent.run_single`,
- // `rpc.invoke_method`) must still classify.
- assert_eq!(
- expected_error_kind(
- "agent.run_single failed: custom_openai API error (400 Bad Request): \
- {\"error\":{\"message\":\"Bad request to upstream provider\",\
- \"type\":\"upstream_error\",\"status\":400}}"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- /// Regression for CodeRabbit feedback on PR #2107: the matcher must
- /// not demote unrelated errors that happen to contain both
- /// "bad request to upstream provider" and "upstream_error" without
- /// the `custom_openai API error (400` anchor.
- #[test]
- fn does_not_silence_unrelated_error_with_only_inner_substrings() {
- // No `custom_openai API error (400` prefix → must NOT classify
- // as ProviderUserState, otherwise we'd silence actionable bugs.
- assert_eq!(
- expected_error_kind(
- "internal panic in router: bad request to upstream provider \
- (state=upstream_error)"
- ),
- None,
- );
-
- // A future hypothetical provider envelope reusing one substring
- // also must not classify.
- assert_eq!(
- expected_error_kind(
- "anthropic_api error: upstream_error encountered while \
- forwarding bad request to upstream provider"
- ),
- None,
- );
- }
-
- #[test]
- fn classifies_missing_required_fields_as_provider_user_state() {
- // OPENHUMAN-TAURI-97: composio authorize with a blank required
- // field. Backend wraps the composio 400 as 500 with the inner
- // body embedded as a JSON-stringified error message.
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for POST \
- https://api.tinyhumans.ai/agent-integrations/composio/authorize: \
- 400 {\"error\":{\"message\":\"Missing required fields: Your Subdomain\"}}"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Sibling toolkits surface the same shape with different field names.
- for raw in [
- "Backend returned 500 Internal Server Error for POST /authorize: Missing required fields: WABA ID",
- "Backend returned 500 Internal Server Error for POST /authorize: Missing required fields: Tenant Name",
- "Backend returned 400 Bad Request for POST /authorize: Missing required fields: Domain URL",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderUserState),
- "missing-required-fields shape must classify: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_insufficient_scopes_as_provider_user_state() {
- // OPENHUMAN-TAURI-33: gmail sync surfaced the upstream Google
- // OAuth scopes error verbatim through composio. Reaches the RPC
- // dispatch site via `[composio] sync(gmail) failed: [composio:gmail]
- // GMAIL_FETCH_EMAILS page 0: HTTP 403: Request had insufficient
- // authentication scopes.`.
- assert_eq!(
- expected_error_kind(
- "[composio:gmail] GMAIL_FETCH_EMAILS page 0: HTTP 403: \
- Request had insufficient authentication scopes."
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- // Bare upstream shape (in case any future caller forwards without
- // the gmail prefix).
- assert_eq!(
- expected_error_kind("HTTP 403: Request had insufficient authentication scopes."),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- #[test]
- fn classifies_access_terminated_provider_policy_as_provider_user_state() {
- assert_eq!(
- expected_error_kind(
- "custom_openai API error (403 Forbidden): {\"error\":{\"message\":\"Kimi For Coding is currently only available for Coding Agents such as Kimi CLI, Claude Code, Roo Code, Kilo Code, etc.\",\"type\":\"access_terminated_error\"}}"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
-
- assert_eq!(
- expected_error_kind(
- "agent turn failed: custom_openai API error (403): currently only available for coding agents"
- ),
- Some(ExpectedErrorKind::ProviderUserState)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_500s_as_provider_user_state() {
- // Sanity check: a generic 500 with no provider-user-state body
- // shape must continue to reach Sentry as an actionable event.
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for POST \
- /agent-integrations/composio/triggers: random panic in handler"
- ),
- None
- );
- assert_eq!(
- expected_error_kind(
- "Backend returned 500 Internal Server Error for GET /teams: database connection lost"
- ),
- None
- );
-
- // Free-form text that mentions "not found" / "is not enabled" out
- // of context must not be silenced.
- assert_eq!(
- expected_error_kind("file not found at /tmp/x.json"),
- None,
- "bare 'not found' without 'trigger type' anchor must NOT classify"
- );
- assert_eq!(
- expected_error_kind("the cache is not enabled in this build"),
- None,
- "bare 'is not enabled' without 'toolkit ' anchor must NOT classify"
- );
- }
-
- #[test]
- fn classifies_provider_config_rejection() {
- // #2079 — an OpenHuman abstract tier alias leaked to a custom
- // provider; raised again by `agent.run_single` /
- // `web_channel.run_chat_task` so it escapes the provider-layer
- // demotion and reaches `report_error_or_expected` here.
- assert_eq!(
- expected_error_kind(
- "agent.run_single failed: custom_openai API error (400 Bad Request): \
- The supported API model names are deepseek-v4-pro or deepseek-v4-flash, \
- but you passed reasoning-v1."
- ),
- Some(ExpectedErrorKind::ProviderConfigRejection)
- );
- // #2076 — Moonshot Kimi K2 temperature constraint.
- assert_eq!(
- expected_error_kind(
- "custom_openai API error (400): invalid temperature: only 1 is allowed for this model"
- ),
- Some(ExpectedErrorKind::ProviderConfigRejection)
- );
- // #2202 — unknown / stale model pin (OpenAI-compatible body).
- assert_eq!(
- expected_error_kind(
- "custom_openai API error (400): Model 'claude-opus-4-7' is not available. \
- Use GET /openai/v1/models to list available models."
- ),
- Some(ExpectedErrorKind::ProviderConfigRejection)
- );
- }
-
- #[test]
- fn classifies_embedding_endpoint_absent_as_config_rejection() {
- // TAURI-RUST-5JR — custom embeddings provider pointed at a chat-only
- // base URL (DeepSeek) that has no `/embeddings` route. Verbatim shape
- // produced by `crates/openhuman-core/src/inference/embeddings/openai.rs` (prefix preserved
- // even after the actionable-hint suffix is appended).
- assert_eq!(
- expected_error_kind(
- "Embedding API error (404 Not Found): <html>not found</html> \
- — this endpoint has no embeddings API; pick an embeddings-capable \
- provider in Settings → Memory"
- ),
- Some(ExpectedErrorKind::ProviderConfigRejection)
- );
- // 405 Method Not Allowed — route exists for GET only / wrong verb.
- assert_eq!(
- expected_error_kind("Embedding API error (405 Method Not Allowed): {}"),
- Some(ExpectedErrorKind::ProviderConfigRejection)
- );
- }
-
- #[test]
- fn does_not_demote_real_embedding_server_faults() {
- // Polarity guard: a 500 from a VALID embeddings endpoint is a real
- // server fault and must keep reaching Sentry — not demoted.
- assert_eq!(
- expected_error_kind("Embedding API error (500 Internal Server Error): upstream boom"),
- None,
- "embedding 500 is a real fault and must stay in Sentry"
- );
- // A 400 (e.g. oversized input — TAURI-RUST-4SA) is prevented at source
- // by the chunk cap (#3598); a residual 400 must stay visible, NOT be
- // swallowed by the 404/405-scoped endpoint-absent arm.
- assert_eq!(
- expected_error_kind(
- "Embedding API error (400 Bad Request): {\"error\":{\"message\":\
- \"maximum input length is 8192 tokens.\"}}"
- ),
- None,
- "embedding 400 must NOT be demoted by the endpoint-absent (404/405) arm"
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_provider_failures_as_config_rejection() {
- // Inverted polarity / scope guard: a 5xx or a generic 4xx with no
- // config-rejection body must still reach Sentry as actionable.
- // (The OpenHuman backend never emits these phrases, so the
- // message-level predicate is intrinsically custom-provider scoped;
- // the HTTP-layer twin enforces the non-backend guard explicitly.)
- assert_eq!(
- expected_error_kind("custom_openai API error (500): internal server error"),
- None
- );
- assert_eq!(
- expected_error_kind(
- "custom_openai API error (400 Bad Request): missing required field 'messages'"
- ),
- None,
- "generic 4xx without a config-rejection body must NOT demote"
- );
- }
-
- #[test]
- fn unrelated_missing_required_fields_classifies_as_accepted_false_positive() {
- // Documents the breadth of the `"missing required fields"` arm —
- // unlike the trigger/toolkit arms it has no second anchor, so a
- // non-composio call site whose error happens to contain the phrase
- // will also demote. This is the accepted false-positive surface
- // per the classifier doc-comment (every current emit site is
- // scoped to composio/integrations envelopes, so a stray collision
- // would have to come from a brand-new opt-in call site).
- //
- // Pinning this assertion locks the breadth in so a future
- // narrowing of the matcher surfaces here instead of silently
- // re-bucketing the demote path.
- assert_eq!(
- expected_error_kind("Internal error: missing required fields in config"),
- Some(ExpectedErrorKind::ProviderUserState),
- "accepted false-positive: bare 'missing required fields' demotes by design"
- );
- }
-
- #[test]
- fn provider_user_state_takes_precedence_over_backend_user_error() {
- // Critical ordering guarantee: a 4xx body that contains the
- // toolkit-not-enabled phrasing must land in `ProviderUserState`
- // (more specific) — not in the generic `BackendUserError` bucket.
- // Without the ordering in `expected_error_kind`, the 4xx matcher
- // would win and the operator would see a different breadcrumb
- // kind than intended (and miss the `kind="provider_user_state"`
- // tag in info logs).
- let msg = "Backend returned 400 Bad Request for POST \
- /agent-integrations/composio/execute: \
- Toolkit \"github\" is not enabled";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "4xx + toolkit-not-enabled must land in ProviderUserState, not BackendUserError"
- );
- }
-
- // ── TAURI-RUST-X9 (#1166): composio-direct 401 / Invalid API key ────
-
- #[test]
- fn classifies_composio_direct_invalid_api_key_as_provider_user_state() {
- // Canonical Sentry TAURI-RUST-X9 wire shape — the verbatim title
- // body from the issue, captured 15,732 times in ~22h on a single
- // user with a bad direct-mode key. The classifier must demote
- // this to `ProviderUserState` so the polling layer's 5 s retry
- // doesn't keep flooding Sentry.
- let msg = "[composio-direct] list_connections failed: \
- Composio v3 connected_accounts failed: \
- HTTP 401: Invalid API key: ak_VsUvq*****";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "composio-direct HTTP 401 + Invalid API key must demote to ProviderUserState"
- );
- }
-
- #[test]
- fn classifies_composio_direct_invalid_api_key_for_other_ops() {
- // Same arm must cover every op-name the direct branches emit —
- // not just `list_connections`. The matcher gates on the
- // `[composio-direct]` prefix, not on a specific op string, so
- // `list_tools` / `authorize` / `list_connections` all demote.
- let shapes = [
- // list_tools prefetch fails before the actual list_tools call
- "[composio-direct] list_tools: prefetch connections failed: \
- Composio v3 connected_accounts failed: HTTP 401: Invalid API key: ak_…",
- // direct authorize hits the v3 /connected_accounts/link wall
- "[composio-direct] authorize failed: \
- Composio v3 connected_accounts/link failed: HTTP 401: Invalid API key: ak_…",
- // direct list_tools itself
- "[composio-direct] list_tools failed: \
- Composio v3 tools failed: HTTP 401: Invalid API key: ak_…",
- // periodic-tick rendering (no "[composio-direct]" prefix because
- // periodic.rs wraps differently, but the failure still gets the
- // hook — handled by ops.rs's report path, not the
- // expected_error_kind body shape, so we only verify the
- // composio-direct branch here)
- ];
- for msg in shapes {
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "every [composio-direct] op with HTTP 401 / Invalid API key must demote: {msg}"
- );
- }
- }
-
- #[test]
- fn classifies_composio_direct_with_invalid_api_key_only_no_http_401() {
- // The matcher accepts EITHER `HTTP 401` OR `Invalid API key`
- // alongside the `[composio-direct]` prefix. Catches the wire
- // shape variant where the body anchor lands but the status text
- // is rendered differently (e.g. "401 Unauthorized" instead of
- // "HTTP 401") — same user-state condition.
- let msg = "[composio-direct] list_connections failed: \
- Composio v3 connected_accounts failed: \
- 401 Unauthorized: Invalid API key: ak_…";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "composio-direct + Invalid API key body must demote even without literal 'HTTP 401'"
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_http_401_as_composio_direct_user_state() {
- // Discrimination test: a generic 401 that does NOT carry the
- // `[composio-direct]` prefix must NOT match this arm. This
- // protects against the arm accidentally swallowing backend-mode
- // composio 401s, unrelated integration 401s, or any other
- // 401-containing message that lacks the direct-mode anchor.
- //
- // The backend-mode shape is `Backend returned 401 …`; it does
- // not contain `[composio-direct]`, so the new arm rightly skips
- // it. Backend-mode 401s remain a real Sentry signal (bad
- // service-to-service auth, expired token, etc.).
- let backend_401 = "[composio] list_connections failed: \
- Backend returned 401 Unauthorized for GET \
- https://api.tinyhumans.ai/agent-integrations/composio/connections: \
- Invalid API key";
- assert_ne!(
- expected_error_kind(backend_401),
- Some(ExpectedErrorKind::ProviderUserState),
- "backend-mode 401 must NOT demote via the composio-direct arm"
- );
-
- let unrelated_401 = "GitHub API error: HTTP 401: Bad credentials";
- assert_ne!(
- expected_error_kind(unrelated_401),
- Some(ExpectedErrorKind::ProviderUserState),
- "unrelated 401 (no [composio-direct] anchor) must NOT match the composio-direct arm"
- );
- }
-
- // ── TAURI-RUST-K27: composio set-key validation prose (sibling of X9) ──
-
- #[test]
- fn demotes_composio_set_key_invalid_key_rejection() {
- // Drift coupler: assert the classifier demotes the EXACT const the
- // `composio_set_api_key` validate-before-store probe returns. Keying
- // off the shared const (not a copied literal) means any reword that
- // drops the `"Invalid Composio API key"` anchor fails this test in CI
- // instead of silently re-opening the TAURI-RUST-K27 leak.
- assert_eq!(
- expected_error_kind(
- crate::integrations::composio::direct_auth::COMPOSIO_INVALID_API_KEY_USER_MESSAGE
- ),
- Some(ExpectedErrorKind::ProviderUserState),
- "composio_set_api_key invalid-key rejection must demote to ProviderUserState"
- );
- }
-
- #[test]
- fn composio_set_key_anchor_is_substring_of_message() {
- // Contract coupler: the classifier keys on the shared
- // `COMPOSIO_INVALID_API_KEY_ANCHOR`; it is only correct if that anchor is a
- // genuine lowercase substring of the message the probe returns. Assert the
- // two consts stay in sync so neither can be reworded independently.
- use crate::integrations::composio::direct_auth::{
- COMPOSIO_INVALID_API_KEY_ANCHOR, COMPOSIO_INVALID_API_KEY_USER_MESSAGE,
- };
- assert!(
- COMPOSIO_INVALID_API_KEY_USER_MESSAGE
- .to_lowercase()
- .contains(COMPOSIO_INVALID_API_KEY_ANCHOR),
- "the K27 anchor must be a lowercase substring of the user message"
- );
- }
-
- #[test]
- fn does_not_classify_composio_set_key_store_failure_as_user_state() {
- // Discrimination: a genuine defect on the set path — the key validated
- // but persistence/config-save failed — renders a different body and
- // MUST still page. The K27 arm keys on "invalid composio api key",
- // which these do not contain, so they fall through to `None`.
- let store_fail = "[composio-direct] store_composio_api_key failed: \
- keyring write denied (os error 5)";
- let save_fail = "[composio-direct] save config failed: \
- config file is read-only";
- for msg in [store_fail, save_fail] {
- assert_eq!(
- expected_error_kind(msg),
- None,
- "genuine composio set-path failure must still reach Sentry: {msg}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_composio_direct_500_as_user_state() {
- // Real bug shapes — a 500 from the direct v3 path with no auth
- // body anchor — must still fall through to `None` so Sentry
- // sees them. Without this guard the arm could be too permissive
- // and silence genuine backend faults.
- let msg = "[composio-direct] list_connections failed: \
- Composio v3 connected_accounts failed: HTTP 500";
- assert_eq!(
- expected_error_kind(msg),
- None,
- "composio-direct 500 with no auth body must NOT demote — it is a real bug shape"
- );
- }
-
- // ── TAURI-RUST-34H: backend-wrapped Cloudflare anti-bot interstitial ─
-
- #[test]
- fn classifies_backend_cloudflare_antibot_wrap_as_provider_user_state() {
- // Canonical Sentry TAURI-RUST-34H wire shape — the verbatim title
- // body from the issue (8,851 events / 14d on self-hosted
- // `tauri-rust`). The backend wraps an upstream Cloudflare 403
- // anti-bot challenge as `Backend returned 500 … 403 <!DOCTYPE …
- // Just a moment... … cloudflare …`. The 500 escapes the 4xx-only
- // `is_backend_user_error_message` classifier, so this body-shape
- // arm catches it and demotes to `ProviderUserState`.
- let msg = r#"Backend returned 500 Internal Server Error for GET https://api.tinyhumans.ai/agent-integrations/composio/connections: 403 <!DOCTYPE html><html lang="en-US"><head><title>Just a moment...</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="robots" content="noindex,nofollow"><meta name="viewport" content="width=device-width,initial-scale=1"><link href="/cdn-cgi/styles/challenges.css" rel="stylesheet"></head><body class="no-js"><div class="main-wrapper" role="main"><div class="main-content"><h1 class="zone-name-title h1"><img class="heading-favicon" src="/favicon.ico" onerror="this.onerror=null;this.parentNode.removeChild(this)" alt="Icon for api.tinyhumans.ai">api.tinyhumans.ai</h1>...Powered by Cloudflare..."#;
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "backend-wrapped Cloudflare anti-bot interstitial must demote to ProviderUserState"
- );
- }
-
- #[test]
- fn classifies_minimal_cloudflare_antibot_body_as_provider_user_state() {
- // Strip the wire shape down to just the two anchors — the
- // matcher should still fire so future renderings (different
- // line breaks, stripped HTML, alternate caller wrappers) still
- // demote.
- let msg = "Just a moment...\ncloudflare\n";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::ProviderUserState),
- "minimal `Just a moment...` + `cloudflare` body must demote"
- );
- }
-
- #[test]
- fn does_not_classify_half_anchor_cloudflare_messages_as_user_state() {
- // Discrimination test for the double-anchor: either half on its
- // own must NOT match. This guards against unrelated bodies that
- // happen to use either phrase out of context.
-
- // Half-anchor 1: `just a moment` without `cloudflare` — e.g.
- // a daemon restart spinner blurb.
- let half_a = "Just a moment, while we restart the daemon";
- assert_ne!(
- expected_error_kind(half_a),
- Some(ExpectedErrorKind::ProviderUserState),
- "`Just a moment` without `cloudflare` must NOT match the CF anti-bot arm"
- );
-
- // Half-anchor 2: `cloudflare` without `just a moment...` — e.g.
- // a CF Workers footer mention elsewhere.
- let half_b = "Powered by Cloudflare";
- assert_ne!(
- expected_error_kind(half_b),
- Some(ExpectedErrorKind::ProviderUserState),
- "`cloudflare` without `Just a moment...` must NOT match the CF anti-bot arm"
- );
- }
-
- #[test]
- fn does_not_classify_genuine_backend_500_without_cloudflare_body() {
- // Real bug shape — a 500 from the same backend endpoint with no
- // Cloudflare interstitial body — must still fall through so
- // Sentry sees it. Without this guard the arm could be too
- // permissive and silence genuine database / handler faults.
- let msg = "Backend returned 500 Internal Server Error for GET \
- https://api.tinyhumans.ai/agent-integrations/composio/connections: \
- database connection pool exhausted";
- assert_eq!(
- expected_error_kind(msg),
- None,
- "genuine backend 500 without Cloudflare body must NOT demote — it is a real bug"
- );
- }
-
- #[test]
- fn classifies_list_models_404_as_provider_user_state() {
- // OPENHUMAN-TAURI-YJ: `inference/provider/ops.rs::list_models` probed
- // a custom-provider's `/models` endpoint and the upstream server
- // returned 404 because the base URL is wrong / doesn't host a models
- // listing. User-config state — the model-dropdown probe already
- // surfaces it inline. Pin the verbatim Sentry payload plus a few
- // body-shape variants (different upstreams emit different 404 bodies)
- // so the path-agnostic prefix anchor stays the source of truth.
- for raw in [
- // Verbatim shape from the Sentry event.
- r#"provider returned 404: {"error":"path \"/api/v1/models\" not found"}"#,
- // FastAPI-style: `{"detail":"Not Found"}`.
- r#"provider returned 404: {"detail":"Not Found"}"#,
- // Bare HTML — happens when the user pointed at a non-API origin
- // (e.g. the provider's docs site).
- "provider returned 404: <html><body>Not Found</body></html>",
- // After `truncate_with_ellipsis(.., 300)` clips a longer body —
- // prefix anchor must still match.
- r#"provider returned 404: {"error":{"message":"The requested URL /api/v1/models was not found on this server. Please check the URL or co…"#,
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderUserState),
- "OPENHUMAN-TAURI-YJ list_models 404 must classify as ProviderUserState: {raw}"
- );
- }
- }
-
- #[test]
- fn couples_list_models_404_source_shape_to_classifier() {
- // TAURI-RUST-8X3 coupling guard. Ties the TYPED SOURCE error shape
- // emitted by `inference/provider/ops/models.rs` (the
- // `provider returned 404: <body>` format) to the classifier, so a
- // wording / prefix drift fails CI instead of silently leaking events.
- //
- // The wild Sentry message carried the `inference/ops.rs`
- // `error!("[inference::ops] list_models:error: {err}")` PREFIX. The
- // primary fix classifies the raw `err` at the source before that
- // prefix is applied, but the `contains` widening above must ALSO
- // catch the prefixed variant for any future prefixed re-report path.
- // Assert BOTH the raw source shape and the prefixed log-line shape.
-
- // (a) Raw source shape — exactly what `models.rs` returns for a Go
- // default-handler 404 (`404 page not found`).
- let raw_source = "provider returned 404: 404 page not found";
- assert_eq!(
- expected_error_kind(raw_source),
- Some(ExpectedErrorKind::ProviderUserState),
- "raw list_models 404 source shape must classify as ProviderUserState"
- );
-
- // (b) Raw source shape WITH the actionable hint appended by
- // `models.rs` for the 404 case — the prefix anchor must survive
- // the suffix.
- let raw_with_hint = "provider returned 404: 404 page not found — the configured base URL does not expose a `/models` endpoint; check the provider's base URL (it usually ends in `/v1`)";
- assert_eq!(
- expected_error_kind(raw_with_hint),
- Some(ExpectedErrorKind::ProviderUserState),
- "list_models 404 + actionable hint must still classify as ProviderUserState"
- );
-
- // (c) Prefixed log-line shape — the exact pattern from
- // `inference/ops.rs::inference_list_models` `error!`. The explicit
- // `list_models:error: provider returned 404` anchor must catch this
- // even though it does not start with `provider returned 404`. The
- // anchor is the formatted prefix, not a bare `404` substring, so it
- // does NOT mis-fire on a 500 whose body merely relays an upstream
- // 404 (see `does_not_classify_non_404_list_models_failures_as_user_state`).
- let prefixed =
- "[inference::ops] list_models:error: provider returned 404: 404 page not found";
- assert_eq!(
- expected_error_kind(prefixed),
- Some(ExpectedErrorKind::ProviderUserState),
- "prefixed list_models 404 log line must still classify as ProviderUserState (anchored prefix)"
- );
- }
-
- #[test]
- fn does_not_classify_non_404_list_models_failures_as_user_state() {
- // Discrimination guard: only the 404 prefix demotes. Sibling 4xx /
- // 5xx codes from the same `provider returned NNN:` emit site must
- // stay actionable in Sentry — they map to BYO-key auth walls (401 /
- // 403), client-shape bugs (400), and transient / server faults
- // (429 / 5xx) respectively. Pinning each shape here protects the
- // #2286 BYO-key 401 contract and prevents the arm from silently
- // widening to all 4xx.
- for raw in [
- // BYO-key auth wall — must still escalate (`does_not_classify_byo_key_provider_401_as_session_expired` sibling guard).
- r#"provider returned 401: {"error":"Invalid API key"}"#,
- r#"provider returned 403: {"error":"Forbidden: API key revoked"}"#,
- // Request-shape mismatch — likely a bug in our client.
- r#"provider returned 400: {"error":"Bad Request"}"#,
- // Transient — caught by retry/backoff at the provider layer,
- // does NOT belong in the user-state bucket.
- r#"provider returned 429: {"error":"rate_limited"}"#,
- r#"provider returned 503: upstream temporarily unavailable"#,
- // 500 — a real upstream bug; must reach Sentry.
- r#"provider returned 500: {"error":"internal_server_error"}"#,
- // TAURI-RUST-8X3 false-negative guard: a genuine 4xx/5xx whose
- // *body* merely relays an upstream 404 phrase. The actual status
- // is 500/400, so this is a real failure that MUST reach Sentry —
- // the classifier anchors on the `provider returned 404:` prefix,
- // not on any `404` occurrence in the body, so these must NOT demote.
- r#"provider returned 500: {"error":"upstream provider returned 404 page not found"}"#,
- r#"provider returned 400: gateway error — upstream provider returned 404"#,
- // Prefixed log-line variant of the same trap: the genuine status is
- // 500, the buried `... 404` is body text.
- "[inference::ops] list_models:error: provider returned 500: upstream provider returned 404 not found",
- ] {
- assert_ne!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ProviderUserState),
- "non-404 list_models failure must NOT demote to ProviderUserState: {raw}"
- );
- }
- }
-
- #[test]
- fn classifies_local_ai_binary_missing_errors() {
- // OPENHUMAN-TAURI-9N: `local_ai_tts` returns this exact string
- // from `service::speech::tts` when piper isn't on PATH or
- // `PIPER_BIN` isn't set.
- assert_eq!(
- expected_error_kind("piper binary not found. Set PIPER_BIN or install piper."),
- Some(ExpectedErrorKind::LocalAiBinaryMissing)
- );
- // Sibling shapes from the same service area share the anchor and
- // must classify the same way — the user-facing remediation is
- // identical (install / configure the binary).
- assert_eq!(
- expected_error_kind(
- "Ollama binary not found at '/usr/local/bin/ollama'. Provide a valid path to the ollama executable."
- ),
- Some(ExpectedErrorKind::LocalAiBinaryMissing)
- );
- assert_eq!(
- expected_error_kind("Ollama installed but binary not found on system"),
- Some(ExpectedErrorKind::LocalAiBinaryMissing)
- );
- // Wrapped by the RPC dispatcher in production:
- // `"rpc.invoke_method failed: piper binary not found. …"`.
- // The classifier is substring-based, so caller context must not
- // defeat it.
- assert_eq!(
- expected_error_kind(
- "rpc.invoke_method failed: piper binary not found. Set PIPER_BIN or install piper."
- ),
- Some(ExpectedErrorKind::LocalAiBinaryMissing)
- );
- }
-
- #[test]
- fn does_not_classify_unrelated_messages_as_binary_missing() {
- // Pin the anchor: messages that talk about binaries in a
- // different context (download failures, version mismatches)
- // must not be silenced.
- assert_eq!(
- expected_error_kind("piper binary failed to spawn: permission denied"),
- None
- );
- assert_eq!(
- expected_error_kind("piper returned an empty audio file"),
- None
- );
- }
-
- #[test]
- fn classifies_session_expired_messages() {
- // OPENHUMAN-TAURI-26: the canonical wire shape that `agent.run_single`
- // and `web_channel.run_chat_task` re-emit via `report_error_or_expected`
- // when the user's JWT expires mid-conversation. The classifier
- // anchors on the literal `"session expired"` substring from the
- // OpenHuman backend's 401 body — NOT on the bare `(401 Unauthorized)`
- // status, which would also silence BYO-key OpenAI/Anthropic 401s
- // that are actionable.
- assert_eq!(
- expected_error_kind(
- r#"OpenHuman API error (401 Unauthorized): {"success":false,"error":"Session expired. Please log in again."}"#
- ),
- Some(ExpectedErrorKind::SessionExpired)
- );
-
- // Wrapped by the agent / web-channel report sites in production —
- // the classifier is substring-based so caller context must not
- // defeat it.
- assert_eq!(
- expected_error_kind(
- r#"run_chat_task failed client_id=abc thread_id=t1 request_id=r1 error=OpenHuman API error (401 Unauthorized): {"success":false,"error":"Session expired. Please log in again."}"#
- ),
- Some(ExpectedErrorKind::SessionExpired)
- );
-
- // Sentinel raised by `providers::openhuman_backend::resolve_bearer`
- // when the scheduler-gate signed-out override is set
- // (OPENHUMAN-TAURI-1T's cascade dampener returns this so callers
- // get the same teardown path as a real backend 401).
- assert_eq!(
- expected_error_kind(
- "SESSION_EXPIRED: backend session not active — sign in to resume LLM work"
- ),
- Some(ExpectedErrorKind::SessionExpired)
- );
-
- // Local pre-flight guards — OpenHuman-specific phrasing, safe to
- // match regardless of caller wrapping.
- for raw in [
- "no backend session token; run auth_store_session first",
- "session JWT required",
- "composio unavailable: no backend session token. Sign in first (auth_store_session).",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::SessionExpired),
- "should classify as session-expired: {raw}"
- );
- }
- }
-
- /// OPENHUMAN-TAURI-SG (33 events, escalating, release `0.53.43+2b64ea8…`):
- /// pre-#1763 leak of the `resolve_bearer` sentinel through
- /// `agent.run_single`. PR #1763 (1fb0bef5) wired the `SessionExpired`
- /// arm and the existing `classifies_session_expired_messages` test
- /// covers the same byte string — this test pins the *Sentry-event
- /// verbatim* shape (taken from the OPENHUMAN-TAURI-SG event payload)
- /// so a future tweak to `is_session_expired_message` cannot regress
- /// this exact wire form without a red test.
- #[test]
- fn session_expired_sg_wire_shape_matches() {
- let msg = "SESSION_EXPIRED: backend session not active — sign in to resume LLM work";
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::SessionExpired),
- "OPENHUMAN-TAURI-SG wire shape must classify as SessionExpired — \
- a regression here re-leaks 33+ events/cycle to Sentry"
- );
- }
-
- /// The two sibling `SESSION_EXPIRED:` bail sites in
- /// `providers::factory::verify_session_active` emit different message
- /// suffixes but the same sentinel prefix. They route through the same
- /// classifier as the run_single bail at
- /// `providers::openhuman_backend::resolve_bearer`, and any matcher
- /// tweak that breaks the family (e.g. moving from `contains` to a
- /// stricter prefix/suffix match) would re-leak ALL of them. Pin every
- /// variant the codebase actually emits so a future regression on the
- /// matcher is caught for the whole family, not just the SG instance.
- #[test]
- fn session_expired_sibling_family_factory_strings_match() {
- // crates/openhuman-core/src/inference/provider/factory.rs:247
- // (verify_session_active — scheduler_gate signed-out path)
- let custom_providers_variant =
- "SESSION_EXPIRED: backend session not active — sign in to use custom providers";
- // crates/openhuman-core/src/inference/provider/factory.rs:266
- // (verify_session_active — empty auth-profile JWT path)
- let no_backend_session_variant =
- "SESSION_EXPIRED: no backend session — sign in to use OpenHuman";
-
- for raw in [custom_providers_variant, no_backend_session_variant] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::SessionExpired),
- "factory.rs sibling sentinel must classify as SessionExpired: {raw}"
- );
- }
- }
-
- /// OPENHUMAN-TAURI-4P0: the OpenHuman backend rejects an expired/
- /// revoked JWT with the envelope `{"success":false,"error":"Invalid
- /// token"}` (vs. the explicit `"Session expired. Please log in again."`
- /// body covered by `classifies_session_expired_messages`). Same emit
- /// site, same wrapping by `web_channel.run_chat_task`, but the body
- /// substring is different.
- ///
- /// The matcher uses a conjunctive `"OpenHuman API error (401"` +
- /// envelope-shaped `"\"error\":\"Invalid token\""` anchor pair so the
- /// #2286 contract for bare `"Invalid token"` / BYO-key 401s is
- /// preserved — `does_not_classify_byo_key_provider_401_as_session_expired`
- /// pins that and must stay green.
- #[test]
- fn classifies_openhuman_invalid_token_401_as_session_expired() {
- // Verbatim wire shape from the OPENHUMAN-TAURI-4P0 event payload.
- let msg = r#"run_chat_task failed client_id=lssXhQidBfzGXG9k thread_id=thread-743193ba-f0c1-4008-b665-64d3030d1453 request_id=00696b71-fa05-4574-bcdb-5744a5dac6ea error=OpenHuman API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#;
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::SessionExpired),
- "OPENHUMAN-TAURI-4P0 verbatim wire shape must classify as SessionExpired"
- );
-
- // Unwrapped emit shape (without the run_chat_task prefix) — also
- // appears at provider/agent layers; the substring matcher must
- // catch it regardless of caller wrapping.
- assert_eq!(
- expected_error_kind(
- r#"OpenHuman API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#
- ),
- Some(ExpectedErrorKind::SessionExpired),
- "unwrapped OpenHuman invalid-token envelope must classify as SessionExpired"
- );
- }
-
- /// TAURI-RUST-4K5 (118 events, escalating on 0.56.0): the embedding
- /// client at `crates/openhuman-core/src/inference/embeddings/openai.rs:139` wraps the same
- /// OpenHuman backend `{"success":false,"error":"Invalid token"}` 401
- /// envelope as 4P0, but with the `"Embedding API error"` prefix
- /// instead of `"OpenHuman API error"` (different emit-site format
- /// string, same underlying session-expired cause — see breadcrumb
- /// `[scheduler_gate] signed_out false -> true` immediately preceding
- /// the 401 in the event payload).
- ///
- /// Uses the same conjunctive `"<prefix> (401"` + envelope-shaped
- /// `"\"error\":\"Invalid token\""` anchor pattern as 4P0 so the
- /// #2286 / BYO-key contract is preserved — covered by
- /// `does_not_classify_byo_key_provider_401_as_session_expired` and
- /// `does_not_classify_embedding_byo_key_401_as_session_expired`
- /// (below).
- #[test]
- fn classifies_embedding_api_invalid_token_401_as_session_expired() {
- // Verbatim wire shape from the TAURI-RUST-4K5 event payload (Sentry
- // issue 5230, latest event 2026-05-27 20:49 on [email protected],
- // domain=embeddings operation=openai_embed status=401).
- let msg =
- r#"Embedding API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#;
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::SessionExpired),
- "TAURI-RUST-4K5 verbatim wire shape must classify as SessionExpired"
- );
-
- // The substring matcher must survive caller wrapping the same way
- // the 4P0 web-channel `run_chat_task` test wraps the body — callers
- // that re-emit through a tracing field or another layer prepend
- // arbitrary context.
- let wrapped = r#"openai_embed failed error=Embedding API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#;
- assert_eq!(
- expected_error_kind(wrapped),
- Some(ExpectedErrorKind::SessionExpired),
- "wrapped 4K5 envelope must still classify as SessionExpired"
- );
- }
-
- /// TAURI-RUST-1EE (Sentry issue 1807, 110 events, 109 on
- /// [email protected]): the streaming-chat path wraps the same OpenHuman
- /// backend `{"success":false,"error":"Invalid token"}` 401 envelope
- /// with the `"OpenHuman streaming API error"` prefix (emitted at
- /// `inference/provider/compatible.rs:949`) — distinct from the
- /// non-streaming `"OpenHuman API error"` prefix (4P0) and the
- /// `"Embedding API error"` prefix (4K5). The `streaming` token between
- /// `OpenHuman` and `API error` means the 4P0 anchor
- /// (`"OpenHuman API error (401"`) does not match it, so it needs its
- /// own prefix arm.
- #[test]
- fn classifies_openhuman_streaming_invalid_token_401_as_session_expired() {
- // Verbatim wire shape from the TAURI-RUST-1EE event payload
- // (domain=llm_provider operation=streaming_chat status=401
- // provider=OpenHuman model=reasoning-v1).
- let msg = r#"OpenHuman streaming API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#;
- assert_eq!(
- expected_error_kind(msg),
- Some(ExpectedErrorKind::SessionExpired),
- "TAURI-RUST-1EE verbatim streaming wire shape must classify as SessionExpired"
- );
-
- // Caller-wrapped (agent.run_single / web_channel.run_chat_task
- // re-emit prepends context) must still classify.
- let wrapped = r#"run_chat_task failed error=OpenHuman streaming API error (401 Unauthorized): {"success":false,"error":"Invalid token"}"#;
- assert_eq!(
- expected_error_kind(wrapped),
- Some(ExpectedErrorKind::SessionExpired),
- "wrapped 1EE streaming envelope must still classify as SessionExpired"
- );
- }
-
- /// Polarity guard for the 1EE streaming arm — a third-party BYO-key
- /// provider's streaming 401 (`"OpenAI streaming API error (401 …):
- /// invalid_api_key"`) must STILL reach Sentry as actionable
- /// misconfiguration. The `"OpenHuman streaming API error (401"` prefix
- /// gate keeps the match OpenHuman-scoped.
- #[test]
- fn does_not_classify_streaming_byo_key_401_as_session_expired() {
- for raw in [
- "OpenAI streaming API error (401 Unauthorized): invalid_api_key",
- r#"OpenAI streaming API error (401 Unauthorized): {"error":{"code":"invalid_api_key","message":"Incorrect API key provided"}}"#,
- "Anthropic streaming API error (401): authentication_error",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "BYO-key streaming 401 must reach Sentry as actionable error: {raw}"
- );
- }
- }
-
- /// Polarity guard for the 4K5 arm. The classifier must NOT swallow
- /// `"Embedding API error (401 …)"` shapes from third-party BYO-key
- /// embedding providers (OpenAI / Voyage / Cohere upstream rejecting
- /// the user's own API key). Those are actionable user-config errors
- /// that need to reach Sentry — same contract as
- /// `does_not_classify_byo_key_provider_401_as_session_expired` for
- /// the OpenAI chat API.
- #[test]
- fn does_not_classify_embedding_byo_key_401_as_session_expired() {
- for raw in [
- "Embedding API error (401 Unauthorized): invalid_api_key",
- r#"Embedding API error (401 Unauthorized): {"error":{"code":"invalid_api_key","message":"Incorrect API key provided"}}"#,
- // Wire shape without the OpenHuman envelope — bare provider
- // rejection prose. Must reach Sentry as actionable BYO-key
- // misconfiguration.
- "Embedding API error (401): authentication_error",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "BYO-key embedding 401 must reach Sentry as actionable error: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_byo_key_provider_401_as_session_expired() {
- // Critical: a BYO-key 401 from OpenAI / Anthropic etc. is an
- // actionable misconfiguration (wrong API key) that the user needs
- // to fix in settings. It must reach Sentry as an error and must
- // NOT be classified as session-expired at the agent layer — the
- // strict classifier requires the OpenHuman backend's
- // "session expired" body to anchor the match. The JSON-RPC
- // dispatch-site classifier uses the same strict rule so these
- // scoped provider failures never clear the app session either.
- for raw in [
- "OpenAI API error (401 Unauthorized): invalid_api_key",
- "Anthropic API error (401 Unauthorized): authentication_error",
- "OpenAI API error (401): unauthorized",
- r#"OpenAI API error (401 Unauthorized): {"error":{"code":"invalid_api_key","message":"Incorrect API key provided"}}"#,
- // Generic "invalid token" without OpenHuman session phrasing —
- // could mean a third-party provider rejected its own token.
- "Invalid token",
- "got an invalid token here",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- None,
- "BYO-key / generic 401 must reach Sentry as actionable error: {raw}"
- );
- }
- }
-
- #[test]
- fn does_not_classify_unrelated_messages_as_session_expired() {
- // Bare numeric 401 (port number, runbook reference) must not be
- // silenced.
- assert_eq!(expected_error_kind("server returned 401"), None);
- assert_eq!(
- expected_error_kind("see runbook for 401 handling at https://example.com/401"),
- None
- );
- // Provider 5xx — must reach Sentry.
- assert_eq!(
- expected_error_kind("OpenAI API error (500): internal server error"),
- None
- );
- // Lowercase sentinel must NOT match — the SESSION_EXPIRED sentinel
- // is case-sensitive by design (matches the sentinel emitted by
- // `providers::openhuman_backend::resolve_bearer` exactly).
- assert_eq!(expected_error_kind("session_expired lowercase"), None);
- }
-
- #[test]
- fn report_error_does_not_panic_with_many_tags() {
- let err = anyhow::anyhow!("multi-tag");
- report_error(
- &err,
- "test",
- "multi_tag",
- &[("a", "1"), ("b", "2"), ("c", "3"), ("d", "4")],
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- fn event_with_tags(pairs: &[(&str, &str)]) -> sentry::protocol::Event<'static> {
- let mut event = sentry::protocol::Event::default();
- let mut tags: std::collections::BTreeMap<String, String> =
- std::collections::BTreeMap::new();
- for (k, v) in pairs {
- tags.insert((*k).to_string(), (*v).to_string());
- }
- event.tags = tags;
- event
- }
-
- #[cfg(feature = "crash-reporting")]
- fn event_with_tags_and_message(
- pairs: &[(&str, &str)],
- message: &str,
- ) -> sentry::protocol::Event<'static> {
- let mut event = event_with_tags(pairs);
- event.message = Some(message.to_string());
- event
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_drops_429_408_502_503_504() {
- for status in ["429", "408", "502", "503", "504"] {
- let event = event_with_tags(&[
- ("domain", "llm_provider"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_transient_provider_http_failure(&event),
- "status {status} must be classified as transient and filtered"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn custom_openai_502_event_shape_is_transient_provider_http() {
- let event = event_with_tags_and_message(
- &[
- ("domain", "llm_provider"),
- ("provider", "custom_openai"),
- ("failure", "non_2xx"),
- ("status", "502"),
- ],
- "custom_openai API error (502 Bad Gateway): upstream gateway blip",
- );
- assert!(
- is_transient_provider_http_failure(&event),
- "custom_openai 502 attempts should be treated as transient provider HTTP noise"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_keeps_permanent_failures() {
- for status in ["400", "401", "403", "404", "500"] {
- let event = event_with_tags(&[
- ("domain", "llm_provider"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_transient_provider_http_failure(&event),
- "status {status} must NOT be filtered — it's actionable"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_keeps_aggregate_all_exhausted() {
- let event = event_with_tags(&[
- ("domain", "llm_provider"),
- ("failure", "all_exhausted"),
- ("status", "503"),
- ]);
- assert!(
- !is_transient_provider_http_failure(&event),
- "aggregate all_exhausted events must surface (they are the cascade signal)"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_keeps_events_with_no_status_tag() {
- let event = event_with_tags(&[("domain", "llm_provider"), ("failure", "non_2xx")]);
- assert!(
- !is_transient_provider_http_failure(&event),
- "missing status tag must not be silently dropped"
- );
- }
-
- // Regression guard: the filter must scope to provider events only. Other
- // subsystems emit `failure=non_2xx` (e.g.
- // `providers/compatible.rs` uses the same marker for OAI-compatible
- // error paths, but every site goes through `report_error(..,
- // "llm_provider", ..)` so the domain tag is consistent), but the broader
- // point is: any future caller that re-uses the same tag set for a
- // different domain must NOT be silently dropped by this filter.
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_keeps_events_with_no_domain_tag() {
- let event = event_with_tags(&[("failure", "non_2xx"), ("status", "503")]);
- assert!(
- !is_transient_provider_http_failure(&event),
- "missing domain tag means the event isn't provider-originated — must surface"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_filter_keeps_events_from_other_domains() {
- let event = event_with_tags(&[
- ("domain", "scheduler"),
- ("failure", "non_2xx"),
- ("status", "503"),
- ]);
- assert!(
- !is_transient_provider_http_failure(&event),
- "non-provider domain must surface even if failure/status tags collide"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn backend_api_filter_drops_transient_statuses() {
- for status in TRANSIENT_HTTP_STATUSES {
- let event = event_with_tags(&[
- ("domain", "backend_api"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_transient_backend_api_failure(&event),
- "backend status {status} must be classified as transient"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn backend_api_filter_drops_transient_transport_phrases() {
- for phrase in TRANSIENT_TRANSPORT_PHRASES {
- let event = event_with_tags_and_message(
- &[("domain", "backend_api"), ("failure", "transport")],
- &format!("GET /teams failed: {phrase}"),
- );
- assert!(
- is_transient_backend_api_failure(&event),
- "backend transport phrase {phrase} must be classified as transient"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn backend_api_filter_keeps_non_transient_failures() {
- for status in ["404", "500"] {
- let event = event_with_tags(&[
- ("domain", "backend_api"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_transient_backend_api_failure(&event),
- "backend status {status} must stay visible"
- );
- }
-
- let wrong_domain = event_with_tags(&[
- ("domain", "scheduler"),
- ("failure", "non_2xx"),
- ("status", "503"),
- ]);
- assert!(
- !is_transient_backend_api_failure(&wrong_domain),
- "domain scoping must keep unrelated transient-shaped events visible"
- );
-
- let non_matching_transport = event_with_tags_and_message(
- &[("domain", "backend_api"), ("failure", "transport")],
- "GET /teams failed: certificate verify failed",
- );
- assert!(
- !is_transient_backend_api_failure(&non_matching_transport),
- "transport failures without an allowlisted phrase must stay visible"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn skills_install_fetch_filter_drops_client_error_statuses() {
- for status in ["400", "401", "403", "404", "410", "499"] {
- let event = event_with_tags(&[
- ("domain", "skills"),
- ("operation", "install_fetch"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_skill_install_user_fetch_failure(&event),
- "skills install_fetch status {status} must be treated as user/catalog state"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn skills_install_fetch_filter_keeps_server_and_wrong_shape_failures() {
- for status in ["500", "502", "503"] {
- let event = event_with_tags(&[
- ("domain", "skills"),
- ("operation", "install_fetch"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_skill_install_user_fetch_failure(&event),
- "skills install_fetch status {status} must remain reportable"
- );
- }
-
- for tags in [
- [
- ("domain", "skills"),
- ("operation", "install_fetch"),
- ("failure", "transport"),
- ("status", "404"),
- ],
- [
- ("domain", "skills"),
- ("operation", "run"),
- ("failure", "non_2xx"),
- ("status", "404"),
- ],
- [
- ("domain", "backend_api"),
- ("operation", "install_fetch"),
- ("failure", "non_2xx"),
- ("status", "404"),
- ],
- ] {
- let event = event_with_tags(&tags);
- assert!(
- !is_skill_install_user_fetch_failure(&event),
- "only skills.install_fetch non_2xx 4xx events may be filtered: {tags:?}"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn integrations_filter_drops_transient_statuses() {
- for status in TRANSIENT_HTTP_STATUSES {
- let event = event_with_tags(&[
- ("domain", "integrations"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_transient_integrations_failure(&event),
- "integrations status {status} must be classified as transient"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn integrations_filter_drops_transient_transport_phrases() {
- for phrase in TRANSIENT_TRANSPORT_PHRASES {
- let event = event_with_tags_and_message(
- &[("domain", "integrations"), ("failure", "transport")],
- &format!("GET /agent-integrations/tools failed: {phrase}"),
- );
- assert!(
- is_transient_integrations_failure(&event),
- "integrations transport phrase {phrase} must be classified as transient"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn integrations_filter_keeps_non_transient_failures() {
- for status in ["404", "500"] {
- let event = event_with_tags(&[
- ("domain", "integrations"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_transient_integrations_failure(&event),
- "integrations status {status} must stay visible"
- );
- }
-
- // Sibling-domain check: composio op-layer events MUST be silenced
- // by the integrations filter — composio routes through the same
- // `IntegrationClient` so the failure shape is identical, but
- // op-level reporters that wrap and re-emit with their own domain
- // tag would otherwise escape (OPENHUMAN-TAURI-35 / -2H).
- let scheduler_domain = event_with_tags(&[
- ("domain", "scheduler"),
- ("failure", "non_2xx"),
- ("status", "503"),
- ]);
- assert!(
- !is_transient_integrations_failure(&scheduler_domain),
- "domain scoping must keep unrelated transient-shaped events visible"
- );
-
- let non_matching_transport = event_with_tags_and_message(
- &[("domain", "integrations"), ("failure", "transport")],
- "GET /agent-integrations/tools failed: invalid certificate",
- );
- assert!(
- !is_transient_integrations_failure(&non_matching_transport),
- "transport failures without an allowlisted phrase must stay visible"
- );
- }
-
- /// TAURI-RUST-CGE: skill-install fetch 4xx (a missing/renamed catalog
- /// `SKILL.md`) is expected user-input state — the before_send net must drop
- /// it, while a genuine 5xx remote failure and unrelated domains stay
- /// reportable.
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn skills_install_client_error_filter_drops_4xx_keeps_5xx() {
- // 4xx (esp. 404/410) = missing skill / wrong URL → dropped.
- for status in ["400", "403", "404", "410", "429"] {
- let event = event_with_tags(&[
- ("domain", "skills"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_skills_install_client_error_event(&event),
- "skills install 4xx {status} must be dropped"
- );
- }
-
- // 5xx = genuine remote failure → stays a Sentry signal.
- for status in ["500", "502", "503"] {
- let event = event_with_tags(&[
- ("domain", "skills"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_skills_install_client_error_event(&event),
- "skills install 5xx {status} must stay reportable"
- );
- }
-
- // Domain scoping: a 4xx in another domain must not be touched here.
- let other_domain = event_with_tags(&[
- ("domain", "backend_api"),
- ("failure", "non_2xx"),
- ("status", "404"),
- ]);
- assert!(
- !is_skills_install_client_error_event(&other_domain),
- "non-skills 4xx must not be swallowed by the skills filter"
- );
-
- // A skills event without the non_2xx failure marker (e.g. a transport
- // failure) must not be dropped by this status-scoped filter.
- let skills_transport = event_with_tags(&[("domain", "skills"), ("failure", "transport")]);
- assert!(
- !is_skills_install_client_error_event(&skills_transport),
- "skills transport failures are out of scope for the 4xx filter"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn composio_domain_routes_through_integrations_filter() {
- // OPENHUMAN-TAURI-35 (~139 events) / -2H (~26 events):
- // `[composio] list_connections failed: Backend returned 502 …` —
- // composio op-layer wrappers (e.g. `composio_list_connections`) emit
- // errors under `domain="composio"` so the original
- // `domain="integrations"` filter let them through. Routing the
- // composio domain through the same transient classifier closes
- // that gap; the underlying transport / non_2xx semantics are
- // identical because both layers share the same `IntegrationClient`.
- for status in TRANSIENT_HTTP_STATUSES {
- let event = event_with_tags(&[
- ("domain", "composio"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- is_transient_integrations_failure(&event),
- "composio status {status} must be classified as transient"
- );
- }
-
- // Transport-phrase variant — composio also surfaces reqwest
- // transport failures (timeouts, connection resets) once the op
- // wrapper has tagged the event with `failure=transport`.
- for phrase in TRANSIENT_TRANSPORT_PHRASES {
- let event = event_with_tags_and_message(
- &[("domain", "composio"), ("failure", "transport")],
- &format!("[composio] execute failed: {phrase}"),
- );
- assert!(
- is_transient_integrations_failure(&event),
- "composio transport phrase {phrase} must be classified as transient"
- );
- }
-
- // Non-transient composio statuses (404 / 500) must still surface —
- // actionable bugs even when reported under the composio domain.
- for status in ["404", "500"] {
- let event = event_with_tags(&[
- ("domain", "composio"),
- ("failure", "non_2xx"),
- ("status", status),
- ]);
- assert!(
- !is_transient_integrations_failure(&event),
- "composio status {status} must stay visible"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn composio_list_connections_503_504_wrappers_stay_filtered() {
- for (status, reason) in [("503", "Service Unavailable"), ("504", "Gateway Timeout")] {
- let message = format!(
- "[composio] list_connections failed: Backend returned {status} {reason} \
- for GET /agent-integrations/composio/connections"
- );
- let event = event_with_tags_and_message(
- &[
- ("domain", "composio"),
- ("failure", "non_2xx"),
- ("status", status),
- ],
- &message,
- );
- assert!(
- is_transient_integrations_failure(&event),
- "wrapped composio list_connections {status} failures must be filtered"
- );
- }
-
- for (status, reason) in [("503", "Service Unavailable"), ("504", "Gateway Timeout")] {
- let message = format!(
- "Backend returned {status} {reason} \
- for GET /agent-integrations/composio/connections"
- );
- let event = event_with_tags_and_message(
- &[
- ("domain", "integrations"),
- ("failure", "non_2xx"),
- ("status", status),
- ],
- &message,
- );
- assert!(
- is_transient_integrations_failure(&event),
- "raw integrations list_connections {status} failures must be filtered"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_transient_403_is_dropped() {
- let event = event_with_tags_and_message(
- &[
- ("domain", "update"),
- ("operation", "check_releases"),
- ("failure", "non_2xx"),
- ("status", "403"),
- ],
- "[observability] update.check_releases failed: GitHub API error: 403 Forbidden",
- );
- assert!(
- is_updater_transient_event(&event),
- "GitHub 403 updater checks are unactionable transient/rate-limit noise"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_github_403_message_only_shapes_are_dropped() {
- for event in [
- event_with_message("GitHub API error: 403 Forbidden"),
- event_with_exception_value("GitHub API error: 403 Forbidden"),
- ] {
- assert!(
- is_updater_transient_event(&event),
- "message-only GitHub 403 updater failures must be filtered"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_transient_502_is_dropped() {
- let event = event_with_tags_and_message(
- &[
- ("domain", "update.check_releases"),
- ("failure", "non_2xx"),
- ("status", "502"),
- ],
- "GitHub API error: 502 Bad Gateway",
- );
- assert!(
- is_updater_transient_event(&event),
- "GitHub 5xx updater checks must be filtered as transient"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_real_panic_still_reported() {
- let event = event_with_tags_and_message(
- &[("domain", "update"), ("operation", "check_releases")],
- "thread 'main' panicked at crates/openhuman-core/src/platform/update/core.rs: index out of bounds",
- );
- assert!(
- !is_updater_transient_event(&event),
- "update-domain events without a transient updater shape must still reach Sentry"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_endpoint_non_success_message_is_dropped() {
- // TAURI-RUST-CD (~151 events / 9 days, Windows): `tauri-plugin-updater`
- // logs `update endpoint did not respond with a successful status code`
- // (updater.rs) on any non-2xx response and discards the status, so the
- // captured event has NO `domain`/`status` tag — only the bare message.
- // It can therefore only be matched via the message fast-path.
- assert!(is_updater_transient_message(
- "update endpoint did not respond with a successful status code"
- ));
-
- let event = event_with_tags_and_message(
- &[],
- "update endpoint did not respond with a successful status code",
- );
- assert!(
- is_updater_transient_event(&event),
- "the plugin's status-blind, domain-less non-success log line is unactionable updater noise"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn updater_endpoint_non_success_anchor_does_not_silence_unrelated_errors() {
- // The new anchor is the literal plugin string. Other updater failures
- // that DO carry an actionable signal (signature/permission failures on
- // apply, deserialize errors) and unrelated non-updater errors that
- // merely mention a status code MUST NOT be dropped by it. Pin the
- // rejection contract so a future refactor doesn't loosen the substring.
- for msg in [
- "failed to apply update: signature verification failed",
- "failed to deserialize update response: missing field `version`",
- "backend request to /agent-integrations failed with status code 500",
- "tool exited with non-zero status code 1",
- ] {
- let event = event_with_tags_and_message(&[], msg);
- assert!(
- !is_updater_transient_event(&event),
- "unrelated/actionable error must still reach Sentry: {msg}"
- );
- }
- }
-
- #[test]
- fn message_failure_classifier_matches_canonical_status_phrases() {
- for msg in [
- "rpc.invoke_method failed: GET /teams failed (502 Bad Gateway)",
- "GET /teams/me/usage failed (503 Service Unavailable)",
- "downstream returned (504 Gateway Timeout): retry budget exhausted",
- "OpenHuman API error (520 <unknown status code>): cf",
- "POST /channels/telegram/typing failed (429 Too Many Requests)",
- "auth connect failed: 503 Service Unavailable",
- ] {
- assert!(
- is_transient_message_failure(msg),
- "{msg:?} must be classified as transient"
- );
- }
- }
-
- #[test]
- fn message_failure_classifier_matches_transport_phrases() {
- for msg in [
- "integrations.get failed: composio/tools → operation timed out",
- "GET https://api.example.com → connection forcibly closed (os 10054)",
- "POST /v1/foo → tls handshake eof",
- "error sending request for url (https://api.example.com)",
- ] {
- assert!(
- is_transient_message_failure(msg),
- "{msg:?} must be classified as transient"
- );
- }
- }
-
- #[test]
- fn message_failure_classifier_keeps_unrelated_messages() {
- for msg in [
- "rpc.invoke_method failed: schema validation error",
- "process 502 exited unexpectedly",
- "GET /teams failed (404 Not Found)",
- "GET /teams failed (500 Internal Server Error)",
- "unrelated error with port 5023",
- "",
- ] {
- assert!(
- !is_transient_message_failure(msg),
- "{msg:?} must not be classified as transient"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn budget_filter_drops_budget_message_on_tagged_400() {
- let event = event_with_tags_and_message(
- &[("failure", "non_2xx"), ("status", "400")],
- r#"OpenHuman API error (400 Bad Request): {"success":false,"error":"Insufficient budget"}"#,
- );
-
- assert!(is_budget_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn budget_filter_drops_budget_exception_on_tagged_400() {
- let mut event = event_with_tags(&[("failure", "non_2xx"), ("status", "400")]);
- event.exception.values.push(sentry::protocol::Exception {
- value: Some("Budget exceeded — add credits to continue".to_string()),
- ..Default::default()
- });
-
- assert!(is_budget_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn budget_filter_keeps_non_budget_400() {
- let event = event_with_tags_and_message(
- &[("failure", "non_2xx"), ("status", "400")],
- "Bad request: missing field",
- );
-
- assert!(!is_budget_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn budget_filter_requires_non_2xx_failure_and_400_status() {
- let message = "Budget exceeded — add credits to continue";
- for tags in [
- vec![("failure", "transport"), ("status", "400")],
- vec![("failure", "non_2xx"), ("status", "500")],
- vec![("failure", "non_2xx")],
- ] {
- let event = event_with_tags_and_message(&tags, message);
- assert!(!is_budget_event(&event));
- }
- }
-
- #[test]
- fn report_error_or_expected_does_not_panic() {
- report_error_or_expected(
- "local ai is disabled",
- "rpc",
- "invoke_method",
- &[("method", "openhuman.inference_prompt")],
- );
- report_error_or_expected(
- "ollama API key not set",
- "agent",
- "provider_chat",
- &[("provider", "ollama")],
- );
- // #2079 / #2076 / #2202 — exercises the expected_error_kind
- // ProviderConfigRejection branch AND the report_expected_message
- // skip-log arm (the agent/web-channel re-report demotion path).
- report_error_or_expected(
- "agent.run_single failed: custom_openai API error (400 Bad Request): \
- The supported API model names are deepseek-v4-pro or deepseek-v4-flash, \
- but you passed reasoning-v1.",
- "agent",
- "native_chat",
- &[("provider", "custom_openai")],
- );
- report_error_or_expected(
- "custom_openai API error (400): invalid temperature: only 1 is allowed for this model",
- "web_channel",
- "run_chat_task",
- &[("provider", "custom_openai")],
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- fn event_with_message(msg: &str) -> sentry::protocol::Event<'static> {
- let mut event = sentry::protocol::Event::default();
- event.message = Some(msg.to_string());
- event
- }
-
- #[cfg(feature = "crash-reporting")]
- fn event_with_exception_value(value: &str) -> sentry::protocol::Event<'static> {
- let mut event = sentry::protocol::Event::default();
- event.exception = vec![sentry::protocol::Exception {
- value: Some(value.to_string()),
- ..Default::default()
- }]
- .into();
- event
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn quota_exhausted_filter_matches_500_wrapped_kiro_event() {
- // TAURI-RUST-C9A: verbatim message as formatted by the provider emit
- // site — a 500 envelope around an inner 402 / MONTHLY_REQUEST_COUNT.
- // The status-agnostic quota filter must catch it on the message path
- // and the exception path.
- let body = "kiro API error (500 Internal Server Error): {\"error\":{\"message\":\
- \"HTTP 402 from Kiro IDE: {\\\"reason\\\":\\\"MONTHLY_REQUEST_COUNT\\\"}\",\
- \"type\":\"server_error\"}}";
- assert!(is_quota_exhausted_event(&event_with_message(body)));
- assert!(is_quota_exhausted_event(&event_with_exception_value(body)));
- assert!(is_quota_exhausted_message(body));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn quota_exhausted_filter_matches_responses_usage_limit_reached_event() {
- // TAURI-RUST-AFE: verbatim message as formatted by the `chat_via_responses`
- // emit site — the Codex/ChatGPT OAuth `/responses` plan cap. Mirrors the
- // real production shape `"<name> Responses API error (<status>): <body>"`
- // (`compatible_helpers.rs:135`), including the `(429)` status segment and
- // the full AFE payload (`plan_type` + `resets_at`) from `ops/http_error.rs`,
- // so this stays coupled to the actual wire format rather than a loose
- // substring. No "monthly"/"quota" co-marker, so it exercises the AFE
- // phrase extension reaching the before_send net on both message and
- // exception paths (the subconscious loop retries until `resets_at`).
- let body = "openai Responses API error (429): {\"error\":{\"type\":\
- \"usage_limit_reached\",\"message\":\"The usage limit has been reached\",\
- \"plan_type\":\"plus\",\"resets_at\":1750000000}}";
- assert!(is_quota_exhausted_event(&event_with_message(body)));
- assert!(is_quota_exhausted_event(&event_with_exception_value(body)));
- assert!(is_quota_exhausted_message(body));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn quota_exhausted_filter_ignores_generic_500_and_rate_limit() {
- // A generic 500 outage and a 429 rate-limit are not plan-quota
- // exhaustion — they must keep reaching Sentry / their own handling.
- assert!(!is_quota_exhausted_event(&event_with_message(
- "kiro API error (500 Internal Server Error): upstream connection reset"
- )));
- assert!(!is_quota_exhausted_event(&event_with_message(
- "provider API error (429 Too Many Requests): rate_limit_exceeded"
- )));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn insufficient_credits_filter_matches_message_path() {
- // Verbatim TAURI-RUST-C62 message as formatted by the provider emit
- // sites: "<provider> API error (402 Payment Required): <body>".
- let event = event_with_message(
- "myopenrouter API error (402 Payment Required): This request requires more credits, \
- or fewer max_tokens. You requested up to 65536 tokens, but can only afford 49732.",
- );
- assert!(is_insufficient_credits_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn insufficient_credits_filter_matches_exception_path() {
- let event = event_with_exception_value(
- "myopenrouter API error (402 Payment Required): insufficient balance",
- );
- assert!(is_insufficient_credits_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn insufficient_credits_filter_requires_both_402_and_credit_phrase() {
- // A 402 with no credit phrase must NOT be swallowed (could be another
- // payment semantic) ...
- assert!(!is_insufficient_credits_event(&event_with_message(
- "provider API error (402): some unrelated condition"
- )));
- // ... and a credit phrase without a 402 must NOT be swallowed (e.g. a
- // 400/500 that merely mentions balance) so a real defect still pages.
- assert!(!is_insufficient_credits_event(&event_with_message(
- "provider API error (500): internal error, insufficient memory"
- )));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn insufficient_credits_filter_ignores_402_digits_in_a_non_402_body() {
- // A non-402 error whose body merely contains the digits "402" and a
- // credit phrase must NOT be suppressed — the 402 must be the status,
- // not an arbitrary number in the body.
- assert!(!is_insufficient_credits_event(&event_with_message(
- "provider API error (400): can only afford 402 tokens"
- )));
- }
-
- #[test]
- fn is_insufficient_credits_message_matches_verbatim_cron_402() {
- // Verbatim TAURI-RUST-514 body as it reaches the cron `report_error`
- // call site (`domain=cron`, `operation=agent_job`): the message-level
- // matcher must catch it so the cron halt skips the leaking report.
- assert!(is_insufficient_credits_message(
- "openrouter API error (402 Payment Required): {\"error\":{\"message\":\"This \
- request requires more credits, or fewer max_tokens. You requested up to 65536 \
- tokens, but can only afford 5081.\"}}",
- ));
- assert!(is_insufficient_credits_message(
- "custom_openai API error (402 Payment Required): insufficient balance",
- ));
- }
-
- #[test]
- fn is_insufficient_credits_message_requires_402_and_credit_phrase() {
- // A 402 without a credit phrase, and a credit phrase without a 402
- // status, must both stay reportable (could be a real defect).
- assert!(!is_insufficient_credits_message(
- "provider API error (402): some unrelated condition"
- ));
- assert!(!is_insufficient_credits_message(
- "provider API error (500): internal error, insufficient memory"
- ));
- // The status must be the 402, not a digit in the body.
- assert!(!is_insufficient_credits_message(
- "provider API error (400): can only afford 402 tokens"
- ));
- // codex P2: the status prefix "(402 Payment Required)" itself contains
- // the phrase "payment required". An unrelated body behind a real 402
- // must NOT be classified as insufficient-credits (else the cron halt
- // would suppress a genuine 402 defect). The credit signal must live in
- // the BODY, not the formatted status prefix.
- assert!(!is_insufficient_credits_message(
- "provider API error (402 Payment Required): some unrelated condition"
- ));
- // But a body that literally carries the credit signal still matches,
- // even when the status prefix also says "Payment Required".
- assert!(is_insufficient_credits_message(
- "provider API error (402 Payment Required): your account has insufficient balance"
- ));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn is_insufficient_credits_event_delegates_to_message_matcher() {
- // Parity: the event-level filter is now a thin wrapper over the
- // message-level matcher across both the message and exception paths.
- let body = "myopenrouter API error (402 Payment Required): This request requires \
- more credits, or fewer max_tokens.";
- assert!(is_insufficient_credits_message(body));
- assert!(is_insufficient_credits_event(&event_with_message(body)));
- assert!(is_insufficient_credits_event(&event_with_exception_value(
- body
- )));
- }
-
- #[test]
- fn ollama_cloud_internal_500_reraise_routes_through_expected_path() {
- // TAURI-RUST-5MV — the actionable message the emit sites raise must
- // demote to `TransientUpstreamHttp` when re-reported at the agent / RPC
- // boundary (`provider_chat` → `report_error_or_expected`), so the
- // `domain=agent` half of the flood is suppressed too.
- let reraise = crate::inference::provider::ollama_cloud_internal_500_user_message(
- Some("minimax-m3:cloud"),
- reqwest::StatusCode::INTERNAL_SERVER_ERROR,
- );
- assert_eq!(
- expected_error_kind(&reraise),
- Some(ExpectedErrorKind::TransientUpstreamHttp)
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn ollama_cloud_internal_500_before_send_matches_raw_and_reraised_shapes() {
- // The outermost net catches BOTH the raw emit body (any compatible
- // path that bypassed the cascade) and the actionable re-raise.
- let raw = "ollama API error (500 Internal Server Error): \
- {\"error\":\"Internal Server Error (ref: df512dcb-d915-493b-8f2d-e8d3dfa640c1)\"}";
- assert!(is_ollama_cloud_internal_500_event(&event_with_message(raw)));
- assert!(is_ollama_cloud_internal_500_event(
- &event_with_exception_value(raw)
- ));
-
- let reraise = crate::inference::provider::ollama_cloud_internal_500_user_message(
- None,
- reqwest::StatusCode::INTERNAL_SERVER_ERROR,
- );
- assert!(is_ollama_cloud_internal_500_event(&event_with_message(
- &reraise
- )));
-
- // A local Ollama 500 without the `ref:` envelope, and a non-ollama 500,
- // both stay reportable.
- assert!(!is_ollama_cloud_internal_500_event(&event_with_message(
- "ollama API error (500 Internal Server Error): {\"error\":\"out of memory\"}"
- )));
- assert!(!is_ollama_cloud_internal_500_event(&event_with_message(
- "openai API error (500): Internal Server Error (ref: abc)"
- )));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn session_expired_before_send_matches_core_401_events() {
- let msg = "SESSION_EXPIRED: backend session not active — sign in to resume LLM work";
- for event in [
- event_with_tags_and_message(&[("domain", "llm_provider"), ("status", "401")], msg),
- {
- let mut event = event_with_exception_value(msg);
- event.tags.insert("domain".into(), "backend_api".into());
- event.tags.insert("status".into(), "401".into());
- event
- },
- ] {
- assert!(
- is_session_expired_event(&event),
- "core/backend session-expired 401 events should be filtered"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn session_expired_before_send_stays_domain_scoped() {
- let event = event_with_tags_and_message(
- &[("domain", "composio"), ("status", "401")],
- "SESSION_EXPIRED: backend session not active — sign in to resume LLM work",
- );
- assert!(
- !is_session_expired_event(&event),
- "non-core domains must not be filtered as backend session expiry"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn max_iterations_filter_matches_message_path() {
- // `report_error_message` calls `sentry::capture_message`, which
- // populates `event.message`. The filter must see the canonical
- // phrase on that field path.
- let event = event_with_message("Agent exceeded maximum tool iterations (8)");
- assert!(is_max_iterations_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn max_iterations_filter_matches_exception_path() {
- // sentry-tracing with attach_stacktrace=true populates the
- // exception list instead of (or in addition to) `event.message`.
- // Filter must still catch the noise.
- let event = event_with_exception_value(
- "agent.run_single failed: Agent exceeded maximum tool iterations (10)",
- );
- assert!(is_max_iterations_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn max_iterations_filter_keeps_unrelated_events() {
- assert!(!is_max_iterations_event(&event_with_message(
- "provider returned 503"
- )));
- assert!(!is_max_iterations_event(&event_with_message("")));
- assert!(!is_max_iterations_event(&sentry::protocol::Event::default()));
- }
-
- // ── is_channel_message_not_found_event (TAURI-R7) ────────────────────────
-
- #[cfg(feature = "crash-reporting")]
- fn channel_message_404_event(method: &str) -> sentry::protocol::Event<'static> {
- let mut event = sentry::protocol::Event::default();
- event.tags.insert("domain".into(), "backend_api".into());
- event.tags.insert("failure".into(), "non_2xx".into());
- event.tags.insert("status".into(), "404".into());
- event.tags.insert("method".into(), method.into());
- event.message = Some(
- "PATCH /channels/telegram/messages/1103 failed (404); response_body_len=172"
- .to_string(),
- );
- event
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_matches_patch() {
- // Canonical TAURI-R7 shape: PATCH 404 on a channel-message path.
- assert!(is_channel_message_not_found_event(
- &channel_message_404_event("PATCH")
- ));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_matches_delete() {
- assert!(is_channel_message_not_found_event(
- &channel_message_404_event("DELETE")
- ));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_ignores_get_404() {
- // GET 404 on a channel-message path is NOT an expected state — must keep Sentry signal.
- assert!(!is_channel_message_not_found_event(
- &channel_message_404_event("GET")
- ));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_ignores_non_channel_path() {
- let mut event = channel_message_404_event("PATCH");
- event.message = Some("PATCH /auth/profile failed (404); response_body_len=42".to_string());
- assert!(!is_channel_message_not_found_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_ignores_wrong_status() {
- let mut event = channel_message_404_event("PATCH");
- event.tags.insert("status".into(), "403".into());
- assert!(!is_channel_message_not_found_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_ignores_wrong_domain() {
- let mut event = channel_message_404_event("PATCH");
- event.tags.insert("domain".into(), "channels".into());
- assert!(!is_channel_message_not_found_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn channel_message_not_found_filter_matches_exception_path() {
- // sentry-tracing with attach_stacktrace=true populates exception list.
- let mut event = sentry::protocol::Event::default();
- event.tags.insert("domain".into(), "backend_api".into());
- event.tags.insert("failure".into(), "non_2xx".into());
- event.tags.insert("status".into(), "404".into());
- event.tags.insert("method".into(), "PATCH".into());
- event.exception = vec![sentry::protocol::Exception {
- value: Some("PATCH /channels/discord/messages/abc failed (404): Not Found".to_string()),
- ..Default::default()
- }]
- .into();
- assert!(is_channel_message_not_found_event(&event));
- }
-
- // ── LoopbackUnavailable (TAURI-R5, TAURI-R6) ─────────────────────────────
-
- /// Verbatim body shape from OPENHUMAN-TAURI-R5 (~2.5k events): the
- /// `integrations.get` site reaches the embedded core's `127.0.0.1:18474`
- /// listener during the boot window and reqwest's source chain renders as
- /// `error sending request for url (…) → client error (Connect) → tcp
- /// connect error → Connection refused (os error 61)`.
- const R5_BODY: &str = "error sending request for url \
- (http://127.0.0.1:18474/agent-integrations/composio/connections) \
- → client error (Connect) → tcp connect error → Connection refused (os error 61)";
-
- /// Verbatim body shape from OPENHUMAN-TAURI-R6 (~2.5k events): the same
- /// transport failure as R5, re-wrapped one frame up by the composio
- /// op-layer and re-emitted at the `rpc.invoke_method` site so it lands in
- /// Sentry under `domain=rpc` instead of `domain=integrations`.
- const R6_BODY: &str = "[composio] list_connections failed: \
- GET http://127.0.0.1:18474/agent-integrations/composio/connections failed: \
- error sending request for url \
- (http://127.0.0.1:18474/agent-integrations/composio/connections) \
- → client error (Connect) → tcp connect error → Connection refused (os error 61)";
-
- #[test]
- fn classifies_r5_loopback_connect_refused_as_loopback_unavailable() {
- assert_eq!(
- expected_error_kind(R5_BODY),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "R5 body must classify as LoopbackUnavailable, not the broader NetworkUnreachable bucket"
- );
- }
-
- #[test]
- fn classifies_r6_rpc_wrapped_loopback_connect_refused_as_loopback_unavailable() {
- assert_eq!(
- expected_error_kind(R6_BODY),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "R6 body (rpc.invoke_method re-wrap) must classify as LoopbackUnavailable"
- );
- }
-
- #[test]
- fn classifies_loopback_connect_refused_across_platforms() {
- // Linux WSL / native: os error 111. Windows WSAECONNREFUSED: 10061.
- // Both must classify so the matcher works regardless of where the
- // user's desktop happens to be running.
- for raw in [
- "error sending request for url (http://127.0.0.1:18474/x) \
- → tcp connect error → Connection refused (os error 111)",
- "error sending request for url (http://localhost:18474/x) \
- → tcp connect error → Connection refused (os error 10061)",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "should classify as LoopbackUnavailable across platforms: {raw}"
- );
- }
- }
-
- #[test]
- fn loopback_unavailable_precedence_over_network_unreachable() {
- // Precedence guard: a loopback `Connection refused (os error 61)`
- // body would ALSO match `is_network_unreachable_message` because the
- // broader matcher catches both `error sending request for url` and
- // `connection refused`. The ladder must route through the
- // loopback-specific bucket first so the two error classes stay
- // distinguishable in Sentry.
- let kind = expected_error_kind(R5_BODY);
- assert_eq!(kind, Some(ExpectedErrorKind::LoopbackUnavailable));
- assert_ne!(kind, Some(ExpectedErrorKind::NetworkUnreachable));
- }
-
- #[test]
- fn does_not_classify_loopback_url_with_different_error_class_as_loopback() {
- // A real upstream HTTP failure that happens to hit a developer's
- // local proxy on `127.0.0.1:` (e.g. `mitmproxy`, `Charles`,
- // `ngrok http`) must NOT be silenced as loopback noise — the body
- // shape is a 503 status, not a transport-level connect-refused, and
- // is actionable for Sentry.
- let raw = "Backend returned 503 Service Unavailable for GET \
- http://127.0.0.1:8080/agent-integrations/composio/connections: \
- upstream timed out";
- assert!(
- !matches!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::LoopbackUnavailable)
- ),
- "loopback URL with non-transport error must not classify as LoopbackUnavailable"
- );
- }
-
- #[test]
- fn does_not_classify_non_loopback_connect_refused_as_loopback() {
- // A `Connection refused` against a non-loopback host (DNS resolved
- // to a remote IP, ISP-level block, captive portal) must fall
- // through to `NetworkUnreachable`, not into the loopback bucket.
- let raw = "error sending request for url \
- (https://api.tinyhumans.ai/agent-integrations/composio/connections) \
- → tcp connect error → Connection refused (os error 61)";
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::NetworkUnreachable)
- );
- }
-
- /// Verbatim body from TAURI-RUST-12K (2802 events / 29 users): a cron
- /// agent job hits a local LM Studio server (`localhost:1234`) that isn't
- /// running, on a zh-CN Windows host — so the `WSAECONNREFUSED` text is
- /// localized and the English "connection refused" prefix is absent, leaving
- /// only `(os error 10061)` behind the transport-stable `tcp connect error`
- /// marker. The locale-independent arm must still route it to the loopback
- /// bucket rather than leaking to the broad `NetworkUnreachable`.
- #[test]
- fn classifies_localized_loopback_connect_refused_as_loopback_unavailable() {
- let raw = "error sending request for url \
- (http://localhost:1234/v1/chat/completions): client error (Connect): \
- tcp connect error: 由于目标计算机积极拒绝,无法连接。 (os error 10061)";
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "localized WSAECONNREFUSED loopback body must classify as LoopbackUnavailable"
- );
- }
-
- #[test]
- fn does_not_classify_loopback_timeout_as_loopback() {
- // A loopback *timeout* (WSAETIMEDOUT os error 10060, not the
- // connect-refused 10061) shares the `tcp connect error` marker but is
- // a distinct failure class — it must NOT be swallowed by the
- // connect-refused loopback arm.
- let raw = "error sending request for url \
- (http://localhost:1234/v1/chat/completions): \
- tcp connect error: connection timed out (os error 10060)";
- assert!(
- !matches!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::LoopbackUnavailable)
- ),
- "loopback timeout must not classify as LoopbackUnavailable"
- );
- }
-
- #[test]
- fn is_local_provider_unreachable_message_wraps_loopback_matcher() {
- let localized = "error sending request for url \
- (http://localhost:1234/v1/chat/completions): client error (Connect): \
- tcp connect error: 由于目标计算机积极拒绝,无法连接。 (os error 10061)";
- assert!(is_local_provider_unreachable_message(localized));
- // Remote refused must not match (loopback-only, keeps real outages visible).
- assert!(!is_local_provider_unreachable_message(
- "error sending request for url (https://api.tinyhumans.ai/x) \
- → tcp connect error → Connection refused (os error 61)"
- ));
- }
-
- #[test]
- fn loopback_matcher_requires_both_host_and_errno_anchors() {
- // Defense against the matcher being too eager: bodies that satisfy
- // only one of the two conjunctive anchors must not classify into the
- // loopback bucket. They may still demote via the broader
- // `NetworkUnreachable` matcher — that is the correct fall-through —
- // but the bucket must stay distinct so Sentry's "what class is
- // spiking?" signal is preserved.
- let loopback_host_no_errno =
- "doctor: probed 127.0.0.1:18474 and got connection refused without errno detail";
- assert_ne!(
- expected_error_kind(loopback_host_no_errno),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "loopback host without `(os error N)` errno must not classify as LoopbackUnavailable"
- );
-
- let errno_no_loopback_host = "note: connection refused (os error 61) on retry";
- assert_ne!(
- expected_error_kind(errno_no_loopback_host),
- Some(ExpectedErrorKind::LoopbackUnavailable),
- "errno without loopback host anchor must not classify as LoopbackUnavailable"
- );
- }
-
- #[test]
- fn report_error_or_expected_routes_r5_r6_through_expected_path() {
- // Smoke test: both verbatim Sentry bodies flow through
- // `report_error_or_expected` without panicking. The classifier
- // routes them to `report_expected_message` (debug breadcrumb,
- // metadata-only) instead of `report_error_message`
- // (`sentry::capture_message` at error level). We can't observe the
- // Sentry hub from this test, but exercising the call path catches
- // any future regression that re-introduces a panic or mis-types
- // the arm.
- report_error_or_expected(
- R5_BODY,
- "integrations",
- "get",
- &[
- ("path", "/agent-integrations/composio/connections"),
- ("failure", "transport"),
- ],
- );
- report_error_or_expected(
- R6_BODY,
- "rpc",
- "invoke_method",
- &[("method", "openhuman.composio_list_connections")],
- );
- }
-
- #[test]
- fn classifies_channel_supervisor_restart_english_discord_gateway() {
- // TAURI-RUST-15 (~11.4k events / 14d on self-hosted `tauri-rust`):
- // verbatim wrapper from `channels::runtime::supervision::spawn_supervised_listener`
- // around the Discord gateway transport error. The English body
- // would otherwise match `is_network_unreachable_message` (which
- // demotes to `warn!` — still a Sentry event); the supervisor
- // wrap precedence routes it to `ChannelSupervisorRestart`
- // (info-only breadcrumb).
- let body = "Channel discord error: error sending request for url \
- (https://discord.com/api/v10/gateway/bot); restarting";
- assert_eq!(
- expected_error_kind(body),
- Some(ExpectedErrorKind::ChannelSupervisorRestart)
- );
- }
-
- #[test]
- fn classifies_channel_supervisor_restart_chinese_windows_wsaetimedout() {
- // TAURI-RUST-BB (~815 events / 14d): same supervisor wrapper,
- // OS-localized inner WSAETIMEDOUT body on Chinese Windows. The
- // English-only `is_network_unreachable_message` anchors miss
- // this inner message, so without the language-agnostic
- // supervisor matcher it would escape classification entirely
- // and emit a full Sentry error. The wrapper-anchored predicate
- // catches it regardless of OS locale.
- let body = "Channel discord error: IO error: \
- 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。 \
- (os error 10060); restarting";
- assert_eq!(
- expected_error_kind(body),
- Some(ExpectedErrorKind::ChannelSupervisorRestart)
- );
- }
-
- #[test]
- fn channel_supervisor_restart_matches_multiple_channel_names() {
- // The wrapper format is `"Channel <name> error: <inner>; restarting"`.
- // The name slot varies by provider (discord, slack, telegram,
- // whatsapp, gmessages, …). The matcher must classify all of them —
- // language-agnostic, name-agnostic.
- for raw in [
- "Channel slack error: gateway disconnect; restarting",
- "Channel telegram error: tls handshake eof; restarting",
- "Channel whatsapp error: connection reset by peer (os error 54); restarting",
- "Channel gmessages error: WebSocket connect: HTTP error: 502 Bad Gateway; restarting",
- ] {
- assert_eq!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ChannelSupervisorRestart),
- "should classify as channel-supervisor-restart: {raw}"
- );
- }
- }
-
- #[test]
- fn channel_supervisor_restart_precedence_over_network_unreachable() {
- // Pin the precedence: a supervisor-wrap body that ALSO contains
- // the canonical `"error sending request for url"` anchor (which
- // would by itself classify as `NetworkUnreachable`) MUST route
- // to `ChannelSupervisorRestart`. The supervisor's own backoff
- // handles the condition; `NetworkUnreachable` would demote to
- // `warn!` (still a Sentry event), whereas
- // `ChannelSupervisorRestart` demotes to `info!` (no event).
- let body = "Channel discord error: error sending request for url \
- (https://discord.com/api/v10/gateway/bot); restarting";
- let kind = expected_error_kind(body);
- assert_eq!(kind, Some(ExpectedErrorKind::ChannelSupervisorRestart));
- assert_ne!(kind, Some(ExpectedErrorKind::NetworkUnreachable));
- }
-
- #[test]
- fn channel_supervisor_restart_does_not_classify_unrelated_restart_notes() {
- // Defense against the matcher being too eager: bodies that
- // contain `"; restarting"` but NOT the `"Channel <name> error:"`
- // preamble must NOT classify — those are generic restart logs
- // from other subsystems where Sentry signal may still be
- // actionable. The matcher requires all three anchors together
- // (`"channel "` prefix + `" error:"` separator + `"; restarting"`
- // trailer).
- for raw in [
- // No `Channel <name>` preamble.
- "systemd: docker.service; restarting",
- // No `Channel <name>` preamble even though `; restarting`
- // appears.
- "Connection refused; restarting",
- // The string `channel` appears but not as the leading
- // `"Channel <name> error:"` wrapper — must not classify.
- "channels::runtime::dispatch failed: error: provider exhausted; restarting",
- // The wrapper prefix is present but the trailer is not —
- // a half-formed log line must not classify.
- "Channel discord error: gateway disconnect",
- ] {
- assert_ne!(
- expected_error_kind(raw),
- Some(ExpectedErrorKind::ChannelSupervisorRestart),
- "must NOT classify as channel-supervisor-restart: {raw}"
- );
- }
- }
-
- #[test]
- fn report_error_or_expected_routes_channel_supervisor_restart_through_expected_path() {
- // Smoke test: the verbatim TAURI-RUST-15 Sentry body flows through
- // `report_error_or_expected` without panicking. The classifier
- // routes it to `report_expected_message` (info breadcrumb) instead
- // of `report_error_message` (`sentry::capture_message` at error
- // level). We can't observe the Sentry hub from this test, but
- // exercising the call path catches any future regression that
- // re-introduces a panic or mis-types the arm.
- report_error_or_expected(
- "Channel discord error: error sending request for url \
- (https://discord.com/api/v10/gateway/bot); restarting",
- "channels",
- "supervised_listener",
- &[("channel", "discord")],
- );
- }
-
- // ── #870 managed-backend errorCode Sentry ownership (F2/F4/F7/F8) ──
-
- fn managed_body(status: &str, code: &str) -> String {
- format!(
- "OpenHuman API error ({status}): {{\"error\":{{\"errorCode\":\"{code}\",\"message\":\"x\"}}}}"
- )
- }
-
- #[test]
- fn expected_kind_demotes_every_backend_owned_error_code() {
- for (status, code) in [
- ("429", "RATE_LIMITED"),
- ("402", "USER_INSUFFICIENT_CREDITS"),
- ("503", "UPSTREAM_UNAVAILABLE"),
- ("404", "MODEL_UNAVAILABLE"),
- ("400", "BAD_REQUEST"),
- ("500", "INTERNAL_ERROR"),
- ] {
- let body = managed_body(status, code);
- assert_eq!(
- expected_error_kind(&body),
- Some(ExpectedErrorKind::BackendErrorCodeOwned),
- "errorCode={code} must be backend-owned (no FE Sentry)"
- );
- }
-
- // Client-guard-leak codes page (None = capture), even with realistic
- // explanatory text that a later substring matcher would otherwise
- // re-demote into a suppressed bucket.
- let payload = "OpenHuman API error (413 Payload Too Large): \
- {\"error\":{\"errorCode\":\"PAYLOAD_TOO_LARGE\",\"message\":\"request entity too large\"}}";
- assert_eq!(
- expected_error_kind(payload),
- None,
- "PAYLOAD_TOO_LARGE is a client guard leak and must page"
- );
-
- // This body's message matches `is_context_window_exceeded_message`, so
- // without the early guard-leak bypass it would re-demote to the
- // suppressed `ContextWindowExceeded` bucket (CodeRabbit).
- let context = "OpenHuman API error (400 Bad Request): \
- {\"error\":{\"errorCode\":\"CONTEXT_LENGTH_EXCEEDED\",\"message\":\"This model's maximum context length is 128000 tokens, however you requested more\"}}";
- assert_eq!(
- expected_error_kind(context),
- None,
- "CONTEXT_LENGTH_EXCEEDED must page even with context-window wording"
- );
-
- // Proof the bypass is load-bearing, not a no-op: this body's text DOES
- // match the context-window matcher, so without the early guard-leak
- // bypass `expected_error_kind` would have re-demoted it to the
- // suppressed `ContextWindowExceeded` bucket.
- assert!(
- crate::inference::provider::is_context_window_exceeded_message(context),
- "test body must actually trigger the matcher the bypass guards against"
- );
- }
-
- #[test]
- fn expected_kind_lets_malformed_bad_request_page() {
- // F8: the one errorCode case that still pages — the backend flagged a
- // client-built payload as unparseable. `expected_error_kind` must NOT
- // classify it as expected, so capture proceeds.
- let body = "OpenHuman API error (400 Bad Request): \
- {\"error\":{\"errorCode\":\"BAD_REQUEST\",\"malformed\":true}}";
- assert_eq!(expected_error_kind(body), None);
- }
-
- #[test]
- fn expected_kind_ignores_byo_errors_with_no_code() {
- // A BYO 401 carries no errorCode — it must NOT be swallowed by the
- // backend-owned branch (it routes through its own matchers / capture).
- let body = "openai API error (401 Unauthorized): \
- {\"error\":{\"message\":\"Incorrect API key provided\"}}";
- assert_ne!(
- expected_error_kind(body),
- Some(ExpectedErrorKind::BackendErrorCodeOwned)
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn expected_kind_ignores_byo_errors_that_carry_an_error_code_token() {
- // CodeRabbit: a BYO / direct-provider envelope whose body happens to
- // carry an `errorCode`-shaped field must NOT be demoted — the
- // managed-envelope gate keeps it reaching Sentry.
- let body = "custom_openai API error (500 Internal Server Error): \
- {\"error\":{\"errorCode\":\"INTERNAL_ERROR\"}}";
- assert_ne!(
- expected_error_kind(body),
- Some(ExpectedErrorKind::BackendErrorCodeOwned)
- );
- let event = event_with_message(body);
- assert!(
- !is_backend_error_code_event(&event),
- "BYO body with an errorCode token must not be dropped by before_send"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn before_send_filter_drops_backend_owned_error_code_events() {
- for code in [
- "RATE_LIMITED",
- "UPSTREAM_UNAVAILABLE",
- "MODEL_UNAVAILABLE",
- "INTERNAL_ERROR",
- "BAD_REQUEST",
- ] {
- let event = event_with_message(&managed_body("500", code));
- assert!(
- is_backend_error_code_event(&event),
- "errorCode={code} event must be dropped by before_send"
- );
- }
-
- // Client-guard-leak codes survive before_send and page (the client
- // should have caught the limit before sending) — including a realistic
- // CONTEXT_LENGTH_EXCEEDED body whose wording matches the context-window
- // substring matcher (the filter keys on the errorCode, not the text).
- let payload = "OpenHuman API error (413 Payload Too Large): \
- {\"error\":{\"errorCode\":\"PAYLOAD_TOO_LARGE\",\"message\":\"request entity too large\"}}";
- let context = "OpenHuman API error (400 Bad Request): \
- {\"error\":{\"errorCode\":\"CONTEXT_LENGTH_EXCEEDED\",\"message\":\"This model's maximum context length is 128000 tokens\"}}";
- for body in [payload, context] {
- let event = event_with_message(body);
- assert!(
- !is_backend_error_code_event(&event),
- "client guard leak must survive before_send: {body}"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn before_send_filter_keeps_malformed_bad_request_event() {
- let event = event_with_message(
- "OpenHuman API error (400 Bad Request): \
- {\"error\":{\"errorCode\":\"BAD_REQUEST\",\"malformed\":true}}",
- );
- assert!(
- !is_backend_error_code_event(&event),
- "malformed BAD_REQUEST must survive before_send and page (F8)"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn before_send_filter_matches_error_code_in_exception_value() {
- let event = event_with_exception_value(&managed_body("500", "INTERNAL_ERROR"));
- assert!(is_backend_error_code_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_provider_transport_filter_drops_flaky_network_blips() {
- // F7: a streaming transport timeout/reset under
- // domain=llm_provider, failure=transport is recovered by
- // retry/fallback — drop it.
- for phrase in [
- "error sending request for url (https://api.tinyhumans.ai/v1/chat): \
- operation timed out",
- "connection reset by peer",
- "tls handshake eof",
- ] {
- for operation in ["stream_chat", "stream_chat_history"] {
- let event = event_with_tags_and_message(
- &[
- ("domain", "llm_provider"),
- ("failure", "transport"),
- ("operation", operation),
- ],
- phrase,
- );
- assert!(
- is_transient_provider_transport_failure(&event),
- "transient transport phrase must be dropped: {phrase} ({operation})"
- );
- }
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_provider_transport_filter_keeps_non_transient_transport() {
- // A genuine, non-transient transport failure (e.g. an unexpected
- // protocol error) is NOT a flaky-network blip — keep paging.
- let event = event_with_tags_and_message(
- &[
- ("domain", "llm_provider"),
- ("failure", "transport"),
- ("operation", "stream_chat"),
- ],
- "invalid URL scheme: unsupported protocol",
- );
- assert!(!is_transient_provider_transport_failure(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_provider_transport_filter_scoped_to_streaming_operations() {
- // CodeRabbit: a NON-streaming llm_provider transport failure with the
- // same domain/failure tags but a different operation must keep paging
- // — the filter is intentionally scoped to the streaming emits.
- let event = event_with_tags_and_message(
- &[
- ("domain", "llm_provider"),
- ("failure", "transport"),
- ("operation", "chat_completions"),
- ],
- "operation timed out",
- );
- assert!(
- !is_transient_provider_transport_failure(&event),
- "non-streaming llm_provider transport must not be suppressed"
- );
-
- // And with no operation tag at all (older/foreign emit) — keep paging.
- let no_op = event_with_tags_and_message(
- &[("domain", "llm_provider"), ("failure", "transport")],
- "operation timed out",
- );
- assert!(!is_transient_provider_transport_failure(&no_op));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn transient_provider_transport_filter_scoped_to_llm_provider() {
- // Same shape under a different domain must not be claimed by this
- // provider-scoped filter.
- let event = event_with_tags_and_message(
- &[
- ("domain", "backend_api"),
- ("failure", "transport"),
- ("operation", "stream_chat"),
- ],
- "operation timed out",
- );
- assert!(!is_transient_provider_transport_failure(&event));
- }
-
- // ── is_auth_get_me_opaque_transport_event ────────────────────────────
- // Covers the TAURI-RUST-10 fingerprint shape: `domain=rpc`,
- // `operation=invoke_method`, `method=openhuman.auth_get_me`, message
- // body = exactly "GET /auth/me" (no underlying chain). See the
- // function docstring + the `auth_get_me` fix in
- // `openhuman::security::credentials::ops::auth_get_me` for the broader
- // context.
-
- #[cfg(feature = "crash-reporting")]
- fn auth_get_me_tags() -> Vec<(&'static str, &'static str)> {
- vec![
- ("domain", "rpc"),
- ("operation", "invoke_method"),
- ("method", "openhuman.auth_get_me"),
- ("elapsed_ms", "5003"),
- ]
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_drops_bare_method_path_message() {
- let event = event_with_tags_and_message(&auth_get_me_tags(), "GET /auth/me");
- assert!(
- is_auth_get_me_opaque_transport_event(&event),
- "bare 'GET /auth/me' message must be dropped (TAURI-RUST-10 shape)"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_tolerates_surrounding_whitespace() {
- let event = event_with_tags_and_message(&auth_get_me_tags(), " GET /auth/me ");
- assert!(
- is_auth_get_me_opaque_transport_event(&event),
- "trimmed equality must still match the opaque shape"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_keeps_full_anyhow_chain_message() {
- // Post-fix shape from `auth_get_me` now using `format!("{e:#}")`.
- let event = event_with_tags_and_message(
- &auth_get_me_tags(),
- "GET /auth/me: error sending request for url \
- (https://api.tinyhumans.ai/auth/me): operation timed out",
- );
- assert!(
- !is_auth_get_me_opaque_transport_event(&event),
- "messages carrying the underlying transport chain must surface — \
- the transient classifier handles those at the rpc dispatcher"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_keeps_other_rpc_methods() {
- // Same opaque shape but for a different RPC must NOT be dropped —
- // we don't have evidence the same anti-pattern exists elsewhere,
- // and a path-only body might be a legitimate distinct error for a
- // future endpoint.
- for method in [
- "openhuman.consume_login_token",
- "openhuman.auth_create_channel_link_token",
- "openhuman.thread_list",
- ] {
- let mut tags = auth_get_me_tags();
- // Replace the method tag.
- if let Some(slot) = tags.iter_mut().find(|(k, _)| *k == "method") {
- slot.1 = method;
- }
- let event = event_with_tags_and_message(&tags, "GET /auth/me");
- assert!(
- !is_auth_get_me_opaque_transport_event(&event),
- "filter must be scoped strictly to method=openhuman.auth_get_me \
- — saw method={method}"
- );
- }
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_requires_rpc_invoke_method_domain() {
- // Wrong domain → must surface.
- let mut tags = auth_get_me_tags();
- if let Some(slot) = tags.iter_mut().find(|(k, _)| *k == "domain") {
- slot.1 = "backend_api";
- }
- let event = event_with_tags_and_message(&tags, "GET /auth/me");
- assert!(!is_auth_get_me_opaque_transport_event(&event));
-
- // Wrong operation → must surface.
- let mut tags = auth_get_me_tags();
- if let Some(slot) = tags.iter_mut().find(|(k, _)| *k == "operation") {
- slot.1 = "post";
- }
- let event = event_with_tags_and_message(&tags, "GET /auth/me");
- assert!(!is_auth_get_me_opaque_transport_event(&event));
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_matches_exception_value_path() {
- // sentry-tracing path: message empty, exception last value carries
- // the body. The filter must still match.
- let mut event = event_with_tags(&auth_get_me_tags());
- event.exception.values.push(sentry::protocol::Exception {
- value: Some("GET /auth/me".to_string()),
- ..Default::default()
- });
- assert!(
- is_auth_get_me_opaque_transport_event(&event),
- "must also catch the exception-value shape (sentry-tracing bridge)"
- );
- }
-
- #[cfg(feature = "crash-reporting")]
- #[test]
- fn auth_get_me_opaque_filter_ignores_empty_and_unrelated() {
- // No message and no exception → false.
- let event = event_with_tags(&auth_get_me_tags());
- assert!(!is_auth_get_me_opaque_transport_event(&event));
-
- // Unrelated message body with the right tags → false.
- let event = event_with_tags_and_message(
- &auth_get_me_tags(),
- "session JWT verified via GET /auth/me on https://api.tinyhumans.ai",
- );
- assert!(
- !is_auth_get_me_opaque_transport_event(&event),
- "substring match must NOT trigger — strict equality only"
- );
- }
-}
diff --git a/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs b/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs
index 918f53a863..f292220e29 100644
--- a/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs
+++ b/crates/openhuman-core/src/memory/tree/tree/rpc_tests.rs
@@ -3,11 +3,12 @@ use chrono::Utc;
use serde_json::json;
use tempfile::TempDir;
// `DocumentInput` (and its `ChatBatch` / `EmailThread` siblings, which
-// `rpc_tests_part_01_tests` reaches the same way) now arrive through the
-// `use super::*` above: they are defined in `rpc_part_01.rs` rather than
-// imported from the engine crate. Naming the engine's copy here would compile
-// and then fail on the first call into `document_item`, since the two are
-// distinct types with identical fields.
+// `rpc_ingest_and_chunk_tests` reaches the same way) now arrive through the
+// `use super::*` above: they are defined in `canonicalize_types.rs` and
+// re-exported through `rpc/ingest.rs`, rather than imported from the engine
+// crate. Naming the engine's copy here would compile and then fail on the
+// first call into `document_item`, since the two are distinct types with
+// identical fields.
use tinymemory_api::chunks::SourceKind;
fn test_config() -> (TempDir, Config) {
diff --git a/crates/openhuman-core/src/voice/server.rs b/crates/openhuman-core/src/voice/server.rs
index 15086f0507..aca9f79d84 100644
--- a/crates/openhuman-core/src/voice/server.rs
+++ b/crates/openhuman-core/src/voice/server.rs
@@ -26,15 +26,21 @@ pub use types::{ServerState, VoiceServerConfig, VoiceServerStatus};
#[cfg(test)]
use pipeline::{
- build_initial_prompt, capture_expected_app_name, process_recording_bg, truncate_for_log,
- update_state_if_current,
+ build_initial_prompt, capture_expected_app_name, process_recording_bg, push_recent_transcript,
+ truncate_for_log, update_state_if_current,
};
#[cfg(test)]
-use pipeline::push_recent_transcript;
-#[cfg(test)]
use types::DEFAULT_SILENCE_THRESHOLD;
#[cfg(test)]
+use crate::config::Config;
+#[cfg(test)]
+use crate::voice::audio_capture::RecordingHandle;
+#[cfg(test)]
use crate::voice::hotkey::ActivationMode;
+#[cfg(test)]
+use std::sync::Arc;
+#[cfg(test)]
+use tokio::sync::Mutex;
const LOG_PREFIX: &str = "[voice_server]";
diff --git a/crates/openhuman-core/src/voice/server_part_01.rs b/crates/openhuman-core/src/voice/server_part_01.rs
deleted file mode 100644
index ef37f22f67..0000000000
--- a/crates/openhuman-core/src/voice/server_part_01.rs
+++ /dev/null
@@ -1,667 +0,0 @@
-use std::sync::atomic::Ordering;
-use std::sync::Arc;
-use std::time::{Duration, Instant};
-
-use log::{debug, info, warn};
-use tokio::sync::Mutex;
-use tokio_util::sync::CancellationToken;
-use uuid::Uuid;
-
-use crate::config::Config;
-#[cfg(target_os = "macos")]
-use crate::desktop::accessibility;
-
-use super::audio_capture::{self, RecordingHandle};
-use super::hotkey::{self, ActivationMode, HotkeyEvent};
-use super::text_input;
-
-const LOG_PREFIX: &str = "[voice_server]";
-
-/// Running state of the voice server.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum ServerState {
- /// Server is not running.
- Stopped,
- /// Server is running and idle, waiting for hotkey.
- Idle,
- /// Actively recording audio.
- Recording,
- /// Transcribing recorded audio.
- Transcribing,
-}
-
-/// Status snapshot of the voice server.
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-pub struct VoiceServerStatus {
- pub state: ServerState,
- pub hotkey: String,
- pub activation_mode: ActivationMode,
- pub transcription_count: u64,
- pub last_error: Option<String>,
-}
-
-/// Default silence threshold (RMS energy). Recordings with peak RMS below
-/// this are considered silent and skipped. Matches OpenWhispr's 0.002 default.
-const DEFAULT_SILENCE_THRESHOLD: f32 = 0.002;
-
-/// Maximum number of recent transcriptions to keep as context for the STT engine's
-/// initial_prompt, improving continuity across consecutive recordings.
-const MAX_RECENT_TRANSCRIPTS: usize = 5;
-
-/// Maximum character length of the combined initial prompt (dictionary +
-/// recent transcripts). The prompt token budget is limited.
-const MAX_INITIAL_PROMPT_CHARS: usize = 500;
-
-/// Configuration for the voice server.
-#[derive(Debug, Clone)]
-pub struct VoiceServerConfig {
- pub hotkey: String,
- pub activation_mode: ActivationMode,
- /// Skip LLM post-processing on transcriptions.
- pub skip_cleanup: bool,
- /// Optional conversation context for better transcription accuracy.
- pub context: Option<String>,
- /// Minimum recording duration in seconds. Shorter recordings are discarded.
- pub min_duration_secs: f32,
- /// RMS energy threshold for silence detection. Recordings with peak
- /// energy below this are treated as silence and skipped.
- pub silence_threshold: f32,
- /// Custom vocabulary words to bias the STT engine toward (passed as initial_prompt).
- pub custom_dictionary: Vec<String>,
-}
-
-impl Default for VoiceServerConfig {
- fn default() -> Self {
- Self {
- hotkey: "Fn".to_string(),
- activation_mode: ActivationMode::Push,
- skip_cleanup: false,
- context: None,
- min_duration_secs: 0.3,
- silence_threshold: DEFAULT_SILENCE_THRESHOLD,
- custom_dictionary: Vec::new(),
- }
- }
-}
-
-/// The voice server runtime.
-pub struct VoiceServer {
- state: Arc<Mutex<ServerState>>,
- /// Wrapped in a Mutex so `run()` can replace it with a fresh token after
- /// `stop()` — a `CancellationToken` cannot be un-cancelled.
- cancel: Mutex<CancellationToken>,
- config: VoiceServerConfig,
- transcription_count: Arc<std::sync::atomic::AtomicU64>,
- session_generation: Arc<std::sync::atomic::AtomicU64>,
- last_error: Arc<Mutex<Option<String>>>,
- /// Rolling buffer of recent transcriptions used as STT context for
- /// better continuity across consecutive recordings.
- recent_transcripts: Arc<Mutex<Vec<String>>>,
-}
-
-impl VoiceServer {
- pub fn new(config: VoiceServerConfig) -> Self {
- Self {
- state: Arc::new(Mutex::new(ServerState::Stopped)),
- cancel: Mutex::new(CancellationToken::new()),
- config,
- transcription_count: Arc::new(std::sync::atomic::AtomicU64::new(0)),
- session_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
- last_error: Arc::new(Mutex::new(None)),
- recent_transcripts: Arc::new(Mutex::new(Vec::new())),
- }
- }
-
- /// Get the current server status.
- pub async fn status(&self) -> VoiceServerStatus {
- VoiceServerStatus {
- state: *self.state.lock().await,
- hotkey: self.config.hotkey.clone(),
- activation_mode: self.config.activation_mode,
- transcription_count: self.transcription_count.load(Ordering::Relaxed),
- last_error: self.last_error.lock().await.clone(),
- }
- }
-
- /// Run the voice server. Blocks until stopped.
- ///
- /// This is the main entry point for both embedded and standalone modes.
- pub async fn run(&self, app_config: &Config) -> Result<(), String> {
- // Atomically transition Stopped → Idle to prevent concurrent run() calls.
- // The globe listener compilation can take several seconds; without this
- // guard the RPC handler sees "Stopped" and spawns a duplicate run().
- //
- // Also replace the cancellation token with a fresh one — a cancelled
- // token cannot be reused (stop() cancels it permanently).
- let cancel = {
- // Lock cancel FIRST, then state — same order as stop() — to
- // prevent a race where stop() cancels the old token between
- // setting Idle and swapping the token.
- let mut cancel_guard = self.cancel.lock().await;
- let mut state = self.state.lock().await;
- if *state != ServerState::Stopped {
- return Err(format!("voice server already running (state={:?})", *state));
- }
-
- let fresh = CancellationToken::new();
- *cancel_guard = fresh.clone();
- *state = ServerState::Idle;
- fresh
- };
-
- info!(
- "{LOG_PREFIX} starting voice server: hotkey={} mode={:?}",
- self.config.hotkey, self.config.activation_mode
- );
-
- // On macOS, the Fn/Globe key is intercepted by the system before
- // rdev's CGEventTap can see it. Use the Swift-based globe listener
- // instead, which monitors NSEvent.flagsChanged for the .function flag.
- let (listener_handle, mut hotkey_rx) = match start_hotkey_listener(
- &self.config.hotkey,
- self.config.activation_mode,
- &cancel,
- ) {
- Ok(pair) => pair,
- Err(e) => {
- *self.state.lock().await = ServerState::Stopped;
- return Err(e);
- }
- };
-
- info!("{LOG_PREFIX} voice server ready, listening for hotkey");
-
- let mut recording: Option<RecordingHandle> = None;
- let mut recording_expected_app: Option<String> = None;
-
- // Pending recording setup: `start_recording()` runs on a blocking
- // thread so the event loop stays responsive to Release events that
- // macOS fires almost immediately for the Fn key.
- let mut recording_pending_rx: Option<
- tokio::sync::oneshot::Receiver<Result<RecordingHandle, String>>,
- > = None;
- let mut pending_expected_app: Option<String> = None;
- let mut pending_generation: Option<u64> = None;
- let mut recording_generation: Option<u64> = None;
- // Set when a stop-intent event (Release/Pressed toggle) arrives before
- // recording has started.
- let mut pending_stop = false;
- // Deferred stop deadline used when stop intent arrives during setup.
- // Keeping this in a select! branch avoids blocking the hotkey loop.
- let mut deferred_stop_deadline: Option<tokio::time::Instant> = None;
-
- /// Minimum recording duration after setup completes. If the user
- /// released the hotkey while cpal was still initialising, we keep
- /// recording for at least this long to capture actual speech.
- const MIN_RECORDING_AFTER_SETUP: Duration = Duration::from_millis(1500);
-
- loop {
- // Build a future that resolves when the pending recording setup
- // completes, or never if there is no pending setup.
- let pending_ready = async {
- match recording_pending_rx.as_mut() {
- Some(rx) => rx.await,
- None => std::future::pending().await,
- }
- };
- let deferred_stop_ready = async {
- match deferred_stop_deadline {
- Some(deadline) => tokio::time::sleep_until(deadline).await,
- None => std::future::pending().await,
- }
- };
-
- tokio::select! {
- ev = hotkey_rx.recv() => {
- let event = match ev {
- Some(e) => e,
- None => {
- warn!("{LOG_PREFIX} hotkey channel closed");
- break;
- }
- };
-
- // Forward hotkey event to the dictation bus so Socket.IO
- // clients receive dictation:toggle events even when the
- // dictation_listener is not running (single rdev listener).
- {
- use super::dictation_listener;
- let event_type = match event {
- HotkeyEvent::Pressed => "pressed",
- HotkeyEvent::Released => "released",
- };
- dictation_listener::publish_dictation_event(
- dictation_listener::DictationEvent {
- event_type: event_type.to_string(),
- hotkey: self.config.hotkey.clone(),
- activation_mode: match self.config.activation_mode {
- ActivationMode::Tap => "toggle".to_string(),
- ActivationMode::Push => "push".to_string(),
- },
- },
- );
- }
-
- match event {
- HotkeyEvent::Pressed => {
- let current_state = *self.state.lock().await;
- info!(
- "{LOG_PREFIX} received hotkey event=Pressed state_before={current_state:?} recording={} pending={}",
- recording.is_some(),
- recording_pending_rx.is_some()
- );
- if recording.is_some() {
- // Recording in progress → stop it (tap toggle or
- // unreliable-release keys like Fn that always send Pressed).
- debug!("{LOG_PREFIX} hotkey pressed while recording → stopping");
- deferred_stop_deadline = None;
- if let Some(handle) = recording.take() {
- self.spawn_process_recording(
- handle,
- app_config,
- recording_generation.take().unwrap_or_default(),
- recording_expected_app.take(),
- );
- }
- } else if recording_pending_rx.is_some() {
- info!("{LOG_PREFIX} hotkey pressed while recording setup pending — buffering stop intent");
- pending_stop = true;
- } else {
- let expected_app = capture_expected_app_name();
- let generation =
- self.session_generation.fetch_add(1, Ordering::Relaxed) + 1;
- debug!("{LOG_PREFIX} hotkey pressed → starting recording (non-blocking)");
- debug!(
- "{LOG_PREFIX} assigned recording generation={} for new session",
- generation
- );
-
- // Start recording on a blocking thread so the
- // event loop remains responsive to Release.
- let (tx, rx) = tokio::sync::oneshot::channel();
- tokio::task::spawn_blocking(move || {
- let result = audio_capture::start_recording();
- let _ = tx.send(result);
- });
- recording_pending_rx = Some(rx);
- pending_expected_app = expected_app;
- pending_generation = Some(generation);
- pending_stop = false;
- deferred_stop_deadline = None;
- *self.state.lock().await = ServerState::Recording;
- }
- }
- HotkeyEvent::Released => {
- info!(
- "{LOG_PREFIX} received hotkey event=Released recording={} pending={}",
- recording.is_some(),
- recording_pending_rx.is_some()
- );
- if let Some(handle) = recording.take() {
- debug!("{LOG_PREFIX} hotkey released → stopping recording");
- deferred_stop_deadline = None;
- self.spawn_process_recording(
- handle,
- app_config,
- recording_generation.take().unwrap_or_default(),
- recording_expected_app.take(),
- );
- } else if recording_pending_rx.is_some() {
- // Release arrived before recording setup finished.
- // Buffer stop intent — we'll handle it once the handle arrives.
- info!("{LOG_PREFIX} release buffered — recording setup still pending");
- pending_stop = true;
- } else {
- debug!("{LOG_PREFIX} release received with no active recording (normal for unreliable-release keys)");
- }
- }
- }
- }
-
- result = pending_ready => {
- // Recording setup completed (or failed).
- recording_pending_rx = None;
- match result {
- Ok(Ok(handle)) => {
- // Check for a buffered stop event that lost the
- // select! race against pending_ready. On warm CPAL
- // init both branches may be ready simultaneously;
- // select! picks one pseudo-randomly, so a Released
- // event can sit unprocessed in hotkey_rx.
- let had_pending_stop = pending_stop;
- if !pending_stop {
- if let Ok(buffered) = hotkey_rx.try_recv() {
- match buffered {
- HotkeyEvent::Released => {
- info!(
- "{LOG_PREFIX} recording handle ready — found buffered Released in hotkey_rx (select! race recovered)"
- );
- pending_stop = true;
- }
- HotkeyEvent::Pressed => {
- // A second Pressed while pending means
- // user wants to stop (tap-style). Treat
- // the same as a stop intent.
- info!(
- "{LOG_PREFIX} recording handle ready — found buffered Pressed in hotkey_rx (treating as stop intent)"
- );
- pending_stop = true;
- }
- }
- }
- }
-
- info!(
- "{LOG_PREFIX} recording handle ready (pending_stop={pending_stop}, was_buffered={})",
- !had_pending_stop && pending_stop
- );
-
- if pending_stop {
- // A stop intent arrived while cpal was initialising.
- // Keep recording for a minimum duration, then stop
- // via non-blocking deferred deadline branch.
- pending_stop = false;
- recording = Some(handle);
- recording_generation = pending_generation.take();
- recording_expected_app = pending_expected_app.take();
-
- info!(
- "{LOG_PREFIX} deferred stop: recording for at least {}ms",
- MIN_RECORDING_AFTER_SETUP.as_millis()
- );
- deferred_stop_deadline = Some(
- tokio::time::Instant::now() + MIN_RECORDING_AFTER_SETUP,
- );
- } else {
- recording = Some(handle);
- recording_generation = pending_generation.take();
- recording_expected_app = pending_expected_app.take();
- deferred_stop_deadline = None;
-
- info!("{LOG_PREFIX} recording started (live)");
- }
- }
- Ok(Err(e)) => {
- pending_stop = false;
- deferred_stop_deadline = None;
- pending_expected_app = None;
- pending_generation = None;
- warn!("{LOG_PREFIX} failed to start recording: {e}");
- *self.state.lock().await = ServerState::Idle;
- *self.last_error.lock().await = Some(e);
- }
- Err(_) => {
- pending_stop = false;
- deferred_stop_deadline = None;
- pending_expected_app = None;
- pending_generation = None;
- warn!("{LOG_PREFIX} recording setup task dropped");
- *self.state.lock().await = ServerState::Idle;
- }
- }
- }
-
- _ = deferred_stop_ready => {
- deferred_stop_deadline = None;
- if let Some(handle) = recording.take() {
- info!(
- "{LOG_PREFIX} deferred stop deadline reached after {}ms, stopping recording",
- MIN_RECORDING_AFTER_SETUP.as_millis()
- );
- self.spawn_process_recording(
- handle,
- app_config,
- recording_generation.take().unwrap_or_default(),
- recording_expected_app.take(),
- );
- }
- }
-
- _ = cancel.cancelled() => {
- debug!("{LOG_PREFIX} cancellation received");
- break;
- }
- }
- }
-
- listener_handle.stop();
- *self.state.lock().await = ServerState::Stopped;
- info!("{LOG_PREFIX} voice server stopped");
-
- Ok(())
- }
-
- /// Stop the voice server and wait for it to reach `Stopped` state.
- ///
- /// Cancels the run-loop token and polls until the state transitions to
- /// `Stopped` (or a 5-second timeout expires). This prevents a fast
- /// logout → login cycle from seeing a stale `Idle`/`Recording` state
- /// and skipping the restart.
- pub async fn stop(&self) {
- info!("{LOG_PREFIX} stopping voice server");
- self.cancel.lock().await.cancel();
-
- // Wait for the run-loop to observe cancellation and set Stopped.
- for _ in 0..50 {
- if *self.state.lock().await == ServerState::Stopped {
- return;
- }
- tokio::time::sleep(std::time::Duration::from_millis(100)).await;
- }
- warn!("{LOG_PREFIX} stop timed out after 5s — state may not be Stopped");
- }
-
- /// Record an error message so it can be surfaced via status().
- pub async fn set_last_error(&self, msg: &str) {
- *self.last_error.lock().await = Some(msg.to_string());
- }
-
- /// Spawn `process_recording` as a background task so the hotkey event
- /// loop is not blocked during transcription. This ensures rapid
- /// consecutive Fn presses are never missed.
- fn spawn_process_recording(
- &self,
- handle: RecordingHandle,
- config: &Config,
- generation: u64,
- expected_app: Option<String>,
- ) {
- let pipeline_id = Uuid::new_v4().to_string()[..8].to_string();
- let state = self.state.clone();
- let server_config = self.config.clone();
- let transcription_count = self.transcription_count.clone();
- let session_generation = self.session_generation.clone();
- let last_error = self.last_error.clone();
- let recent_transcripts = self.recent_transcripts.clone();
- let app_config = config.clone();
-
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] spawning process_recording (generation={generation})"
- );
-
- tokio::spawn(async move {
- process_recording_bg(
- &pipeline_id,
- handle,
- &app_config,
- &server_config,
- state,
- transcription_count,
- session_generation,
- generation,
- last_error,
- recent_transcripts,
- expected_app,
- )
- .await;
- });
- }
-}
-
-// ── Hotkey listener dispatch (rdev vs macOS globe helper) ─────────────
-
-/// Opaque handle that keeps the hotkey listener alive. Drop to stop.
-enum HotkeyListenerKind {
- Rdev(hotkey::HotkeyListenerHandle),
- #[cfg(target_os = "macos")]
- Globe(CancellationToken),
-}
-
-impl HotkeyListenerKind {
- fn stop(&self) {
- match self {
- HotkeyListenerKind::Rdev(handle) => handle.stop(),
- #[cfg(target_os = "macos")]
- HotkeyListenerKind::Globe(cancel) => cancel.cancel(),
- }
- }
-}
-
-/// Start the appropriate hotkey listener for the current platform and key.
-///
-/// On macOS, the Fn/Globe key is handled by the Swift-based globe listener
-/// (`accessibility::globe`) which monitors `NSEvent.flagsChanged`. All other
-/// keys return an error on macOS: rdev's CGEventTap callback calls
-/// `TSMGetInputSourceProperty` off the main thread; macOS 26 enforces
-/// `dispatch_assert_queue(main_queue)` inside that API and kills the process
-/// with `EXC_BREAKPOINT` (`dispatch_assert_queue_fail`). Configure
-/// `hotkey = "fn"` to avoid this. (#2677)
-fn start_hotkey_listener(
- hotkey_str: &str,
- mode: hotkey::ActivationMode,
- server_cancel: &CancellationToken,
-) -> Result<
- (
- HotkeyListenerKind,
- tokio::sync::mpsc::UnboundedReceiver<hotkey::HotkeyEvent>,
- ),
- String,
-> {
- #[cfg(target_os = "macos")]
- {
- if hotkey_str.trim().eq_ignore_ascii_case("fn") {
- return start_globe_hotkey_listener(mode, server_cancel);
- }
- // rdev calls TSMGetInputSourceProperty off the main thread; macOS 26
- // enforces main-queue-only access and crashes the process. Only the
- // Fn/Globe key is safe via the Swift globe listener. (#2677)
- Err(format!(
- "voice server hotkey '{}' is not supported on macOS — \
- only 'fn' (Fn/Globe key) is safe. rdev calls \
- TSMGetInputSourceProperty off the main thread on macOS 26, \
- causing EXC_BREAKPOINT. Set hotkey = \"fn\" in voice config \
- (issue #2677).",
- hotkey_str
- ))
- }
-
- // Non-macOS: rdev-based listener for all keys.
- #[cfg(not(target_os = "macos"))]
- {
- // `server_cancel` is only consumed by the macOS Swift-globe listener
- // branch above; the rdev listener manages its own lifecycle, so bind it
- // here to keep the shared signature warning-free on non-macOS.
- let _ = server_cancel;
- let combo = hotkey::parse_hotkey(hotkey_str)?;
- let (handle, rx) = hotkey::start_listener(combo, mode)?;
- Ok((HotkeyListenerKind::Rdev(handle), rx))
- }
-}
-
-/// macOS-only: start the Swift globe listener and bridge FN_DOWN / FN_UP
-/// events into `HotkeyEvent::Pressed` / `HotkeyEvent::Released`.
-#[cfg(target_os = "macos")]
-fn start_globe_hotkey_listener(
- mode: hotkey::ActivationMode,
- server_cancel: &CancellationToken,
-) -> Result<
- (
- HotkeyListenerKind,
- tokio::sync::mpsc::UnboundedReceiver<hotkey::HotkeyEvent>,
- ),
- String,
-> {
- use crate::desktop::accessibility::{globe_listener_poll, globe_listener_start};
-
- info!("{LOG_PREFIX} hotkey is Fn on macOS — using Swift globe listener instead of rdev");
-
- let status = globe_listener_start()?;
- if !status.running {
- let err_msg = status
- .last_error
- .unwrap_or_else(|| "globe listener failed to start".to_string());
- return Err(format!("globe listener: {err_msg}"));
- }
- info!(
- "{LOG_PREFIX} globe listener started, permission={:?}",
- status.input_monitoring_permission
- );
-
- let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
- let cancel = server_cancel.child_token();
- let cancel_clone = cancel.clone();
-
- // Tap mode state: track whether we're currently active.
- let is_active = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
-
- tokio::spawn(async move {
- let mut poll_interval = tokio::time::interval(Duration::from_millis(50));
- poll_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
-
- loop {
- tokio::select! {
- _ = cancel_clone.cancelled() => {
- debug!("{LOG_PREFIX} globe poller cancelled");
- break;
- }
- _ = poll_interval.tick() => {
- let poll_result = match globe_listener_poll() {
- Ok(r) => r,
- Err(e) => {
- warn!("{LOG_PREFIX} globe poll error: {e}");
- continue;
- }
- };
-
- for event_str in &poll_result.events {
- let hotkey_event = match event_str.as_str() {
- "FN_DOWN" => match mode {
- hotkey::ActivationMode::Push => {
- Some(hotkey::HotkeyEvent::Pressed)
- }
- hotkey::ActivationMode::Tap => {
- let was_active = is_active.load(std::sync::atomic::Ordering::SeqCst);
- if was_active {
- is_active.store(false, std::sync::atomic::Ordering::SeqCst);
- Some(hotkey::HotkeyEvent::Released)
- } else {
- is_active.store(true, std::sync::atomic::Ordering::SeqCst);
- Some(hotkey::HotkeyEvent::Pressed)
- }
- }
- },
- "FN_UP" => match mode {
- hotkey::ActivationMode::Push => {
- Some(hotkey::HotkeyEvent::Released)
- }
- hotkey::ActivationMode::Tap => None, // tap ignores release
- },
- _ => None, // ignore modifier events
- };
-
- if let Some(ev) = hotkey_event {
- debug!("{LOG_PREFIX} globe event {event_str} → {ev:?}");
- if tx.send(ev).is_err() {
- debug!("{LOG_PREFIX} globe poller: receiver dropped, stopping");
- return;
- }
- }
- }
- }
- }
- }
- });
-
- Ok((HotkeyListenerKind::Globe(cancel), rx))
-}
diff --git a/crates/openhuman-core/src/voice/server_part_02.rs b/crates/openhuman-core/src/voice/server_part_02.rs
deleted file mode 100644
index f47009fa84..0000000000
--- a/crates/openhuman-core/src/voice/server_part_02.rs
+++ /dev/null
@@ -1,435 +0,0 @@
-
-// ── Background processing (free functions, spawnable) ─────────────────
-
-/// Capture the frontmost app name at hotkey press so insertion can be validated later.
-#[cfg(target_os = "macos")]
-fn capture_expected_app_name() -> Option<String> {
- match accessibility::focused_text_context_verbose() {
- Ok(ctx) => {
- let app = ctx
- .app_name
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty());
- if let Some(app_name) = app {
- debug!("{LOG_PREFIX} captured focused app on press: '{app_name}'");
- Some(app_name.to_string())
- } else {
- debug!("{LOG_PREFIX} focus query returned no app name on press");
- None
- }
- }
- Err(e) => {
- warn!("{LOG_PREFIX} failed to capture focused app on press: {e}");
- None
- }
- }
-}
-
-#[cfg(not(target_os = "macos"))]
-fn capture_expected_app_name() -> Option<String> {
- None
-}
-
-/// Build the STT initial_prompt from custom dictionary + recent transcripts.
-async fn build_initial_prompt(
- config: &VoiceServerConfig,
- recent_transcripts: &Mutex<Vec<String>>,
-) -> Option<String> {
- let mut parts: Vec<String> = Vec::new();
-
- if !config.custom_dictionary.is_empty() {
- parts.push(config.custom_dictionary.join(", "));
- }
-
- let recent = recent_transcripts.lock().await;
- if !recent.is_empty() {
- parts.push(recent.join(" "));
- }
-
- if parts.is_empty() {
- return None;
- }
-
- let mut prompt = parts.join(". ");
- if prompt.chars().count() > MAX_INITIAL_PROMPT_CHARS {
- prompt = prompt.chars().take(MAX_INITIAL_PROMPT_CHARS).collect();
- if let Some(last_space) = prompt.rfind(' ') {
- prompt.truncate(last_space);
- }
- }
- debug!(
- "{LOG_PREFIX} built initial_prompt ({} chars): '{}'",
- prompt.len(),
- truncate_for_log(&prompt, 100)
- );
- Some(prompt)
-}
-
-/// Add a transcript to the rolling recent buffer.
-async fn push_recent_transcript(recent_transcripts: &Mutex<Vec<String>>, text: &str) {
- let trimmed = text.trim();
- if trimmed.is_empty() {
- return;
- }
- let mut recent = recent_transcripts.lock().await;
- recent.push(trimmed.to_string());
- while recent.len() > MAX_RECENT_TRANSCRIPTS {
- recent.remove(0);
- }
-}
-
-/// Process a completed recording in the background.
-///
-/// This is a free function (not `&self`) so it can be spawned via
-/// `tokio::spawn` without blocking the hotkey event loop. All shared
-/// state is passed as `Arc` handles.
-#[allow(clippy::too_many_arguments)]
-async fn process_recording_bg(
- pipeline_id: &str,
- handle: RecordingHandle,
- config: &Config,
- server_config: &VoiceServerConfig,
- state: Arc<Mutex<ServerState>>,
- transcription_count: Arc<std::sync::atomic::AtomicU64>,
- session_generation: Arc<std::sync::atomic::AtomicU64>,
- generation: u64,
- last_error: Arc<Mutex<Option<String>>>,
- recent_transcripts: Arc<Mutex<Vec<String>>>,
- expected_app: Option<String>,
-) {
- let pipeline_started = Instant::now();
- info!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=start generation={generation}");
- update_state_if_current(
- &state,
- &session_generation,
- generation,
- ServerState::Transcribing,
- "transcribing",
- )
- .await;
-
- let stop_started = Instant::now();
- match handle.stop(config).await {
- Ok(result) => {
- let stop_elapsed = stop_started.elapsed();
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=stop_recording duration={:.1}s bytes={} peak_rms={:.6} stop_elapsed_ms={}",
- result.duration_secs,
- result.wav_bytes.len(),
- result.peak_rms,
- stop_elapsed.as_millis()
- );
-
- // Gate 1: minimum duration.
- if result.duration_secs < server_config.min_duration_secs {
- warn!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_duration DROPPED ({:.1}s < {:.1}s min)",
- result.duration_secs,
- server_config.min_duration_secs
- );
- update_state_if_current(
- &state,
- &session_generation,
- generation,
- ServerState::Idle,
- "idle_after_short_recording",
- )
- .await;
- return;
- }
-
- // Gate 2: silence detection.
- if result.peak_rms < server_config.silence_threshold {
- warn!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_silence DROPPED (peak_rms={:.6} < threshold={:.6})",
- result.peak_rms,
- server_config.silence_threshold
- );
- update_state_if_current(
- &state,
- &session_generation,
- generation,
- ServerState::Idle,
- "idle_after_silence",
- )
- .await;
- return;
- }
-
- // Build initial_prompt from dictionary + recent transcripts.
- let initial_prompt = build_initial_prompt(server_config, &recent_transcripts).await;
- let context = initial_prompt
- .as_deref()
- .or(server_config.context.as_deref());
- if let Some(app) = expected_app.as_deref() {
- debug!("{LOG_PREFIX} [pipeline={pipeline_id}] insertion target: app='{app}'");
- } else {
- debug!("{LOG_PREFIX} [pipeline={pipeline_id}] insertion target unknown");
- }
-
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe skip_cleanup={} context={}",
- server_config.skip_cleanup,
- context.map_or("none".to_string(), |c| format!("{}chars", c.len()))
- );
-
- let transcribe_started = Instant::now();
- match crate::voice::voice_transcribe_bytes(
- config,
- &result.wav_bytes,
- Some("wav".to_string()),
- context,
- server_config.skip_cleanup,
- )
- .await
- {
- Ok(outcome) => {
- let transcribe_elapsed = transcribe_started.elapsed();
- let text = &outcome.value.text;
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcription_result text='{}' chars={} elapsed_ms={}",
- truncate_for_log(text, 80),
- text.len(),
- transcribe_elapsed.as_millis()
- );
-
- // Gate 3: filter hallucinated/blank output.
- //
- // Falls OPEN when the module cannot be reached. Dictation
- // inserts into the user's active text field, so a stray
- // "Thank you." is visible and undoable, while a filter that
- // failed closed would swallow real dictation with no trace.
- let hallucinated =
- match is_hallucinated(config, text, HallucinationMode::Dictation).await {
- Ok(verdict) => verdict,
- Err(error) => {
- warn!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_hallucination \
- UNAVAILABLE ({error}); passing text through"
- );
- false
- }
- };
- if hallucinated {
- warn!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_hallucination DROPPED text='{}'",
- truncate_for_log(text, 60)
- );
- update_state_if_current(
- &state,
- &session_generation,
- generation,
- ServerState::Idle,
- "idle_after_hallucination",
- )
- .await;
- return;
- }
-
- if !text.trim().is_empty() {
- push_recent_transcript(&recent_transcripts, text).await;
-
- // When the Tauri app itself is focused, deliver via
- // Socket.IO so the frontend inserts into the chat.
- // Otherwise paste via OS-level Cmd+V into the
- // external app.
- let is_self = expected_app
- .as_deref()
- .map(|app| app.to_lowercase().contains("openhuman"))
- .unwrap_or(false);
-
- if is_self {
- let receivers =
- super::dictation_listener::publish_transcription(text.to_string());
- transcription_count.fetch_add(1, Ordering::Relaxed);
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_socketio receivers={receivers} total_pipeline_ms={}",
- pipeline_started.elapsed().as_millis()
- );
- } else {
- let insert_started = Instant::now();
- if let Err(e) = text_input::insert_text(text, expected_app.as_deref()) {
- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_paste FAILED: {e}");
- *last_error.lock().await = Some(e);
- } else {
- let insert_elapsed = insert_started.elapsed();
- transcription_count.fetch_add(1, Ordering::Relaxed);
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=deliver_paste insert_ms={} total_pipeline_ms={}",
- insert_elapsed.as_millis(),
- pipeline_started.elapsed().as_millis()
- );
- }
- }
- } else {
- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=gate_empty DROPPED (transcription was blank)");
- }
- }
- Err(e) => {
- // Windows DLL-not-found errors are classified at the
- // subprocess layer and logged with a 5-minute backoff.
- // Demote to warn! so they don't flood Sentry (issue #5168).
- if e.contains("STATUS_DLL_NOT_FOUND") {
- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe DLL_UNAVAILABLE: {e}");
- } else {
- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=transcribe FAILED: {e}");
- }
- *last_error.lock().await = Some(e);
- }
- }
- }
- Err(e) => {
- warn!("{LOG_PREFIX} [pipeline={pipeline_id}] stage=stop_recording FAILED: {e}");
- *last_error.lock().await = Some(e);
- }
- }
-
- info!(
- "{LOG_PREFIX} [pipeline={pipeline_id}] stage=done total_pipeline_ms={}",
- pipeline_started.elapsed().as_millis()
- );
- update_state_if_current(
- &state,
- &session_generation,
- generation,
- ServerState::Idle,
- "idle_after_processing",
- )
- .await;
-}
-
-async fn update_state_if_current(
- state: &Arc<Mutex<ServerState>>,
- session_generation: &Arc<std::sync::atomic::AtomicU64>,
- generation: u64,
- next_state: ServerState,
- reason: &str,
-) {
- let latest_generation = session_generation.load(Ordering::Relaxed);
- if latest_generation != generation {
- debug!(
- "{LOG_PREFIX} skipped stale state update reason={} generation={} latest_generation={} next_state={next_state:?}",
- reason,
- generation,
- latest_generation
- );
- return;
- }
-
- debug!(
- "{LOG_PREFIX} state update reason={} generation={} next_state={next_state:?}",
- reason, generation
- );
- *state.lock().await = next_state;
-}
-
-/// Global voice server instance, lazily initialized.
-static VOICE_SERVER: once_cell::sync::OnceCell<Arc<VoiceServer>> = once_cell::sync::OnceCell::new();
-
-/// Get or initialize the global voice server instance.
-pub fn global_server(config: VoiceServerConfig) -> Arc<VoiceServer> {
- VOICE_SERVER
- .get_or_init(|| Arc::new(VoiceServer::new(config)))
- .clone()
-}
-
-/// Get the global voice server if already initialized.
-pub fn try_global_server() -> Option<Arc<VoiceServer>> {
- VOICE_SERVER.get().cloned()
-}
-
-/// Start the embedded global voice server when config enables auto-start.
-///
-/// This is intended for core process startup. The server runs in the background
-/// and reuses the process-global singleton so RPC status/stop calls continue to
-/// operate on the same instance.
-pub async fn start_if_enabled(app_config: &Config) {
- if !app_config.voice_server.auto_start {
- info!("{LOG_PREFIX} auto-start disabled in config, skipping embedded voice server");
- return;
- }
-
- let server_config = VoiceServerConfig {
- hotkey: app_config.voice_server.hotkey.clone(),
- activation_mode: match app_config.voice_server.activation_mode {
- crate::config::VoiceActivationMode::Tap => ActivationMode::Tap,
- crate::config::VoiceActivationMode::Push => ActivationMode::Push,
- },
- skip_cleanup: app_config.voice_server.skip_cleanup,
- context: None,
- min_duration_secs: app_config.voice_server.min_duration_secs,
- silence_threshold: app_config.voice_server.silence_threshold,
- custom_dictionary: app_config.voice_server.custom_dictionary.clone(),
- };
-
- if let Some(existing) = try_global_server() {
- let status = existing.status().await;
- if status.state != ServerState::Stopped {
- info!(
- "{LOG_PREFIX} embedded voice server already running: hotkey={} mode={:?}",
- status.hotkey, status.activation_mode
- );
- return;
- }
- }
-
- info!(
- "{LOG_PREFIX} auto-start enabled, launching embedded voice server: hotkey={} mode={:?}",
- server_config.hotkey, server_config.activation_mode
- );
-
- let server = global_server(server_config);
- let config_for_run = app_config.clone();
- let server_for_err = server.clone();
- tokio::spawn(async move {
- if let Err(e) = server.run(&config_for_run).await {
- warn!("{LOG_PREFIX} embedded voice server exited with error: {e}");
- server_for_err.set_last_error(&e).await;
- }
- });
-}
-
-/// Run the voice server standalone (blocking). Intended for CLI usage.
-///
-/// Creates a fresh `VoiceServer` that is **not** registered in the global
-/// singleton used by `voice_server_status` RPC. This keeps CLI-started
-/// instances isolated from the core RPC lifecycle.
-pub async fn run_standalone(
- app_config: Config,
- server_config: VoiceServerConfig,
-) -> Result<(), String> {
- info!("{LOG_PREFIX} starting standalone voice server");
- info!("{LOG_PREFIX} hotkey: {}", server_config.hotkey);
- info!("{LOG_PREFIX} mode: {:?}", server_config.activation_mode);
- info!("{LOG_PREFIX} press the hotkey to start dictating");
-
- let server = VoiceServer::new(server_config);
-
- // Handle Ctrl+C gracefully.
- let server_arc = Arc::new(server);
- let server_for_signal = server_arc.clone();
-
- tokio::spawn(async move {
- if let Ok(()) = tokio::signal::ctrl_c().await {
- info!("{LOG_PREFIX} Ctrl+C received, shutting down");
- server_for_signal.stop().await;
- }
- });
-
- // This is safe because we hold the Arc and nothing else moves it.
- // The server.run() borrows &self, and we await it to completion.
- server_arc.run(&app_config).await
-}
-
-// Hallucination detection is now in the shared `hallucination` module.
-use crate::modules::voice::{is_hallucinated, HallucinationMode};
-
-fn truncate_for_log(s: &str, max: usize) -> String {
- let truncated: String = s.chars().take(max).collect();
- if truncated.len() < s.len() {
- format!("{truncated}...")
- } else {
- truncated
- }
-}