From ac0ca0f4a63c6f2ff62af17e6f226ae4fba45921 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 13:16:42 +0000 Subject: [PATCH 1/8] fix(backend): surface errorCode and opt-in error text for non-2xx backend failures Diagnoses gemini live/sessions 400 (#8501): Sentry only carried the body shape. Append a safe, identifier-like errorCode to the report and add an opt-in (OPENHUMAN_LOG_BACKEND_ERROR_TEXT) debug log of error/details text. Client request unchanged; root cause is likely server-side (see FINDINGS-gemini-live.md). Co-Authored-By: Claude Sonnet 5.5 --- FINDINGS-gemini-live.md | 56 +++++++++++++++ .../src/client/backend_client_tests.rs | 28 +++++++- .../src/client/classify.rs | 68 ++++++++++++++++++- 3 files changed, 150 insertions(+), 2 deletions(-) create mode 100644 FINDINGS-gemini-live.md diff --git a/FINDINGS-gemini-live.md b/FINDINGS-gemini-live.md new file mode 100644 index 00000000000..7c5e0906691 --- /dev/null +++ b/FINDINGS-gemini-live.md @@ -0,0 +1,56 @@ +# FINDINGS: gemini live/sessions 400 (TAURI-RUST-13BR, #8501) + +## Verdict +Root cause NOT determinable from client code or git history. No client-side +regression found; the request body is unchanged since the feature landed. +Hypothesis: server-side validation rejection (different repo). Only +observability was changed. + +## Found +- Client: `crates/openhuman-tinyhumans/src/voice/live.rs::mint_gemini_ticket` + (v0.64.15: `crates/openhuman-core/src/voice/live/providers.rs`, identical logic) + does `BackendClient::authed_json(cred, POST, "/agent-integrations/gemini/live/sessions", Some(body))`. +- Auth: session JWT as `Authorization: Bearer`, or API key as `x-api-key` + (transport layer, JSON content-type via `send_json`). No query params. +- Body: `tinyliveagents::gemini::ticket_request(live)` + (`vendor/tinyagents/vendor/tinyliveagents/.../gemini/setup.rs`), a flat object: + `mode:"conversation"`, `model` (user setting or default `gemini-3.8-live`), + `responseModalities:["AUDIO"]`, optional `speechConfig` (voice/languageCode), + `systemInstruction.parts[].text`, optional `tools`, `realtimeInputConfig`, + `contextWindowCompression:{slidingWindow:{}}`, optional `maxMinutes`. +- History: the endpoint/feature was added 2026-10-06/07 (e2609bdc64, 6e81614943 + etc.), all before v0.64.15 (2026-10-09). The vendored tinyliveagents `gemini/` + sources are byte-identical between the v0.64.15 pin (91664e7) and the current + checkout (e10e6eb). The move to `openhuman-tinyhumans` did not change the body + or path. No renamed/removed/mistyped field or content-type change found, so + "began 2026-10-08" most likely coincides with release/rollout, not a client diff. +- The failing response is the standard envelope `{success,error,errorCode,details}` + (len 182). Its text was never in telemetry: `classify.rs` reports only the + shape to Sentry (the 512-byte body does go into the returned error string). +- Suspects for the server to check (unverified guesses, not evidence): the + `model` id `gemini-3.8-live` default / user-set model not accepted; the + `contextWindowCompression`/`realtimeInputConfig` passthrough fields not in the + backend's schema; unknown top-level keys under strict validation; payload size + of `systemInstruction`. + +## Changed +`crates/openhuman-tinyhumans/src/client/classify.rs` (+ tests in +`backend_client_tests.rs`), applies to all authed_json non-2xx reports: +- Sentry message now appends `error_code=` only when it is a short + ASCII identifier (<=40 chars, same filter as safe key names). +- New opt-in gate `OPENHUMAN_LOG_BACKEND_ERROR_TEXT=1|true|yes|on`: logs the + backend `error` and `details` text (each truncated to 300 bytes) at + `tracing::debug!`. Off by default; never added to the Sentry report, since + values are server-controlled free text. + +## Verified +- `cargo check -p openhuman-tinyhumans` could NOT be completed: the base + (upstream/main 218d35f4b9, verified identical failure with my change stashed) + does not compile, with 401 errors in `openhuman-core`, e.g. unresolved + `tinychannels_bus::module_progressive::ChannelOutputEvent`, `tinychannels_bus::web`, + `ContentPart`. The `vendor/tinychannels` pin (f83b2a80) appears out of sync with + core. That is a vendor/submodule issue and was not edited. Needs a + tinychannels pin bump (or core fix) upstream. +- Instead, the new pure functions and their two unit tests were extracted into a + scratch crate (serde_json only) and pass (2/2). `cargo fmt` was run. The + in-repo test module was not run for the reason above. diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs index a8fa8c098df..92200c73a77 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -1,6 +1,7 @@ use super::*; use crate::client::classify::{ - backend_api_body_shape, BACKEND_API_BODY_SHAPE_MAX_BYTES, BACKEND_API_ERROR_BODY_MAX_BYTES, + backend_api_body_shape, backend_api_error_code, backend_api_error_text, + BACKEND_API_BODY_SHAPE_MAX_BYTES, BACKEND_API_ERROR_BODY_MAX_BYTES, }; use crate::client::{flatten_authed_error, HostedApiError}; use axum::extract::State; @@ -394,3 +395,28 @@ async fn non_2xx_error_body_is_truncated_in_the_returned_error() { message.len() ); } + +#[test] +fn backend_api_error_code_only_echoes_identifier_like_codes() { + let body = r#"{"success":false,"error":"x","errorCode":"INVALID_ARGUMENT"}"#; + assert_eq!( + backend_api_error_code(body).as_deref(), + Some("INVALID_ARGUMENT") + ); + let free_text = r#"{"errorCode":"bad value for jo@example.com"}"#; + assert_eq!(backend_api_error_code(free_text), None); + assert_eq!(backend_api_error_code("not json"), None); +} + +#[test] +fn backend_api_error_text_extracts_error_and_details_truncated() { + let body = + r#"{"success":false,"error":"Bad Request","errorCode":"E","details":["model: unknown"]}"#; + let text = backend_api_error_text(body).unwrap(); + assert!(text.contains("error=Bad Request"), "{text}"); + assert!(text.contains(r#"details=["model: unknown"]"#), "{text}"); + let long = format!(r#"{{"error":"{}"}}"#, "a".repeat(2000)); + assert!(backend_api_error_text(&long).unwrap().len() < 400); + assert_eq!(backend_api_error_text(r#"{"success":true}"#), None); + assert_eq!(backend_api_error_text(""), None); +} diff --git a/crates/openhuman-tinyhumans/src/client/classify.rs b/crates/openhuman-tinyhumans/src/client/classify.rs index b38b3c0ff56..688476444e9 100644 --- a/crates/openhuman-tinyhumans/src/client/classify.rs +++ b/crates/openhuman-tinyhumans/src/client/classify.rs @@ -54,6 +54,56 @@ pub(super) fn backend_api_body_shape(body: &str) -> String { } } +/// Max bytes of each of the backend's `error` / `details` text echoed by the +/// opt-in diagnostic log (see [`backend_error_text_logging_enabled`]). +pub(super) const BACKEND_API_ERROR_TEXT_MAX_BYTES: usize = 300; + +/// Env flag that opts in to logging the backend's `error` / `details` text. +/// Off by default: those values are server-controlled free text and may echo +/// user content, so they are never put in Sentry reports. +const LOG_BACKEND_ERROR_TEXT_ENV: &str = "OPENHUMAN_LOG_BACKEND_ERROR_TEXT"; + +fn backend_error_text_logging_enabled() -> bool { + std::env::var(LOG_BACKEND_ERROR_TEXT_ENV) + .map(|v| { + matches!( + v.trim().to_ascii_lowercase().as_str(), + "1" | "true" | "yes" | "on" + ) + }) + .unwrap_or(false) +} + +/// The backend's `errorCode`, only when it is a short ASCII identifier (an +/// enum-like code such as `INVALID_ARGUMENT`), so it is safe for telemetry. +pub(super) fn backend_api_error_code(body: &str) -> Option { + let value = serde_json::from_str::(body.trim()).ok()?; + let code = value.get("errorCode")?.as_str()?; + is_schema_like_key(code).then(|| code.to_string()) +} + +/// The backend's `error` and `details` text (the standard +/// `{success,error,errorCode,details}` failure envelope), each truncated. +/// Contains server-controlled values: for the opt-in local log only. +pub(super) fn backend_api_error_text(body: &str) -> Option { + let value = serde_json::from_str::(body.trim()).ok()?; + let render = |v: &Value| match v { + Value::String(s) => s.clone(), + other => other.to_string(), + }; + let mut parts = Vec::new(); + for key in ["error", "details"] { + if let Some(v) = value.get(key).filter(|v| !v.is_null()) { + let text = render(v); + parts.push(format!( + "{key}={}", + truncate_at_byte_boundary(&text, BACKEND_API_ERROR_TEXT_MAX_BYTES) + )); + } + } + (!parts.is_empty()).then(|| parts.join("; ")) +} + /// A JSON key safe to echo into telemetry: a short ASCII identifier. fn is_schema_like_key(key: &str) -> bool { const MAX_KEY_LEN: usize = 40; @@ -238,13 +288,29 @@ impl BackendClient { let host = url.host_str().unwrap_or(""); let body_shape = backend_api_body_shape(&text); let status_str = status_code.to_string(); + let error_code = backend_api_error_code(&text) + .map(|c| format!("; error_code={c}")) + .unwrap_or_default(); + if backend_error_text_logging_enabled() { + if let Some(detail) = backend_api_error_text(&text) { + tracing::debug!( + method = method.as_str(), + path = url.path(), + status = status_code, + "[backend_api] {} {} failed ({status}): {detail}", + method.as_str(), + url.path(), + ); + } + } report_error( format!( - "{} {} failed ({status}); response_body_len={}; body_shape={}", + "{} {} failed ({status}); response_body_len={}; body_shape={}{}", method.as_str(), url.path(), text.len(), body_shape, + error_code, ) .as_str(), "backend_api", From f4a6d45ec2c568f79ca4bd34eea94c1900ee84f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 13:21:02 +0000 Subject: [PATCH 2/8] fix(tinyhumans): warn-log backend errorCode on non-2xx responses Complements the errorCode/opt-in error-text diagnostics from the previous commit: also emit a warn line carrying only the identifier-shaped errorCode (no raw body), and add a test for non-identifier / non-string codes. Co-Authored-By: Claude Sonnet 5.5 --- FINDINGS-voice-signed-url.md | 46 +++++++++++++++++++ .../src/client/backend_client_tests.rs | 12 +++++ .../src/client/classify.rs | 13 ++++++ 3 files changed, 71 insertions(+) create mode 100644 FINDINGS-voice-signed-url.md diff --git a/FINDINGS-voice-signed-url.md b/FINDINGS-voice-signed-url.md new file mode 100644 index 00000000000..1c1ed493ada --- /dev/null +++ b/FINDINGS-voice-signed-url.md @@ -0,0 +1,46 @@ +# FINDINGS: voice-agent signed-url 403 (TAURI-RUST-11G3, GitHub #8504) + +## Found +- Caller: `mint_voice_agent_signed_url` in `crates/openhuman-tinyhumans/src/voice/realtime.rs` + (used by `voice/live.rs` and the `voice/schemas.rs` RPC). It does + `resolve_backend_credential(config)` (API key -> `x-api-key`, else session JWT -> Bearer), + `ensure_secure_backend_url`, then `BackendClient::authed_json(GET /voice-agent/get-signed-url, no body)`. +- Auth/header handling lives in `crates/openhuman-tinyhumans/src/client/` + `transport/`. 401 is + mapped to typed `Unauthorized`/`ApiKeyRejected` (session-expiry, not reported). 403 is + deliberately not treated as session expiry (test `authed_json_403_is_not_demoted_to_unauthorized`), + so it falls through to `report_error` with only `response_body_len` + `body_shape`. +- A 403 means the credential WAS accepted (a bad/expired one would be 401 and is handled + separately) but the backend refused it for this route. The request is a bodyless GET with the + same credential path as every other authed call, so I found no client-side malformed/missing + field or header. The git history of `voice/realtime.rs` and `client/backend_client.rs` shows only + refactors (credential module moves, TinySecurity migration), no change to this endpoint's auth flow. +- Telemetry only has the body shape `keys=[error,errorCode,success]`; the actual `error`/`errorCode` + values are not available, so the reason for the 403 cannot be determined from this repo. + +## Hypothesis (not fixed: no client-side defect found) +Most likely server-side entitlement/authorization in the TinyHumans backend repo (e.g. the account +or plan not permitted to use voice-agent, or the backend rejecting API-key credentials / a +particular account state for `/voice-agent/*`). Only ~17 users, consistent with a per-account +condition rather than a systemic client regression. Unconfirmed: needs the `errorCode` (now +captured, below) or backend logs. + +## Changed +- `client/classify.rs`: new `backend_api_error_code(body)` extracts the backend `errorCode` only if + it is a short ASCII identifier (reuses `is_schema_like_key`), and it is appended to the + `report_error` message as `error_code=` and emitted on a `tracing::warn!`. This applies + to all reported non-2xx backend responses, so 403s become distinguishable/groupable in Sentry. + The free-text `error` value is intentionally NOT added to the report/log: the existing + PII guard (#4058) states raw bodies must not reach pre-scrub logs. (The returned error string + still carries the first 512 bytes of the body to the caller, unchanged.) +- Test `backend_api_error_code_only_echoes_identifier_shaped_codes` in `client/backend_client_tests.rs`. + +## Verified +- The `backend_api_error_code` logic was verified in an isolated scratch crate (asserts pass). +- `cargo test -p openhuman-tinyhumans` / `cargo check` could NOT be run: the `openhuman-core` + (`openhuman` lib) dependency fails to compile with ~400 errors on an UNMODIFIED + upstream/main checkout (confirmed via `git stash`). Examples: `tinychannels_bus::ContentPart` + / `MediaReference` / `OutboundVoice` not found, `ReleaseAsset` missing `library_sha256`, + `TurnRunnerConfig` has no `cancel_grace`, `SecretStorageError::MasterKeyUnavailable` not covered. + All `vendor/*` submodules match the commits recorded in HEAD, so the pinned submodule revisions + appear out of sync with core source. This is a vendor/submodule-pin issue; I did not edit vendor/. + The edit was `cargo fmt`ed. diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs index 92200c73a77..d64a9e178bd 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -408,6 +408,18 @@ fn backend_api_error_code_only_echoes_identifier_like_codes() { assert_eq!(backend_api_error_code("not json"), None); } +#[test] +fn backend_api_error_code_rejects_non_identifier_and_non_string_codes() { + let body = r#"{"success":false,"error":"jo@example.com is not entitled","errorCode":"FORBIDDEN_PLAN"}"#; + assert_eq!( + backend_api_error_code(body).as_deref(), + Some("FORBIDDEN_PLAN") + ); + assert_eq!(backend_api_error_code(r#"{"errorCode":7}"#), None); + assert_eq!(backend_api_error_code(r#"{"error":"x"}"#), None); + assert_eq!(backend_api_error_code("Forbidden"), None); +} + #[test] fn backend_api_error_text_extracts_error_and_details_truncated() { let body = diff --git a/crates/openhuman-tinyhumans/src/client/classify.rs b/crates/openhuman-tinyhumans/src/client/classify.rs index 688476444e9..84391b38ca7 100644 --- a/crates/openhuman-tinyhumans/src/client/classify.rs +++ b/crates/openhuman-tinyhumans/src/client/classify.rs @@ -291,6 +291,19 @@ impl BackendClient { let error_code = backend_api_error_code(&text) .map(|c| format!("; error_code={c}")) .unwrap_or_default(); + // Only the identifier-shaped `errorCode` is logged here: the raw + // body may hold PII and the report message precedes Sentry scrubbing. + tracing::warn!( + domain = "backend_api", + operation = "authed_json", + method = method.as_str(), + path = url.path(), + status = status_code, + error_code = backend_api_error_code(&text).as_deref().unwrap_or(""), + "[backend_api] {} {} failed ({status})", + method.as_str(), + url.path(), + ); if backend_error_text_logging_enabled() { if let Some(detail) = backend_api_error_text(&text) { tracing::debug!( From d7d7ed2159b1d7b99c933ca587a3040e7e6671e4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 14:20:24 +0000 Subject: [PATCH 3/8] docs(findings): revise gemini 400 and signed-url 403 root-cause analysis Live voice first shipped in v0.64.14 (2026-10-08), so the gemini 400 is a launch-day rejection, not a regression; the leading suspect is the tool declarations in the ticket body. The signed-url 403 coincides with the new elevenlabs-hosted provider, which is offered without an entitlement check. Co-Authored-By: Claude Opus 5.5 --- FINDINGS-gemini-live.md | 54 +++++++++++++++++++++++++++++------- FINDINGS-voice-signed-url.md | 29 ++++++++++++++----- 2 files changed, 66 insertions(+), 17 deletions(-) diff --git a/FINDINGS-gemini-live.md b/FINDINGS-gemini-live.md index 7c5e0906691..2df71cbc3b7 100644 --- a/FINDINGS-gemini-live.md +++ b/FINDINGS-gemini-live.md @@ -1,11 +1,44 @@ # FINDINGS: gemini live/sessions 400 (TAURI-RUST-13BR, #8501) ## Verdict -Root cause NOT determinable from client code or git history. No client-side -regression found; the request body is unchanged since the feature landed. -Hypothesis: server-side validation rejection (different repo). Only +Root cause NOT confirmed. This is not a regression: live voice (including the +`gemini-hosted` provider) first shipped in v0.64.14 on 2026-10-08, the day the +issue began, so the request has most likely been rejected since launch. +Leading hypothesis: the backend rejects the *content* of the ticket body, most +likely the agent's tool declarations (see "Revised analysis"). Only observability was changed. +## Revised analysis (second pass) +- Release timeline: the first commit with the hosted Gemini route + (e9aa12b395, 2026-10-07) is first contained in v0.64.14 (tagged + 2026-10-08). v0.64.15 differs from v0.64.14 only by version bumps and the + `vendor/tinybus` pin; no voice code changed. So "began 2026-10-08" is the + feature launch, and comparing history for a renamed field was the wrong test. +- Why it is systemic: `gemini-hosted` is the default live provider + (`default_provider()` in `config/schema/voice_live.rs`), and it counts as + "configured" whenever any backend credential exists. +- Call path: app `LiveVoiceControls` (session over the core's + `/ws/live-voice`) or the `LiveVoicePanel` test button → + `voice/live/session.rs::start` / `ops.rs::live_test_provider` → + `providers::prepare` → `mint_gemini_ticket` → POST. +- Field names match the backend contract: every key the client sends exists, + in the right camelCase, on `GeminiLiveConversation` in + `vendor/tinyhumans-sdk/src/api/agent_integrations/gemini.rs`, and + `gemini-3.8-live` is a documented model there. The route is in the SDK + manifest synced from backend `main` (`tests/openapi_sync.rs`, 208 -> 211). +- What does not match is the content: the SDK's only test body is + `{"mode":"conversation","model":"gemini-3.8-live","tools":[{"googleSearch":{}}]}`. + The real client sends the full agent tool catalogue as + `functionDeclarations` (`session.rs` sets + `live.tools = tinyagents_live::tool_declarations(&harness, false)` before + minting) plus a long system prompt. Nothing in the repo shows the backend + accepting that payload. The `details` key in the 400 envelope fits a + validation error. +- Discriminating test (not run: it calls the real backend): with a dev + account, POST the SDK's minimal body. 200 → the client payload is the + cause; re-add `tools`, then `systemInstruction`, etc. to find the field. + 400 → server-side. + ## Found - Client: `crates/openhuman-tinyhumans/src/voice/live.rs::mint_gemini_ticket` (v0.64.15: `crates/openhuman-core/src/voice/live/providers.rs`, identical logic) @@ -22,16 +55,17 @@ observability was changed. etc.), all before v0.64.15 (2026-10-09). The vendored tinyliveagents `gemini/` sources are byte-identical between the v0.64.15 pin (91664e7) and the current checkout (e10e6eb). The move to `openhuman-tinyhumans` did not change the body - or path. No renamed/removed/mistyped field or content-type change found, so - "began 2026-10-08" most likely coincides with release/rollout, not a client diff. + or path. No renamed/removed/mistyped field or content-type change found; + "began 2026-10-08" is the v0.64.14 feature launch (see above). - The failing response is the standard envelope `{success,error,errorCode,details}` (len 182). Its text was never in telemetry: `classify.rs` reports only the shape to Sentry (the 512-byte body does go into the returned error string). -- Suspects for the server to check (unverified guesses, not evidence): the - `model` id `gemini-3.8-live` default / user-set model not accepted; the - `contextWindowCompression`/`realtimeInputConfig` passthrough fields not in the - backend's schema; unknown top-level keys under strict validation; payload size - of `systemInstruction`. +- Suspects for the server to check, in order (unverified): the + `functionDeclarations` (a tool name or schema the backend rejects, or the + tool count/size); the size of `systemInstruction`. The first-pass guesses + (the `gemini-3.8-live` model id, the `contextWindowCompression` / + `realtimeInputConfig` fields) are less likely: both appear in the SDK's + backend contract. ## Changed `crates/openhuman-tinyhumans/src/client/classify.rs` (+ tests in diff --git a/FINDINGS-voice-signed-url.md b/FINDINGS-voice-signed-url.md index 1c1ed493ada..0ea9cac94fe 100644 --- a/FINDINGS-voice-signed-url.md +++ b/FINDINGS-voice-signed-url.md @@ -17,14 +17,28 @@ - Telemetry only has the body shape `keys=[error,errorCode,success]`; the actual `error`/`errorCode` values are not available, so the reason for the 403 cannot be determined from this repo. -## Hypothesis (not fixed: no client-side defect found) -Most likely server-side entitlement/authorization in the TinyHumans backend repo (e.g. the account -or plan not permitted to use voice-agent, or the backend rejecting API-key credentials / a -particular account state for `/voice-agent/*`). Only ~17 users, consistent with a per-account -condition rather than a systemic client regression. Unconfirmed: needs the `errorCode` (now -captured, below) or backend logs. +## Revised analysis (second pass) +- The endpoint is old: it first shipped in v0.64.0 (94ffd992d3, 2026-08-05, #5407), and its auth + path in v0.64.15 (`crates/openhuman-core/src/voice/realtime.rs`) is unchanged. +- What v0.64.14 (2026-10-08) changed is reach: it added a second caller. Before, only the + `voice.agent_signed_url` RPC called the endpoint; now the new `elevenlabs-hosted` live-voice + provider (`prepare_elevenlabs`) does too. +- That provider is gated only by `backend_ready()`, which checks that a backend credential + exists (`resolve_backend_credential(..).is_ok()`), with no plan or entitlement check. So every + signed-in user is offered hosted ElevenLabs in the live-voice picker. + +## Hypothesis (not fixed: no client-side request defect found) +The backend refuses users who are not entitled to the hosted ElevenLabs agent (plan or account +state), and v0.64.14 exposed the endpoint to them through the new picker. That fits the small +count (~17). If so, the server is right to refuse; the client-side defect is offering the provider +without an entitlement check and surfacing a generic failure. Unconfirmed. To confirm: the +backend's `error` text for one of these 403s (the `errorCode` is now captured, below), and whether +TAURI-RUST-11G3 appears on v0.64.13 or earlier in Sentry. ## Changed +Merged into `fix/gemini-live-400-and-voice-403` with workstream A. Workstream A's +`backend_api_error_code` (same behaviour) was kept; this workstream adds the `tracing::warn!` +line and an extra test. The original standalone change was: - `client/classify.rs`: new `backend_api_error_code(body)` extracts the backend `errorCode` only if it is a short ASCII identifier (reuses `is_schema_like_key`), and it is appended to the `report_error` message as `error_code=` and emitted on a `tracing::warn!`. This applies @@ -32,7 +46,8 @@ captured, below) or backend logs. The free-text `error` value is intentionally NOT added to the report/log: the existing PII guard (#4058) states raw bodies must not reach pre-scrub logs. (The returned error string still carries the first 512 bytes of the body to the caller, unchanged.) -- Test `backend_api_error_code_only_echoes_identifier_shaped_codes` in `client/backend_client_tests.rs`. +- Test `backend_api_error_code_only_echoes_identifier_shaped_codes` in `client/backend_client_tests.rs` + (kept on the merged branch as `backend_api_error_code_rejects_non_identifier_and_non_string_codes`). ## Verified - The `backend_api_error_code` logic was verified in an isolated scratch crate (asserts pass). From 49fe5b28b8dac61babeec351ed33f47ad00344ec Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 16:58:10 +0000 Subject: [PATCH 4/8] fix(voice): classify hosted live-voice billing refusals instead of reporting them The backend refuses a Gemini Live session with a 400 `USER_INSUFFICIENT_CREDITS` when the balance is below the per-session reserve (TAURI-RUST-13BR), and the voice-agent signed URL with a 403 "requires a paid plan" / "Insufficient balance ... Add credits" (TAURI-RUST-11G3). Neither matched the 400-only budget phrase filter, so both paged Sentry and the UI showed the raw backend line. authed_json now reads the errorCode and the 403 billing messages, logs them at info, and returns typed InsufficientCredits / PaidPlanRequired errors that flatten onto new INSUFFICIENT_CREDITS: / PAID_PLAN_REQUIRED: sentinels, which expected_error_kind demotes. The hosted live providers map them to the insufficient_credits / paid_plan_required session codes, and the live voice controls show translated "add credits" / "paid plan" messages. Co-Authored-By: Claude Opus 5.5 --- FINDINGS-gemini-live.md | 48 +++++++- FINDINGS-voice-signed-url.md | 23 ++++ .../features/human/LiveVoiceControls.test.tsx | 2 + app/src/features/human/LiveVoiceControls.tsx | 6 + app/src/lib/i18n/ar.ts | 2 + app/src/lib/i18n/bn.ts | 2 + app/src/lib/i18n/de.ts | 2 + app/src/lib/i18n/en.ts | 2 + app/src/lib/i18n/es.ts | 2 + app/src/lib/i18n/fr.ts | 2 + app/src/lib/i18n/hi.ts | 2 + app/src/lib/i18n/id.ts | 2 + app/src/lib/i18n/it.ts | 2 + app/src/lib/i18n/ja.ts | 2 + app/src/lib/i18n/ko.ts | 2 + app/src/lib/i18n/pl.ts | 2 + app/src/lib/i18n/pt.ts | 2 + app/src/lib/i18n/ru.ts | 2 + app/src/lib/i18n/tr.ts | 2 + app/src/lib/i18n/zh-CN.ts | 2 + .../openhuman-core/src/core/observability.rs | 5 +- .../src/core/observability_availability.rs | 18 +++ ...y_error_classification_user_state_tests.rs | 25 ++++ ...rvability_expected_error_classification.rs | 7 +- crates/openhuman-embed/src/host_internals.rs | 4 +- .../src/client/backend_client_tests.rs | 115 +++++++++++++++++- .../src/client/classify.rs | 72 +++++++++++ .../openhuman-tinyhumans/src/client/error.rs | 42 ++++++- crates/openhuman-tinyhumans/src/voice/live.rs | 23 +++- .../src/voice/live_tests.rs | 14 +++ 30 files changed, 426 insertions(+), 10 deletions(-) diff --git a/FINDINGS-gemini-live.md b/FINDINGS-gemini-live.md index 2df71cbc3b7..2ed26a06c51 100644 --- a/FINDINGS-gemini-live.md +++ b/FINDINGS-gemini-live.md @@ -1,6 +1,52 @@ # FINDINGS: gemini live/sessions 400 (TAURI-RUST-13BR, #8501) -## Verdict +## Verdict (final, backend-confirmed) +**User billing state, not a request defect.** The 400 is the backend's balance gate: +`tinyhumansai/backend` @ 6af8f69, `src/controllers/agentIntegrations/gemini/liveSessions.ts:119-125` +throws `BadRequestError("Gemini Live requires an available balance of at least $X.XX (reserved per +open session)", {reserveUsd}, USER_INSUFFICIENT_CREDITS)` when the user's balance is below the +per-session reserve. Serialized through `errorHandler.ts` that body is +`{"success":false,"error":"Gemini Live requires an available balance of at least $1.00 (reserved per open session)","errorCode":"USER_INSUFFICIENT_CREDITS","details":{"reserveUsd":1}}`, +exactly **182 bytes with keys `details,error,errorCode,success`**, matching the Sentry shape. The +request body passes the backend's strict zod schema (`validators/agentIntegration.validator.ts:278-305`; +`functionDeclarations` max 128, `tools` max 10), which rules out the tool-declaration hypothesis below. +It is systemic because `gemini-hosted` is the default live provider and counts as configured for every +signed-in user, whatever their balance. + +Why it reached Sentry: the client's budget filter keys on phrases ("insufficient balance", "add +credits", ...), and this message contains none of them; the `errorCode` was never read. + +## Fix (this branch) +- `client/classify.rs`: `backend_billing_refusal(status, body)` classifies an + `errorCode: USER_INSUFFICIENT_CREDITS` envelope (any status) and the voice-agent 403 billing + messages (see FINDINGS-voice-signed-url.md). Those are info-logged, **not** `report_error`ed, and + returned as typed `HostedApiError::InsufficientCredits` / `PaidPlanRequired`. +- `client/error.rs`: the two variants display in the generic ` failed (): ` + shape and flatten onto new `INSUFFICIENT_CREDITS:` / `PAID_PLAN_REQUIRED:` sentinels. +- `openhuman-core` observability: the sentinels (`observability_availability.rs`, re-exported through + embed) classify as `ExpectedErrorKind::BudgetExhausted`, so a re-report at any boundary is demoted. +- `voice/live.rs`: `mint_error` maps the sentinels to live-session codes `insufficient_credits` / + `paid_plan_required` (Gemini and ElevenLabs hosted mints). +- App: `LiveVoiceControls.tsx` `errorText` shows "Live voice needs more credits. Add credits to + continue." / "Live voice requires a paid plan. Upgrade to continue." instead of the raw backend line; + both keys translated in all 16 locales. +- Not done (product decision): hiding or de-defaulting the hosted live providers for users below the + reserve. `backend_ready()` still only checks that a credential exists. + +## Verification of the fix +- In-tree `cargo check`/`test` still impossible (vendor pins, see below). `cargo check -p openhuman + --tests` gives the **same error set** with and without this change (880 vs 881 lines, identical + after normalizing line numbers, none in touched files). +- `backend_billing_refusal`, the two error variants and `flatten_authed_error` were compiled verbatim + in a scratch crate together with the in-repo pure tests (the real 182-byte body, both 403 messages, + non-matches) and pass. The axum round-trip test, `mint_error` test, core classifier test and the + Vitest case were added but not run (no compiling tree; no pnpm/node_modules on this box). All 16 + locale files were parsed with node and carry both keys exactly once. + +--- +Earlier analysis, kept for the record (superseded by the verdict above): + +## Verdict (first/second pass) Root cause NOT confirmed. This is not a regression: live voice (including the `gemini-hosted` provider) first shipped in v0.64.14 on 2026-10-08, the day the issue began, so the request has most likely been rejected since launch. diff --git a/FINDINGS-voice-signed-url.md b/FINDINGS-voice-signed-url.md index 0ea9cac94fe..aa21a6edc23 100644 --- a/FINDINGS-voice-signed-url.md +++ b/FINDINGS-voice-signed-url.md @@ -1,5 +1,28 @@ # FINDINGS: voice-agent signed-url 403 (TAURI-RUST-11G3, GitHub #8504) +## Verdict (final, backend-confirmed) +**User billing state.** `tinyhumansai/backend` @ 6af8f69, `src/controllers/voiceAgent/getSignedUrl.ts:48-56` +answers `ForbiddenError` (`errorCode: FORBIDDEN`, no `details`, matching the Sentry shape +`keys=[error,errorCode,success]`) with either: +- "Voice sessions require a paid plan." (free plan), or +- "Insufficient balance to start a voice session. Add credits to continue." (balance below + `VOICE_AGENT_MIN_BALANCE_USD`, default $1). + +The client's budget filter only runs on status 400, so these 403s went to Sentry, and the UI showed the +raw backend line. The second-pass hypothesis below (entitlement exposed by the new +`elevenlabs-hosted` picker) was right in kind; the backend source settles which gate it is. + +## Fix +Shared with TAURI-RUST-13BR, see FINDINGS-gemini-live.md "Fix": a 403 whose `error` names a paid plan +becomes `HostedApiError::PaidPlanRequired`; one matching the budget phrases (here "insufficient +balance" / "add credits") becomes `InsufficientCredits`. Both are kept out of Sentry and shown in the +live-voice UI as "requires a paid plan" / "add credits". A 403 with any other message (e.g. a plain +"Forbidden") still reports. The `voice.agent_signed_url` RPC path gets the same sentinel and the same +`BudgetExhausted` demotion. + +--- +Earlier analysis, kept for the record: + ## Found - Caller: `mint_voice_agent_signed_url` in `crates/openhuman-tinyhumans/src/voice/realtime.rs` (used by `voice/live.rs` and the `voice/schemas.rs` RPC). It does diff --git a/app/src/features/human/LiveVoiceControls.test.tsx b/app/src/features/human/LiveVoiceControls.test.tsx index 92432f8610f..8b600f3ecc7 100644 --- a/app/src/features/human/LiveVoiceControls.test.tsx +++ b/app/src/features/human/LiveVoiceControls.test.tsx @@ -114,6 +114,8 @@ describe('LiveVoiceControls', () => { ['mic_denied', /Microphone access was denied/], ['mic_unavailable', /No microphone is available/], ['connection_failed', /Couldn't connect/], + ['insufficient_credits', /Add credits to continue/], + ['paid_plan_required', /requires a paid plan/], ['provider_down', /provider exploded/], ])('shows the %s error with a retry', (code, text) => { session.current = makeSession({ diff --git a/app/src/features/human/LiveVoiceControls.tsx b/app/src/features/human/LiveVoiceControls.tsx index e8043222841..6f4f399172b 100644 --- a/app/src/features/human/LiveVoiceControls.tsx +++ b/app/src/features/human/LiveVoiceControls.tsx @@ -64,6 +64,12 @@ function errorText(t: (key: string) => string, error: LiveVoiceError): string { case 'connection_failed': case 'core_unreachable': return t('voice.live.error.connection'); + // The backend refused the hosted session on billing grounds; its raw + // message is a backend failure line, not user-facing copy. + case 'insufficient_credits': + return t('voice.live.error.insufficientCredits'); + case 'paid_plan_required': + return t('voice.live.error.paidPlanRequired'); default: return error.message || t('voice.live.error.connection'); } diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts index bc881025856..d572b49075f 100644 --- a/app/src/lib/i18n/ar.ts +++ b/app/src/lib/i18n/ar.ts @@ -4266,6 +4266,8 @@ const messages: TranslationMap = { 'تم رفض الوصول إلى الميكروفون. اسمح به من إعدادات النظام ثم حاول مرة أخرى.', 'voice.live.error.micUnavailable': 'لا يتوفر ميكروفون.', 'voice.live.error.connection': 'تعذّر الاتصال بالوكيل الصوتي.', + 'voice.live.error.insufficientCredits': 'يحتاج الصوت المباشر إلى رصيد إضافي. أضف رصيدًا للمتابعة.', + 'voice.live.error.paidPlanRequired': 'يتطلب الصوت المباشر خطة مدفوعة. قم بالترقية للمتابعة.', 'voice.live.toolRunning': 'جارٍ تشغيل {name}', 'voice.live.toolOk': 'اكتمل {name}', 'voice.live.toolFailed': 'فشل {name}', diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts index a7bea4ce33d..074215dd5e8 100644 --- a/app/src/lib/i18n/bn.ts +++ b/app/src/lib/i18n/bn.ts @@ -4352,6 +4352,8 @@ const messages: TranslationMap = { 'মাইক্রোফোনের অনুমতি দেওয়া হয়নি। সিস্টেম সেটিংসে অনুমতি দিয়ে আবার চেষ্টা করুন।', 'voice.live.error.micUnavailable': 'কোনো মাইক্রোফোন পাওয়া যায়নি।', 'voice.live.error.connection': 'ভয়েস এজেন্টের সাথে সংযোগ করা যায়নি।', + 'voice.live.error.insufficientCredits': 'লাইভ ভয়েসের জন্য আরও ক্রেডিট প্রয়োজন। চালিয়ে যেতে ক্রেডিট যোগ করুন।', + 'voice.live.error.paidPlanRequired': 'লাইভ ভয়েসের জন্য একটি পেইড প্ল্যান প্রয়োজন। চালিয়ে যেতে আপগ্রেড করুন।', 'voice.live.toolRunning': '{name} চলছে', 'voice.live.toolOk': '{name} সম্পন্ন', 'voice.live.toolFailed': '{name} ব্যর্থ হয়েছে', diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts index 1df14f2fe0d..b49e9fc9381 100644 --- a/app/src/lib/i18n/de.ts +++ b/app/src/lib/i18n/de.ts @@ -4494,6 +4494,8 @@ const messages: TranslationMap = { 'Der Mikrofonzugriff wurde verweigert. Erlaube ihn in den Systemeinstellungen und versuche es erneut.', 'voice.live.error.micUnavailable': 'Kein Mikrofon verfügbar.', 'voice.live.error.connection': 'Verbindung zum Sprachagenten fehlgeschlagen.', + 'voice.live.error.insufficientCredits': 'Für Live-Sprache brauchst du mehr Guthaben. Lade Guthaben auf, um fortzufahren.', + 'voice.live.error.paidPlanRequired': 'Live-Sprache erfordert einen kostenpflichtigen Tarif. Führe ein Upgrade durch, um fortzufahren.', 'voice.live.toolRunning': '{name} läuft', 'voice.live.toolOk': '{name} abgeschlossen', 'voice.live.toolFailed': '{name} fehlgeschlagen', diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.ts index 89f70dfea27..07407cf5997 100644 --- a/app/src/lib/i18n/en.ts +++ b/app/src/lib/i18n/en.ts @@ -4632,6 +4632,8 @@ const en: TranslationMap = { 'Microphone access was denied. Allow it in your system settings and try again.', 'voice.live.error.micUnavailable': 'No microphone is available.', 'voice.live.error.connection': "Couldn't connect to the voice agent.", + 'voice.live.error.insufficientCredits': 'Live voice needs more credits. Add credits to continue.', + 'voice.live.error.paidPlanRequired': 'Live voice requires a paid plan. Upgrade to continue.', 'voice.live.toolRunning': 'Running {name}', 'voice.live.toolOk': '{name} finished', 'voice.live.toolFailed': '{name} failed', diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts index 58e63aad286..6deb6fa9efe 100644 --- a/app/src/lib/i18n/es.ts +++ b/app/src/lib/i18n/es.ts @@ -4446,6 +4446,8 @@ const messages: TranslationMap = { 'Se denegó el acceso al micrófono. Permítelo en la configuración del sistema e inténtalo de nuevo.', 'voice.live.error.micUnavailable': 'No hay ningún micrófono disponible.', 'voice.live.error.connection': 'No se pudo conectar con el agente de voz.', + 'voice.live.error.insufficientCredits': 'La voz en directo necesita más créditos. Añade créditos para continuar.', + 'voice.live.error.paidPlanRequired': 'La voz en directo requiere un plan de pago. Mejora tu plan para continuar.', 'voice.live.toolRunning': 'Ejecutando {name}', 'voice.live.toolOk': '{name} completado', 'voice.live.toolFailed': '{name} falló', diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts index 1b454ba2e17..a23a53d08f4 100644 --- a/app/src/lib/i18n/fr.ts +++ b/app/src/lib/i18n/fr.ts @@ -4469,6 +4469,8 @@ const messages: TranslationMap = { "L'accès au micro a été refusé. Autorisez-le dans les réglages système puis réessayez.", 'voice.live.error.micUnavailable': 'Aucun micro disponible.', 'voice.live.error.connection': "Impossible de se connecter à l'agent vocal.", + 'voice.live.error.insufficientCredits': 'La voix en direct nécessite plus de crédits. Ajoutez des crédits pour continuer.', + 'voice.live.error.paidPlanRequired': 'La voix en direct nécessite un forfait payant. Passez à un forfait supérieur pour continuer.', 'voice.live.toolRunning': '{name} en cours', 'voice.live.toolOk': '{name} terminé', 'voice.live.toolFailed': 'Échec de {name}', diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts index d8190e97945..769be7eb6da 100644 --- a/app/src/lib/i18n/hi.ts +++ b/app/src/lib/i18n/hi.ts @@ -4357,6 +4357,8 @@ const messages: TranslationMap = { 'माइक्रोफ़ोन की अनुमति नहीं मिली। सिस्टम सेटिंग में अनुमति दें और फिर कोशिश करें।', 'voice.live.error.micUnavailable': 'कोई माइक्रोफ़ोन उपलब्ध नहीं है।', 'voice.live.error.connection': 'वॉइस एजेंट से कनेक्ट नहीं हो सका।', + 'voice.live.error.insufficientCredits': 'लाइव वॉइस के लिए और क्रेडिट चाहिए। जारी रखने के लिए क्रेडिट जोड़ें।', + 'voice.live.error.paidPlanRequired': 'लाइव वॉइस के लिए पेड प्लान ज़रूरी है। जारी रखने के लिए अपग्रेड करें।', 'voice.live.toolRunning': '{name} चल रहा है', 'voice.live.toolOk': '{name} पूरा हुआ', 'voice.live.toolFailed': '{name} विफल रहा', diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts index 3163f538f2b..fe911e3e493 100644 --- a/app/src/lib/i18n/id.ts +++ b/app/src/lib/i18n/id.ts @@ -4395,6 +4395,8 @@ const messages: TranslationMap = { 'Akses mikrofon ditolak. Izinkan di pengaturan sistem lalu coba lagi.', 'voice.live.error.micUnavailable': 'Tidak ada mikrofon yang tersedia.', 'voice.live.error.connection': 'Tidak dapat terhubung ke agen suara.', + 'voice.live.error.insufficientCredits': 'Suara langsung memerlukan lebih banyak kredit. Tambahkan kredit untuk melanjutkan.', + 'voice.live.error.paidPlanRequired': 'Suara langsung memerlukan paket berbayar. Tingkatkan paket untuk melanjutkan.', 'voice.live.toolRunning': 'Menjalankan {name}', 'voice.live.toolOk': '{name} selesai', 'voice.live.toolFailed': '{name} gagal', diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts index df8db1800ef..02a7f42b21d 100644 --- a/app/src/lib/i18n/it.ts +++ b/app/src/lib/i18n/it.ts @@ -4430,6 +4430,8 @@ const messages: TranslationMap = { "L'accesso al microfono è stato negato. Consentilo nelle impostazioni di sistema e riprova.", 'voice.live.error.micUnavailable': 'Nessun microfono disponibile.', 'voice.live.error.connection': "Impossibile connettersi all'agente vocale.", + 'voice.live.error.insufficientCredits': 'La voce dal vivo richiede più crediti. Aggiungi crediti per continuare.', + 'voice.live.error.paidPlanRequired': 'La voce dal vivo richiede un piano a pagamento. Passa a un piano superiore per continuare.', 'voice.live.toolRunning': '{name} in esecuzione', 'voice.live.toolOk': '{name} completato', 'voice.live.toolFailed': '{name} non riuscito', diff --git a/app/src/lib/i18n/ja.ts b/app/src/lib/i18n/ja.ts index 4759957a746..80788600a93 100644 --- a/app/src/lib/i18n/ja.ts +++ b/app/src/lib/i18n/ja.ts @@ -4638,6 +4638,8 @@ const messages: TranslationMap = { 'マイクへのアクセスが拒否されました。システム設定で許可してから、もう一度お試しください。', 'voice.live.error.micUnavailable': '利用可能なマイクがありません。', 'voice.live.error.connection': '音声エージェントに接続できませんでした。', + 'voice.live.error.insufficientCredits': 'ライブ音声にはクレジットが不足しています。続けるにはクレジットを追加してください。', + 'voice.live.error.paidPlanRequired': 'ライブ音声には有料プランが必要です。続けるにはアップグレードしてください。', 'voice.live.toolRunning': '{name}を実行中', 'voice.live.toolOk': '{name}が完了しました', 'voice.live.toolFailed': '{name}が失敗しました', diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts index 214ff2319ea..e539855398e 100644 --- a/app/src/lib/i18n/ko.ts +++ b/app/src/lib/i18n/ko.ts @@ -4302,6 +4302,8 @@ const messages: TranslationMap = { '마이크 접근이 거부되었습니다. 시스템 설정에서 허용한 뒤 다시 시도하세요.', 'voice.live.error.micUnavailable': '사용 가능한 마이크가 없습니다.', 'voice.live.error.connection': '음성 에이전트에 연결할 수 없습니다.', + 'voice.live.error.insufficientCredits': '실시간 음성에 크레딧이 더 필요합니다. 계속하려면 크레딧을 추가하세요.', + 'voice.live.error.paidPlanRequired': '실시간 음성은 유료 플랜이 필요합니다. 계속하려면 업그레이드하세요.', 'voice.live.toolRunning': '{name} 실행 중', 'voice.live.toolOk': '{name} 완료', 'voice.live.toolFailed': '{name} 실패', diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts index ea3e2231b7e..1c3761b01df 100644 --- a/app/src/lib/i18n/pl.ts +++ b/app/src/lib/i18n/pl.ts @@ -4417,6 +4417,8 @@ const messages: TranslationMap = { 'Odmówiono dostępu do mikrofonu. Zezwól na niego w ustawieniach systemu i spróbuj ponownie.', 'voice.live.error.micUnavailable': 'Brak dostępnego mikrofonu.', 'voice.live.error.connection': 'Nie udało się połączyć z agentem głosowym.', + 'voice.live.error.insufficientCredits': 'Głos na żywo wymaga więcej środków. Doładuj środki, aby kontynuować.', + 'voice.live.error.paidPlanRequired': 'Głos na żywo wymaga płatnego planu. Przejdź na wyższy plan, aby kontynuować.', 'voice.live.toolRunning': 'Trwa {name}', 'voice.live.toolOk': 'Ukończono {name}', 'voice.live.toolFailed': 'Błąd: {name}', diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts index 1b09462293b..67ad3c00b65 100644 --- a/app/src/lib/i18n/pt.ts +++ b/app/src/lib/i18n/pt.ts @@ -4419,6 +4419,8 @@ const messages: TranslationMap = { 'O acesso ao microfone foi negado. Permita-o nas configurações do sistema e tente novamente.', 'voice.live.error.micUnavailable': 'Nenhum microfone disponível.', 'voice.live.error.connection': 'Não foi possível conectar ao agente de voz.', + 'voice.live.error.insufficientCredits': 'A voz ao vivo precisa de mais créditos. Adicione créditos para continuar.', + 'voice.live.error.paidPlanRequired': 'A voz ao vivo requer um plano pago. Faça upgrade para continuar.', 'voice.live.toolRunning': 'Executando {name}', 'voice.live.toolOk': '{name} concluído', 'voice.live.toolFailed': '{name} falhou', diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts index 59951ebdc59..372a7b1af98 100644 --- a/app/src/lib/i18n/ru.ts +++ b/app/src/lib/i18n/ru.ts @@ -4401,6 +4401,8 @@ const messages: TranslationMap = { 'Доступ к микрофону запрещён. Разрешите его в настройках системы и попробуйте снова.', 'voice.live.error.micUnavailable': 'Микрофон недоступен.', 'voice.live.error.connection': 'Не удалось подключиться к голосовому агенту.', + 'voice.live.error.insufficientCredits': 'Для голоса в реальном времени нужно больше кредитов. Пополните баланс, чтобы продолжить.', + 'voice.live.error.paidPlanRequired': 'Для голоса в реальном времени нужен платный тариф. Перейдите на него, чтобы продолжить.', 'voice.live.toolRunning': 'Выполняется {name}', 'voice.live.toolOk': '{name} завершено', 'voice.live.toolFailed': 'Ошибка: {name}', diff --git a/app/src/lib/i18n/tr.ts b/app/src/lib/i18n/tr.ts index 128a7508d96..738f05b4e09 100644 --- a/app/src/lib/i18n/tr.ts +++ b/app/src/lib/i18n/tr.ts @@ -4289,6 +4289,8 @@ const messages: TranslationMap = { 'Mikrofon erişimi reddedildi. Sistem ayarlarınızdan izin verip yeniden deneyin.', 'voice.live.error.micUnavailable': 'Kullanılabilir mikrofon yok.', 'voice.live.error.connection': 'Ses ajanına bağlanılamadı.', + 'voice.live.error.insufficientCredits': 'Canlı ses için daha fazla kredi gerekiyor. Devam etmek için kredi ekleyin.', + 'voice.live.error.paidPlanRequired': 'Canlı ses ücretli bir plan gerektirir. Devam etmek için planınızı yükseltin.', 'voice.live.toolRunning': '{name} çalışıyor', 'voice.live.toolOk': '{name} tamamlandı', 'voice.live.toolFailed': '{name} başarısız oldu', diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.ts index 79677e04733..56fda43a905 100644 --- a/app/src/lib/i18n/zh-CN.ts +++ b/app/src/lib/i18n/zh-CN.ts @@ -4106,6 +4106,8 @@ const messages: TranslationMap = { 'voice.live.error.micDenied': '麦克风访问被拒绝。请在系统设置中允许后重试。', 'voice.live.error.micUnavailable': '没有可用的麦克风。', 'voice.live.error.connection': '无法连接到语音助手。', + 'voice.live.error.insufficientCredits': '实时语音需要更多额度。请充值后继续。', + 'voice.live.error.paidPlanRequired': '实时语音需要付费套餐。请升级后继续。', 'voice.live.toolRunning': '正在运行 {name}', 'voice.live.toolOk': '{name} 已完成', 'voice.live.toolFailed': '{name} 失败', diff --git a/crates/openhuman-core/src/core/observability.rs b/crates/openhuman-core/src/core/observability.rs index 9aac3997e9d..893e6a2ea8a 100644 --- a/crates/openhuman-core/src/core/observability.rs +++ b/crates/openhuman-core/src/core/observability.rs @@ -34,8 +34,9 @@ pub use release_tag::is_stale_release_event; mod availability; use availability::log_module_unavailable; pub use availability::{ - is_api_key_rejected_message, is_backend_unavailable_message, is_module_unavailable_message, - API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, + is_api_key_rejected_message, is_backend_unavailable_message, is_hosted_billing_refusal_message, + is_module_unavailable_message, API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, + INSUFFICIENT_CREDITS_PREFIX, PAID_PLAN_REQUIRED_PREFIX, }; /// A `(key, value)` pair attached as a Sentry tag. Tags are short, indexed, diff --git a/crates/openhuman-core/src/core/observability_availability.rs b/crates/openhuman-core/src/core/observability_availability.rs index 98fd8ba0e01..317eeb3f5ba 100644 --- a/crates/openhuman-core/src/core/observability_availability.rs +++ b/crates/openhuman-core/src/core/observability_availability.rs @@ -19,6 +19,24 @@ pub const BACKEND_UNAVAILABLE_PREFIX: &str = "BACKEND_UNAVAILABLE:"; /// change. pub const API_KEY_REJECTED_PREFIX: &str = "API_KEY_REJECTED:"; +/// Sentinel prefix on the error string a backend call returns when the backend +/// refuses a gated hosted feature because the account balance is too low (an +/// `errorCode: USER_INSUFFICIENT_CREDITS` response, or a 403 asking the user to +/// add credits). [`super::expected_error_kind`] demotes it: the fix is a top-up, +/// not a code change. +pub const INSUFFICIENT_CREDITS_PREFIX: &str = "INSUFFICIENT_CREDITS:"; + +/// Sentinel prefix on the error string a backend call returns when the backend +/// refuses a hosted feature that needs a paid plan (a 403). Demoted like +/// [`INSUFFICIENT_CREDITS_PREFIX`]. +pub const PAID_PLAN_REQUIRED_PREFIX: &str = "PAID_PLAN_REQUIRED:"; + +/// Whether `msg` carries the [`INSUFFICIENT_CREDITS_PREFIX`] or +/// [`PAID_PLAN_REQUIRED_PREFIX`] sentinel anywhere in its chain. +pub fn is_hosted_billing_refusal_message(msg: &str) -> bool { + msg.contains(INSUFFICIENT_CREDITS_PREFIX) || msg.contains(PAID_PLAN_REQUIRED_PREFIX) +} + /// Whether `msg` carries the [`API_KEY_REJECTED_PREFIX`] sentinel anywhere in /// its chain. pub fn is_api_key_rejected_message(msg: &str) -> bool { diff --git a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs index a0662809e20..639ff264e71 100644 --- a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs +++ b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs @@ -726,3 +726,28 @@ fn connector_provider_output_is_already_reported_without_affecting_other_modules ); } } + +#[test] +fn classifies_hosted_billing_refusals_as_budget_exhausted() { + // TAURI-RUST-13BR / -11G3: the hosted client flattens a live-voice billing + // refusal onto these sentinels. The Gemini reserve message matches no + // budget phrase, so only the sentinel keeps it out of Sentry. + let credits = format!( + "{INSUFFICIENT_CREDITS_PREFIX}POST /live failed (400): {{\"error\":\"Gemini Live requires an available balance of at least $1.00 (reserved per open session)\",\"errorCode\":\"USER_INSUFFICIENT_CREDITS\"}}" + ); + let plan = format!("{PAID_PLAN_REQUIRED_PREFIX}GET /signed-url failed (403): {{}}"); + for msg in [credits, plan] { + assert!(is_hosted_billing_refusal_message(&msg), "{msg}"); + assert!( + matches!( + expected_error_kind(&msg), + Some(ExpectedErrorKind::BudgetExhausted) + ), + "{msg}" + ); + } + // A bare mention of the word is not the sentinel. + assert!(!is_hosted_billing_refusal_message( + "insufficient_credits counter overflowed" + )); +} diff --git a/crates/openhuman-core/src/core/observability_expected_error_classification.rs b/crates/openhuman-core/src/core/observability_expected_error_classification.rs index f7090e25f48..46ba4d9aeda 100644 --- a/crates/openhuman-core/src/core/observability_expected_error_classification.rs +++ b/crates/openhuman-core/src/core/observability_expected_error_classification.rs @@ -233,7 +233,12 @@ pub fn expected_error_kind(message: &str) -> Option { if is_local_ai_capability_unavailable_message(&lower) { return Some(ExpectedErrorKind::LocalAiCapabilityUnavailable); } - if tinyinference_providers::is_budget_exhausted_message(message) { + // TAURI-RUST-13BR / -11G3 — the backend refused a gated hosted feature + // (live voice) because the balance is below its reserve or the plan is + // free. Billing user state, same bucket as an exhausted budget. + if tinyinference_providers::is_budget_exhausted_message(message) + || is_hosted_billing_refusal_message(message) + { return Some(ExpectedErrorKind::BudgetExhausted); } if is_backend_unavailable_message(message) { diff --git a/crates/openhuman-embed/src/host_internals.rs b/crates/openhuman-embed/src/host_internals.rs index 8b0c0a1c7dc..daf8578a108 100644 --- a/crates/openhuman-embed/src/host_internals.rs +++ b/crates/openhuman-embed/src/host_internals.rs @@ -41,8 +41,8 @@ pub mod core { is_session_expired_message, is_suppressed_usage_probe_backoff, is_transient_http_status_code, is_transient_message_failure, report_error, report_error_or_expected, report_warning_message, ExpectedErrorKind, - API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, REPORT_ERROR_TRACING_TARGET, - USAGE_PROBE_BACKOFF_PREFIX, + API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, INSUFFICIENT_CREDITS_PREFIX, + PAID_PLAN_REQUIRED_PREFIX, REPORT_ERROR_TRACING_TARGET, USAGE_PROBE_BACKOFF_PREFIX, }; } diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs index d64a9e178bd..e8a5edeb5b8 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -1,7 +1,8 @@ use super::*; use crate::client::classify::{ backend_api_body_shape, backend_api_error_code, backend_api_error_text, - BACKEND_API_BODY_SHAPE_MAX_BYTES, BACKEND_API_ERROR_BODY_MAX_BYTES, + backend_billing_refusal, BillingRefusal, BACKEND_API_BODY_SHAPE_MAX_BYTES, + BACKEND_API_ERROR_BODY_MAX_BYTES, }; use crate::client::{flatten_authed_error, HostedApiError}; use axum::extract::State; @@ -432,3 +433,115 @@ fn backend_api_error_text_extracts_error_and_details_truncated() { assert_eq!(backend_api_error_text(r#"{"success":true}"#), None); assert_eq!(backend_api_error_text(""), None); } + +/// The exact 182-byte body behind TAURI-RUST-13BR (backend +/// `gemini/liveSessions.ts`): balance below the Gemini Live session reserve. +const GEMINI_LIVE_RESERVE_BODY: &str = r#"{"success":false,"error":"Gemini Live requires an available balance of at least $1.00 (reserved per open session)","errorCode":"USER_INSUFFICIENT_CREDITS","details":{"reserveUsd":1}}"#; + +#[test] +fn backend_billing_refusal_classifies_the_live_voice_gates() { + assert_eq!(GEMINI_LIVE_RESERVE_BODY.len(), 182); + assert_eq!( + backend_billing_refusal(400, GEMINI_LIVE_RESERVE_BODY), + Some(BillingRefusal::InsufficientCredits) + ); + // TAURI-RUST-11G3: the voice-agent signed-url gate answers 403 FORBIDDEN. + let balance = r#"{"success":false,"error":"Insufficient balance to start a voice session. Add credits to continue.","errorCode":"FORBIDDEN"}"#; + assert_eq!( + backend_billing_refusal(403, balance), + Some(BillingRefusal::InsufficientCredits) + ); + let plan = r#"{"success":false,"error":"Voice sessions require a paid plan.","errorCode":"FORBIDDEN"}"#; + assert_eq!( + backend_billing_refusal(403, plan), + Some(BillingRefusal::PaidPlanRequired) + ); +} + +#[test] +fn backend_billing_refusal_leaves_other_failures_alone() { + // A real 403 (wrong role) and a validation 400 must keep reaching Sentry. + let forbidden = r#"{"success":false,"error":"Forbidden","errorCode":"FORBIDDEN"}"#; + assert_eq!(backend_billing_refusal(403, forbidden), None); + let invalid = r#"{"success":false,"error":"Invalid request","errorCode":"VALIDATION_ERROR","details":{}}"#; + assert_eq!(backend_billing_refusal(400, invalid), None); + // The billing wording only counts on a 403, and only in the `error` field. + let paid_400 = r#"{"success":false,"error":"Voice sessions require a paid plan.","errorCode":"BAD_REQUEST"}"#; + assert_eq!(backend_billing_refusal(400, paid_400), None); + let echoed = r#"{"success":false,"error":"Forbidden","details":{"hint":"add credits"}}"#; + assert_eq!(backend_billing_refusal(403, echoed), None); + assert_eq!(backend_billing_refusal(403, "Insufficient balance"), None); +} + +#[tokio::test] +async fn authed_json_surfaces_billing_refusals_as_typed_errors() { + let app = Router::new() + .route( + "/agent-integrations/gemini/live/sessions", + post(|| async { + ( + axum::http::StatusCode::BAD_REQUEST, + [(axum::http::header::CONTENT_TYPE, "application/json")], + GEMINI_LIVE_RESERVE_BODY, + ) + }), + ) + .route( + "/voice-agent/get-signed-url", + get(|| async { + ( + axum::http::StatusCode::FORBIDDEN, + Json(json!({ + "success": false, + "error": "Voice sessions require a paid plan.", + "errorCode": "FORBIDDEN", + })), + ) + }), + ); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let client = BackendClient::new(&format!("http://{addr}")).unwrap(); + + let err = client + .authed_json( + "mock-jwt", + Method::POST, + "/agent-integrations/gemini/live/sessions", + Some(json!({ "mode": "conversation" })), + ) + .await + .unwrap_err(); + let typed = err.downcast_ref::().unwrap(); + let HostedApiError::InsufficientCredits { status, path, .. } = typed else { + panic!("expected InsufficientCredits, got {typed:?}"); + }; + assert_eq!(*status, 400); + assert_eq!(path, "/agent-integrations/gemini/live/sessions"); + // Same message shape as the generic failure, behind the sentinel. + let flattened = flatten_authed_error(err); + assert!( + flattened.starts_with( + "INSUFFICIENT_CREDITS:POST /agent-integrations/gemini/live/sessions failed (400): " + ), + "{flattened}" + ); + assert!( + flattened.contains("USER_INSUFFICIENT_CREDITS"), + "{flattened}" + ); + + let err = client + .authed_json("mock-jwt", Method::GET, "/voice-agent/get-signed-url", None) + .await + .unwrap_err(); + let typed = err.downcast_ref::().unwrap(); + assert!( + matches!(typed, HostedApiError::PaidPlanRequired { status: 403, .. }), + "expected PaidPlanRequired, got {typed:?}" + ); + assert!(flatten_authed_error(err).starts_with("PAID_PLAN_REQUIRED:")); +} diff --git a/crates/openhuman-tinyhumans/src/client/classify.rs b/crates/openhuman-tinyhumans/src/client/classify.rs index 84391b38ca7..21c0ae3af25 100644 --- a/crates/openhuman-tinyhumans/src/client/classify.rs +++ b/crates/openhuman-tinyhumans/src/client/classify.rs @@ -104,6 +104,44 @@ pub(super) fn backend_api_error_text(body: &str) -> Option { (!parts.is_empty()).then(|| parts.join("; ")) } +/// The backend `errorCode` for an account whose balance is below what the +/// route reserves (e.g. Gemini Live's per-session reserve). +const INSUFFICIENT_CREDITS_ERROR_CODE: &str = "USER_INSUFFICIENT_CREDITS"; + +/// A billing refusal the backend signals on a gated hosted feature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum BillingRefusal { + /// Balance below the route's reserve. + InsufficientCredits, + /// The feature needs a paid plan. + PaidPlanRequired, +} + +/// Classify a non-2xx response as a billing refusal: an +/// `errorCode: USER_INSUFFICIENT_CREDITS` envelope on any status +/// (TAURI-RUST-13BR, whose message matches no budget phrase), or a 403 whose +/// `error` text asks to add credits or names a paid plan (the voice-agent +/// signed-url gate, TAURI-RUST-11G3, which answers with `errorCode: FORBIDDEN`). +/// Only the `error` field is read for 403s, so a body that merely echoes a +/// phrase elsewhere does not match. +pub(super) fn backend_billing_refusal(status: u16, body: &str) -> Option { + let value = serde_json::from_str::(body.trim()).ok()?; + if value.get("errorCode").and_then(Value::as_str) == Some(INSUFFICIENT_CREDITS_ERROR_CODE) { + return Some(BillingRefusal::InsufficientCredits); + } + if status != 403 { + return None; + } + let error = value.get("error").and_then(Value::as_str)?; + if error.to_ascii_lowercase().contains("paid plan") { + Some(BillingRefusal::PaidPlanRequired) + } else if tinyinference_providers::is_budget_exhausted_message(error) { + Some(BillingRefusal::InsufficientCredits) + } else { + None + } +} + /// A JSON key safe to echo into telemetry: a short ASCII identifier. fn is_schema_like_key(key: &str) -> bool { const MAX_KEY_LEN: usize = 40; @@ -259,6 +297,40 @@ impl BackendClient { let is_transient_infra = is_transient_http_status_code(status_code); let is_budget_exhausted = status_code == 400 && tinyinference_providers::is_budget_exhausted_message(&text); + let billing_refusal = (!is_budget_exhausted) + .then(|| backend_billing_refusal(status_code, &text)) + .flatten(); + if let Some(refusal) = billing_refusal { + tracing::info!( + domain = "backend_api", + operation = "authed_json", + method = method.as_str(), + path = url.path(), + status = status_code, + failure = "non_2xx", + kind = ?refusal, + "[backend_api] billing refusal {status} on {} {}: {refusal:?}, not reporting to Sentry", + method.as_str(), + url.path(), + ); + let (method, path) = (method.as_str().to_string(), url.path().to_string()); + let body = + truncate_at_byte_boundary(&text, BACKEND_API_ERROR_BODY_MAX_BYTES).to_string(); + return Err(anyhow::Error::new(match refusal { + BillingRefusal::InsufficientCredits => HostedApiError::InsufficientCredits { + method, + path, + status: status_code, + body, + }, + BillingRefusal::PaidPlanRequired => HostedApiError::PaidPlanRequired { + method, + path, + status: status_code, + body, + }, + })); + } if is_budget_exhausted { tracing::info!( method = method.as_str(), diff --git a/crates/openhuman-tinyhumans/src/client/error.rs b/crates/openhuman-tinyhumans/src/client/error.rs index b0990b79941..6b495595255 100644 --- a/crates/openhuman-tinyhumans/src/client/error.rs +++ b/crates/openhuman-tinyhumans/src/client/error.rs @@ -4,7 +4,8 @@ //! sentinel strings `core::observability` classifies. use openhuman_embed::__host::core::observability::{ - API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, + API_KEY_REJECTED_PREFIX, BACKEND_UNAVAILABLE_PREFIX, INSUFFICIENT_CREDITS_PREFIX, + PAID_PLAN_REQUIRED_PREFIX, }; /// Typed errors surfaced by `BackendClient::authed_json` for expected backend @@ -68,6 +69,39 @@ pub enum HostedApiError { /// Request path that could not be sent (no query string). path: String, }, + /// The backend refused a gated feature because the account balance is + /// below what it reserves (`errorCode: USER_INSUFFICIENT_CREDITS`, or a + /// 403 asking to add credits). Billing user state, not a bug; flattens onto + /// the `INSUFFICIENT_CREDITS:` sentinel (TAURI-RUST-13BR / -11G3). + /// + /// Displays in the generic non-2xx failure's shape + /// (` failed (): `), so callers that read the + /// message keep working. + #[error("{method} {path} failed ({status}): {body}")] + InsufficientCredits { + /// HTTP method (`"GET"`, `"POST"`, ...). + method: String, + /// Request path (no query string). + path: String, + /// HTTP status the backend answered with. + status: u16, + /// Response body, truncated. + body: String, + }, + /// The backend refused a feature that needs a paid plan (a 403). Billing + /// user state; flattens onto the `PAID_PLAN_REQUIRED:` sentinel + /// (TAURI-RUST-11G3). Displays like [`Self::InsufficientCredits`]. + #[error("{method} {path} failed ({status}): {body}")] + PaidPlanRequired { + /// HTTP method (`"GET"`, `"POST"`, ...). + method: String, + /// Request path (no query string). + path: String, + /// HTTP status the backend answered with. + status: u16, + /// Response body, truncated. + body: String, + }, } /// Flatten an `authed_json` error onto the JSON-RPC `String` channel. @@ -90,6 +124,12 @@ pub fn flatten_authed_error(err: anyhow::Error) -> String { "{BACKEND_UNAVAILABLE_PREFIX}backend transport not available for {method} {path}" ) } + Some(refusal @ HostedApiError::InsufficientCredits { .. }) => { + format!("{INSUFFICIENT_CREDITS_PREFIX}{refusal}") + } + Some(refusal @ HostedApiError::PaidPlanRequired { .. }) => { + format!("{PAID_PLAN_REQUIRED_PREFIX}{refusal}") + } _ => format!("{err:#}"), } } diff --git a/crates/openhuman-tinyhumans/src/voice/live.rs b/crates/openhuman-tinyhumans/src/voice/live.rs index bfc89b111f8..74c94eae46a 100644 --- a/crates/openhuman-tinyhumans/src/voice/live.rs +++ b/crates/openhuman-tinyhumans/src/voice/live.rs @@ -7,6 +7,9 @@ //! ([`register`]); the core carries no hosted entry of its own. use openhuman_embed::__host::config::Config; +use openhuman_embed::__host::core::observability::{ + INSUFFICIENT_CREDITS_PREFIX, PAID_PLAN_REQUIRED_PREFIX, +}; use openhuman_embed::__host::credentials::backend_credential::resolve_backend_credential; use openhuman_embed::__host::voice_registry::{ register_live_provider, LiveProviderEntry, LiveProviderKind, LiveProviderPlacement, @@ -36,6 +39,22 @@ fn non_empty(value: Option) -> Option { value.filter(|v| !v.trim().is_empty()) } +/// The live-session error for a failed backend mint. The backend's billing +/// refusals (balance below the session reserve, or a free plan) get their own +/// codes so the UI can say "add credits" / "upgrade" instead of echoing the +/// raw backend failure (TAURI-RUST-13BR / -11G3). +pub(crate) fn mint_error(message: String) -> LiveVoiceError { + if message.contains(INSUFFICIENT_CREDITS_PREFIX) { + log::info!("{LOG_PREFIX} mint refused: insufficient credits"); + LiveVoiceError::new("insufficient_credits", message) + } else if message.contains(PAID_PLAN_REQUIRED_PREFIX) { + log::info!("{LOG_PREFIX} mint refused: paid plan required"); + LiveVoiceError::new("paid_plan_required", message) + } else { + LiveVoiceError::backend(message) + } +} + /// Whether a backend credential is available for the hosted providers. fn backend_ready(config: &Config) -> openhuman_embed::__host::voice_registry::LiveFuture { let config = config.clone(); @@ -110,7 +129,7 @@ async fn mint_gemini_ticket( Some(body), ) .await - .map_err(|error| LiveVoiceError::backend(flatten_authed_error(error)))?; + .map_err(|error| mint_error(flatten_authed_error(error)))?; parse_ticket(&raw) } @@ -140,7 +159,7 @@ pub(crate) async fn prepare_elevenlabs( ) -> Result { let signed = mint_voice_agent_signed_url(&config) .await - .map_err(LiveVoiceError::backend)? + .map_err(mint_error)? .value; // `user_token` is the identity the backend's Custom-LLM relay verifies on // every relayed turn (#5399). diff --git a/crates/openhuman-tinyhumans/src/voice/live_tests.rs b/crates/openhuman-tinyhumans/src/voice/live_tests.rs index 43c547a9989..1393ff9e450 100644 --- a/crates/openhuman-tinyhumans/src/voice/live_tests.rs +++ b/crates/openhuman-tinyhumans/src/voice/live_tests.rs @@ -103,3 +103,17 @@ async fn hosted_providers_report_not_configured_without_a_backend_credential() { .unwrap(); assert_eq!(err.code, "not_configured"); } + +#[test] +fn mint_error_maps_billing_refusals_to_their_own_codes() { + let credits = mint_error(format!( + "{INSUFFICIENT_CREDITS_PREFIX}POST /x failed (400): {{}}" + )); + assert_eq!(credits.code, "insufficient_credits"); + let plan = mint_error(format!( + "{PAID_PLAN_REQUIRED_PREFIX}GET /x failed (403): {{}}" + )); + assert_eq!(plan.code, "paid_plan_required"); + let other = mint_error("GET /x failed (500): {}".to_string()); + assert_eq!(other.code, "backend"); +} From abc89a26dfd94475bf13e1f5c7ca3a29b6a5ce33 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 07:01:46 +0000 Subject: [PATCH 5/8] fix(tinyhumans): let an explicit USER_INSUFFICIENT_CREDITS code win over budget text A 400 carrying errorCode USER_INSUFFICIENT_CREDITS whose message also matched a budget phrase took the generic budget path, so live voice showed the raw backend error instead of the credits message. Classify billing refusals first; budget 400s without the code are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/client/backend_client_tests.rs | 34 +++++++++++++++++++ .../src/client/classify.rs | 9 ++--- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs index e8a5edeb5b8..72e4f6a3f03 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -486,6 +486,19 @@ async fn authed_json_surfaces_billing_refusals_as_typed_errors() { ) }), ) + .route( + "/agent-integrations/coded-budget", + post(|| async { + ( + axum::http::StatusCode::BAD_REQUEST, + Json(json!({ + "success": false, + "error": "Insufficient balance", + "errorCode": "USER_INSUFFICIENT_CREDITS", + })), + ) + }), + ) .route( "/voice-agent/get-signed-url", get(|| async { @@ -534,6 +547,27 @@ async fn authed_json_surfaces_billing_refusals_as_typed_errors() { "{flattened}" ); + // The explicit code wins over the generic budget-text path. + assert!(tinyinference_providers::is_budget_exhausted_message( + "Insufficient balance" + )); + let err = client + .authed_json( + "mock-jwt", + Method::POST, + "/agent-integrations/coded-budget", + None, + ) + .await + .unwrap_err(); + assert!( + matches!( + err.downcast_ref::(), + Some(HostedApiError::InsufficientCredits { status: 400, .. }) + ), + "expected InsufficientCredits, got {err:?}" + ); + let err = client .authed_json("mock-jwt", Method::GET, "/voice-agent/get-signed-url", None) .await diff --git a/crates/openhuman-tinyhumans/src/client/classify.rs b/crates/openhuman-tinyhumans/src/client/classify.rs index 21c0ae3af25..09c3391ee1f 100644 --- a/crates/openhuman-tinyhumans/src/client/classify.rs +++ b/crates/openhuman-tinyhumans/src/client/classify.rs @@ -297,10 +297,11 @@ impl BackendClient { let is_transient_infra = is_transient_http_status_code(status_code); let is_budget_exhausted = status_code == 400 && tinyinference_providers::is_budget_exhausted_message(&text); - let billing_refusal = (!is_budget_exhausted) - .then(|| backend_billing_refusal(status_code, &text)) - .flatten(); - if let Some(refusal) = billing_refusal { + // Checked before the budget-text path: an explicit + // `USER_INSUFFICIENT_CREDITS` code wins even when the message also + // matches a budget phrase. Budget 400s without it fall through as before + // (the 403 text match never overlaps the 400-only budget check). + if let Some(refusal) = backend_billing_refusal(status_code, &text) { tracing::info!( domain = "backend_api", operation = "authed_json", From f9252fff968265cc5a9e3b008c476bc91fa09d95 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 12:57:35 +0000 Subject: [PATCH 6/8] style(i18n): prettier-format the live voice billing strings Co-Authored-By: Claude Opus 5.5 --- app/src/lib/i18n/ar.ts | 3 ++- app/src/lib/i18n/bn.ts | 6 ++++-- app/src/lib/i18n/de.ts | 6 ++++-- app/src/lib/i18n/es.ts | 6 ++++-- app/src/lib/i18n/fr.ts | 6 ++++-- app/src/lib/i18n/hi.ts | 6 ++++-- app/src/lib/i18n/id.ts | 6 ++++-- app/src/lib/i18n/it.ts | 6 ++++-- app/src/lib/i18n/ja.ts | 6 ++++-- app/src/lib/i18n/ko.ts | 6 ++++-- app/src/lib/i18n/pl.ts | 6 ++++-- app/src/lib/i18n/pt.ts | 6 ++++-- app/src/lib/i18n/ru.ts | 6 ++++-- app/src/lib/i18n/tr.ts | 6 ++++-- 14 files changed, 54 insertions(+), 27 deletions(-) diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.ts index d572b49075f..6e47039c2a6 100644 --- a/app/src/lib/i18n/ar.ts +++ b/app/src/lib/i18n/ar.ts @@ -4266,7 +4266,8 @@ const messages: TranslationMap = { 'تم رفض الوصول إلى الميكروفون. اسمح به من إعدادات النظام ثم حاول مرة أخرى.', 'voice.live.error.micUnavailable': 'لا يتوفر ميكروفون.', 'voice.live.error.connection': 'تعذّر الاتصال بالوكيل الصوتي.', - 'voice.live.error.insufficientCredits': 'يحتاج الصوت المباشر إلى رصيد إضافي. أضف رصيدًا للمتابعة.', + 'voice.live.error.insufficientCredits': + 'يحتاج الصوت المباشر إلى رصيد إضافي. أضف رصيدًا للمتابعة.', 'voice.live.error.paidPlanRequired': 'يتطلب الصوت المباشر خطة مدفوعة. قم بالترقية للمتابعة.', 'voice.live.toolRunning': 'جارٍ تشغيل {name}', 'voice.live.toolOk': 'اكتمل {name}', diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.ts index 074215dd5e8..e367954d4ce 100644 --- a/app/src/lib/i18n/bn.ts +++ b/app/src/lib/i18n/bn.ts @@ -4352,8 +4352,10 @@ const messages: TranslationMap = { 'মাইক্রোফোনের অনুমতি দেওয়া হয়নি। সিস্টেম সেটিংসে অনুমতি দিয়ে আবার চেষ্টা করুন।', 'voice.live.error.micUnavailable': 'কোনো মাইক্রোফোন পাওয়া যায়নি।', 'voice.live.error.connection': 'ভয়েস এজেন্টের সাথে সংযোগ করা যায়নি।', - 'voice.live.error.insufficientCredits': 'লাইভ ভয়েসের জন্য আরও ক্রেডিট প্রয়োজন। চালিয়ে যেতে ক্রেডিট যোগ করুন।', - 'voice.live.error.paidPlanRequired': 'লাইভ ভয়েসের জন্য একটি পেইড প্ল্যান প্রয়োজন। চালিয়ে যেতে আপগ্রেড করুন।', + 'voice.live.error.insufficientCredits': + 'লাইভ ভয়েসের জন্য আরও ক্রেডিট প্রয়োজন। চালিয়ে যেতে ক্রেডিট যোগ করুন।', + 'voice.live.error.paidPlanRequired': + 'লাইভ ভয়েসের জন্য একটি পেইড প্ল্যান প্রয়োজন। চালিয়ে যেতে আপগ্রেড করুন।', 'voice.live.toolRunning': '{name} চলছে', 'voice.live.toolOk': '{name} সম্পন্ন', 'voice.live.toolFailed': '{name} ব্যর্থ হয়েছে', diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.ts index b49e9fc9381..b1764a8a0b5 100644 --- a/app/src/lib/i18n/de.ts +++ b/app/src/lib/i18n/de.ts @@ -4494,8 +4494,10 @@ const messages: TranslationMap = { 'Der Mikrofonzugriff wurde verweigert. Erlaube ihn in den Systemeinstellungen und versuche es erneut.', 'voice.live.error.micUnavailable': 'Kein Mikrofon verfügbar.', 'voice.live.error.connection': 'Verbindung zum Sprachagenten fehlgeschlagen.', - 'voice.live.error.insufficientCredits': 'Für Live-Sprache brauchst du mehr Guthaben. Lade Guthaben auf, um fortzufahren.', - 'voice.live.error.paidPlanRequired': 'Live-Sprache erfordert einen kostenpflichtigen Tarif. Führe ein Upgrade durch, um fortzufahren.', + 'voice.live.error.insufficientCredits': + 'Für Live-Sprache brauchst du mehr Guthaben. Lade Guthaben auf, um fortzufahren.', + 'voice.live.error.paidPlanRequired': + 'Live-Sprache erfordert einen kostenpflichtigen Tarif. Führe ein Upgrade durch, um fortzufahren.', 'voice.live.toolRunning': '{name} läuft', 'voice.live.toolOk': '{name} abgeschlossen', 'voice.live.toolFailed': '{name} fehlgeschlagen', diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.ts index 6deb6fa9efe..6eb40042963 100644 --- a/app/src/lib/i18n/es.ts +++ b/app/src/lib/i18n/es.ts @@ -4446,8 +4446,10 @@ const messages: TranslationMap = { 'Se denegó el acceso al micrófono. Permítelo en la configuración del sistema e inténtalo de nuevo.', 'voice.live.error.micUnavailable': 'No hay ningún micrófono disponible.', 'voice.live.error.connection': 'No se pudo conectar con el agente de voz.', - 'voice.live.error.insufficientCredits': 'La voz en directo necesita más créditos. Añade créditos para continuar.', - 'voice.live.error.paidPlanRequired': 'La voz en directo requiere un plan de pago. Mejora tu plan para continuar.', + 'voice.live.error.insufficientCredits': + 'La voz en directo necesita más créditos. Añade créditos para continuar.', + 'voice.live.error.paidPlanRequired': + 'La voz en directo requiere un plan de pago. Mejora tu plan para continuar.', 'voice.live.toolRunning': 'Ejecutando {name}', 'voice.live.toolOk': '{name} completado', 'voice.live.toolFailed': '{name} falló', diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.ts index a23a53d08f4..bd2a40be71a 100644 --- a/app/src/lib/i18n/fr.ts +++ b/app/src/lib/i18n/fr.ts @@ -4469,8 +4469,10 @@ const messages: TranslationMap = { "L'accès au micro a été refusé. Autorisez-le dans les réglages système puis réessayez.", 'voice.live.error.micUnavailable': 'Aucun micro disponible.', 'voice.live.error.connection': "Impossible de se connecter à l'agent vocal.", - 'voice.live.error.insufficientCredits': 'La voix en direct nécessite plus de crédits. Ajoutez des crédits pour continuer.', - 'voice.live.error.paidPlanRequired': 'La voix en direct nécessite un forfait payant. Passez à un forfait supérieur pour continuer.', + 'voice.live.error.insufficientCredits': + 'La voix en direct nécessite plus de crédits. Ajoutez des crédits pour continuer.', + 'voice.live.error.paidPlanRequired': + 'La voix en direct nécessite un forfait payant. Passez à un forfait supérieur pour continuer.', 'voice.live.toolRunning': '{name} en cours', 'voice.live.toolOk': '{name} terminé', 'voice.live.toolFailed': 'Échec de {name}', diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.ts index 769be7eb6da..984b0d7b9c1 100644 --- a/app/src/lib/i18n/hi.ts +++ b/app/src/lib/i18n/hi.ts @@ -4357,8 +4357,10 @@ const messages: TranslationMap = { 'माइक्रोफ़ोन की अनुमति नहीं मिली। सिस्टम सेटिंग में अनुमति दें और फिर कोशिश करें।', 'voice.live.error.micUnavailable': 'कोई माइक्रोफ़ोन उपलब्ध नहीं है।', 'voice.live.error.connection': 'वॉइस एजेंट से कनेक्ट नहीं हो सका।', - 'voice.live.error.insufficientCredits': 'लाइव वॉइस के लिए और क्रेडिट चाहिए। जारी रखने के लिए क्रेडिट जोड़ें।', - 'voice.live.error.paidPlanRequired': 'लाइव वॉइस के लिए पेड प्लान ज़रूरी है। जारी रखने के लिए अपग्रेड करें।', + 'voice.live.error.insufficientCredits': + 'लाइव वॉइस के लिए और क्रेडिट चाहिए। जारी रखने के लिए क्रेडिट जोड़ें।', + 'voice.live.error.paidPlanRequired': + 'लाइव वॉइस के लिए पेड प्लान ज़रूरी है। जारी रखने के लिए अपग्रेड करें।', 'voice.live.toolRunning': '{name} चल रहा है', 'voice.live.toolOk': '{name} पूरा हुआ', 'voice.live.toolFailed': '{name} विफल रहा', diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.ts index fe911e3e493..835eb8b4cf0 100644 --- a/app/src/lib/i18n/id.ts +++ b/app/src/lib/i18n/id.ts @@ -4395,8 +4395,10 @@ const messages: TranslationMap = { 'Akses mikrofon ditolak. Izinkan di pengaturan sistem lalu coba lagi.', 'voice.live.error.micUnavailable': 'Tidak ada mikrofon yang tersedia.', 'voice.live.error.connection': 'Tidak dapat terhubung ke agen suara.', - 'voice.live.error.insufficientCredits': 'Suara langsung memerlukan lebih banyak kredit. Tambahkan kredit untuk melanjutkan.', - 'voice.live.error.paidPlanRequired': 'Suara langsung memerlukan paket berbayar. Tingkatkan paket untuk melanjutkan.', + 'voice.live.error.insufficientCredits': + 'Suara langsung memerlukan lebih banyak kredit. Tambahkan kredit untuk melanjutkan.', + 'voice.live.error.paidPlanRequired': + 'Suara langsung memerlukan paket berbayar. Tingkatkan paket untuk melanjutkan.', 'voice.live.toolRunning': 'Menjalankan {name}', 'voice.live.toolOk': '{name} selesai', 'voice.live.toolFailed': '{name} gagal', diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.ts index 02a7f42b21d..f4e7a3047d4 100644 --- a/app/src/lib/i18n/it.ts +++ b/app/src/lib/i18n/it.ts @@ -4430,8 +4430,10 @@ const messages: TranslationMap = { "L'accesso al microfono è stato negato. Consentilo nelle impostazioni di sistema e riprova.", 'voice.live.error.micUnavailable': 'Nessun microfono disponibile.', 'voice.live.error.connection': "Impossibile connettersi all'agente vocale.", - 'voice.live.error.insufficientCredits': 'La voce dal vivo richiede più crediti. Aggiungi crediti per continuare.', - 'voice.live.error.paidPlanRequired': 'La voce dal vivo richiede un piano a pagamento. Passa a un piano superiore per continuare.', + 'voice.live.error.insufficientCredits': + 'La voce dal vivo richiede più crediti. Aggiungi crediti per continuare.', + 'voice.live.error.paidPlanRequired': + 'La voce dal vivo richiede un piano a pagamento. Passa a un piano superiore per continuare.', 'voice.live.toolRunning': '{name} in esecuzione', 'voice.live.toolOk': '{name} completato', 'voice.live.toolFailed': '{name} non riuscito', diff --git a/app/src/lib/i18n/ja.ts b/app/src/lib/i18n/ja.ts index 80788600a93..552ba74f73a 100644 --- a/app/src/lib/i18n/ja.ts +++ b/app/src/lib/i18n/ja.ts @@ -4638,8 +4638,10 @@ const messages: TranslationMap = { 'マイクへのアクセスが拒否されました。システム設定で許可してから、もう一度お試しください。', 'voice.live.error.micUnavailable': '利用可能なマイクがありません。', 'voice.live.error.connection': '音声エージェントに接続できませんでした。', - 'voice.live.error.insufficientCredits': 'ライブ音声にはクレジットが不足しています。続けるにはクレジットを追加してください。', - 'voice.live.error.paidPlanRequired': 'ライブ音声には有料プランが必要です。続けるにはアップグレードしてください。', + 'voice.live.error.insufficientCredits': + 'ライブ音声にはクレジットが不足しています。続けるにはクレジットを追加してください。', + 'voice.live.error.paidPlanRequired': + 'ライブ音声には有料プランが必要です。続けるにはアップグレードしてください。', 'voice.live.toolRunning': '{name}を実行中', 'voice.live.toolOk': '{name}が完了しました', 'voice.live.toolFailed': '{name}が失敗しました', diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.ts index e539855398e..e19d8db57d7 100644 --- a/app/src/lib/i18n/ko.ts +++ b/app/src/lib/i18n/ko.ts @@ -4302,8 +4302,10 @@ const messages: TranslationMap = { '마이크 접근이 거부되었습니다. 시스템 설정에서 허용한 뒤 다시 시도하세요.', 'voice.live.error.micUnavailable': '사용 가능한 마이크가 없습니다.', 'voice.live.error.connection': '음성 에이전트에 연결할 수 없습니다.', - 'voice.live.error.insufficientCredits': '실시간 음성에 크레딧이 더 필요합니다. 계속하려면 크레딧을 추가하세요.', - 'voice.live.error.paidPlanRequired': '실시간 음성은 유료 플랜이 필요합니다. 계속하려면 업그레이드하세요.', + 'voice.live.error.insufficientCredits': + '실시간 음성에 크레딧이 더 필요합니다. 계속하려면 크레딧을 추가하세요.', + 'voice.live.error.paidPlanRequired': + '실시간 음성은 유료 플랜이 필요합니다. 계속하려면 업그레이드하세요.', 'voice.live.toolRunning': '{name} 실행 중', 'voice.live.toolOk': '{name} 완료', 'voice.live.toolFailed': '{name} 실패', diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.ts index 1c3761b01df..89e3df99254 100644 --- a/app/src/lib/i18n/pl.ts +++ b/app/src/lib/i18n/pl.ts @@ -4417,8 +4417,10 @@ const messages: TranslationMap = { 'Odmówiono dostępu do mikrofonu. Zezwól na niego w ustawieniach systemu i spróbuj ponownie.', 'voice.live.error.micUnavailable': 'Brak dostępnego mikrofonu.', 'voice.live.error.connection': 'Nie udało się połączyć z agentem głosowym.', - 'voice.live.error.insufficientCredits': 'Głos na żywo wymaga więcej środków. Doładuj środki, aby kontynuować.', - 'voice.live.error.paidPlanRequired': 'Głos na żywo wymaga płatnego planu. Przejdź na wyższy plan, aby kontynuować.', + 'voice.live.error.insufficientCredits': + 'Głos na żywo wymaga więcej środków. Doładuj środki, aby kontynuować.', + 'voice.live.error.paidPlanRequired': + 'Głos na żywo wymaga płatnego planu. Przejdź na wyższy plan, aby kontynuować.', 'voice.live.toolRunning': 'Trwa {name}', 'voice.live.toolOk': 'Ukończono {name}', 'voice.live.toolFailed': 'Błąd: {name}', diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.ts index 67ad3c00b65..b7d97957859 100644 --- a/app/src/lib/i18n/pt.ts +++ b/app/src/lib/i18n/pt.ts @@ -4419,8 +4419,10 @@ const messages: TranslationMap = { 'O acesso ao microfone foi negado. Permita-o nas configurações do sistema e tente novamente.', 'voice.live.error.micUnavailable': 'Nenhum microfone disponível.', 'voice.live.error.connection': 'Não foi possível conectar ao agente de voz.', - 'voice.live.error.insufficientCredits': 'A voz ao vivo precisa de mais créditos. Adicione créditos para continuar.', - 'voice.live.error.paidPlanRequired': 'A voz ao vivo requer um plano pago. Faça upgrade para continuar.', + 'voice.live.error.insufficientCredits': + 'A voz ao vivo precisa de mais créditos. Adicione créditos para continuar.', + 'voice.live.error.paidPlanRequired': + 'A voz ao vivo requer um plano pago. Faça upgrade para continuar.', 'voice.live.toolRunning': 'Executando {name}', 'voice.live.toolOk': '{name} concluído', 'voice.live.toolFailed': '{name} falhou', diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.ts index 372a7b1af98..63ad90d7657 100644 --- a/app/src/lib/i18n/ru.ts +++ b/app/src/lib/i18n/ru.ts @@ -4401,8 +4401,10 @@ const messages: TranslationMap = { 'Доступ к микрофону запрещён. Разрешите его в настройках системы и попробуйте снова.', 'voice.live.error.micUnavailable': 'Микрофон недоступен.', 'voice.live.error.connection': 'Не удалось подключиться к голосовому агенту.', - 'voice.live.error.insufficientCredits': 'Для голоса в реальном времени нужно больше кредитов. Пополните баланс, чтобы продолжить.', - 'voice.live.error.paidPlanRequired': 'Для голоса в реальном времени нужен платный тариф. Перейдите на него, чтобы продолжить.', + 'voice.live.error.insufficientCredits': + 'Для голоса в реальном времени нужно больше кредитов. Пополните баланс, чтобы продолжить.', + 'voice.live.error.paidPlanRequired': + 'Для голоса в реальном времени нужен платный тариф. Перейдите на него, чтобы продолжить.', 'voice.live.toolRunning': 'Выполняется {name}', 'voice.live.toolOk': '{name} завершено', 'voice.live.toolFailed': 'Ошибка: {name}', diff --git a/app/src/lib/i18n/tr.ts b/app/src/lib/i18n/tr.ts index 738f05b4e09..0a06697e606 100644 --- a/app/src/lib/i18n/tr.ts +++ b/app/src/lib/i18n/tr.ts @@ -4289,8 +4289,10 @@ const messages: TranslationMap = { 'Mikrofon erişimi reddedildi. Sistem ayarlarınızdan izin verip yeniden deneyin.', 'voice.live.error.micUnavailable': 'Kullanılabilir mikrofon yok.', 'voice.live.error.connection': 'Ses ajanına bağlanılamadı.', - 'voice.live.error.insufficientCredits': 'Canlı ses için daha fazla kredi gerekiyor. Devam etmek için kredi ekleyin.', - 'voice.live.error.paidPlanRequired': 'Canlı ses ücretli bir plan gerektirir. Devam etmek için planınızı yükseltin.', + 'voice.live.error.insufficientCredits': + 'Canlı ses için daha fazla kredi gerekiyor. Devam etmek için kredi ekleyin.', + 'voice.live.error.paidPlanRequired': + 'Canlı ses ücretli bir plan gerektirir. Devam etmek için planınızı yükseltin.', 'voice.live.toolRunning': '{name} çalışıyor', 'voice.live.toolOk': '{name} tamamlandı', 'voice.live.toolFailed': '{name} başarısız oldu', From d234d91fb331c4f6f5adc40f8f30baa5df3b9441 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 2 Nov 2026 14:10:15 +0000 Subject: [PATCH 7/8] test(observability): move billing-refusal classification test to its own file The user-state test file went over the 750-line layout limit (753). Co-Authored-By: Claude Opus 5.5 --- ...or_classification_billing_refusal_tests.rs | 26 +++++++++++++++++++ ...y_error_classification_user_state_tests.rs | 25 ------------------ .../src/core/observability_tests.rs | 2 ++ 3 files changed, 28 insertions(+), 25 deletions(-) create mode 100644 crates/openhuman-core/src/core/observability_error_classification_billing_refusal_tests.rs diff --git a/crates/openhuman-core/src/core/observability_error_classification_billing_refusal_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_billing_refusal_tests.rs new file mode 100644 index 00000000000..37017c615da --- /dev/null +++ b/crates/openhuman-core/src/core/observability_error_classification_billing_refusal_tests.rs @@ -0,0 +1,26 @@ +use super::*; + +#[test] +fn classifies_hosted_billing_refusals_as_budget_exhausted() { + // TAURI-RUST-13BR / -11G3: the hosted client flattens a live-voice billing + // refusal onto these sentinels. The Gemini reserve message matches no + // budget phrase, so only the sentinel keeps it out of Sentry. + let credits = format!( + "{INSUFFICIENT_CREDITS_PREFIX}POST /live failed (400): {{\"error\":\"Gemini Live requires an available balance of at least $1.00 (reserved per open session)\",\"errorCode\":\"USER_INSUFFICIENT_CREDITS\"}}" + ); + let plan = format!("{PAID_PLAN_REQUIRED_PREFIX}GET /signed-url failed (403): {{}}"); + for msg in [credits, plan] { + assert!(is_hosted_billing_refusal_message(&msg), "{msg}"); + assert!( + matches!( + expected_error_kind(&msg), + Some(ExpectedErrorKind::BudgetExhausted) + ), + "{msg}" + ); + } + // A bare mention of the word is not the sentinel. + assert!(!is_hosted_billing_refusal_message( + "insufficient_credits counter overflowed" + )); +} diff --git a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs index 639ff264e71..a0662809e20 100644 --- a/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs +++ b/crates/openhuman-core/src/core/observability_error_classification_user_state_tests.rs @@ -726,28 +726,3 @@ fn connector_provider_output_is_already_reported_without_affecting_other_modules ); } } - -#[test] -fn classifies_hosted_billing_refusals_as_budget_exhausted() { - // TAURI-RUST-13BR / -11G3: the hosted client flattens a live-voice billing - // refusal onto these sentinels. The Gemini reserve message matches no - // budget phrase, so only the sentinel keeps it out of Sentry. - let credits = format!( - "{INSUFFICIENT_CREDITS_PREFIX}POST /live failed (400): {{\"error\":\"Gemini Live requires an available balance of at least $1.00 (reserved per open session)\",\"errorCode\":\"USER_INSUFFICIENT_CREDITS\"}}" - ); - let plan = format!("{PAID_PLAN_REQUIRED_PREFIX}GET /signed-url failed (403): {{}}"); - for msg in [credits, plan] { - assert!(is_hosted_billing_refusal_message(&msg), "{msg}"); - assert!( - matches!( - expected_error_kind(&msg), - Some(ExpectedErrorKind::BudgetExhausted) - ), - "{msg}" - ); - } - // A bare mention of the word is not the sentinel. - assert!(!is_hosted_billing_refusal_message( - "insufficient_credits counter overflowed" - )); -} diff --git a/crates/openhuman-core/src/core/observability_tests.rs b/crates/openhuman-core/src/core/observability_tests.rs index 5016996e381..387fa3759d0 100644 --- a/crates/openhuman-core/src/core/observability_tests.rs +++ b/crates/openhuman-core/src/core/observability_tests.rs @@ -122,6 +122,8 @@ fn event_with_exception_value(value: &str) -> sentry::protocol::Event<'static> { mod crash_filter_integrations; #[path = "observability_crash_filter_messages_tests.rs"] mod crash_filter_messages; +#[path = "observability_error_classification_billing_refusal_tests.rs"] +mod error_classification_billing_refusal; #[path = "observability_error_classification_core_tests.rs"] mod error_classification_core; #[path = "observability_error_classification_network_tests.rs"] From bce7a28929826f1d34aed674fd77156011ccf07f Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Mon, 2 Nov 2026 19:45:24 +0530 Subject: [PATCH 8/8] fix(tinyhumans): classify billing refusals in the transport, drop backend text log Review follow-ups on #8520: - What a backend response means is decided in the transport (AGENTS.md hosted boundary). Move the billing-refusal classifier from client/classify.rs into transport/error.rs: map_sdk_error now yields a typed BackendTransportError::BillingRefusal, and BackendClient only recovers it onto HostedApiError::{InsufficientCredits,PaidPlanRequired}. IntegrationClient no longer reports the same envelope as a generic non-2xx. A 401 keeps precedence as a credential failure. - Remove the OPENHUMAN_LOG_BACKEND_ERROR_TEXT opt-in debug log: the backend's error/details are free text that may echo user content. The identifier-shaped errorCode stays in the warn line. --- .../src/client/backend_client_tests.rs | 24 +-- .../src/client/classify.rs | 170 +++++------------- .../src/transport/README.md | 11 +- .../src/transport/error.rs | 46 ++++- .../openhuman-tinyhumans/src/transport/mod.rs | 6 +- .../src/transport/port.rs | 19 +- 6 files changed, 124 insertions(+), 152 deletions(-) diff --git a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs index 72e4f6a3f03..b8bbafbdc78 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -1,10 +1,10 @@ use super::*; use crate::client::classify::{ - backend_api_body_shape, backend_api_error_code, backend_api_error_text, - backend_billing_refusal, BillingRefusal, BACKEND_API_BODY_SHAPE_MAX_BYTES, + backend_api_body_shape, backend_api_error_code, BACKEND_API_BODY_SHAPE_MAX_BYTES, BACKEND_API_ERROR_BODY_MAX_BYTES, }; use crate::client::{flatten_authed_error, HostedApiError}; +use crate::transport::{billing_refusal, BillingRefusal}; use axum::extract::State; use axum::http::HeaderMap; use axum::routing::{get, post}; @@ -421,23 +421,17 @@ fn backend_api_error_code_rejects_non_identifier_and_non_string_codes() { assert_eq!(backend_api_error_code("Forbidden"), None); } -#[test] -fn backend_api_error_text_extracts_error_and_details_truncated() { - let body = - r#"{"success":false,"error":"Bad Request","errorCode":"E","details":["model: unknown"]}"#; - let text = backend_api_error_text(body).unwrap(); - assert!(text.contains("error=Bad Request"), "{text}"); - assert!(text.contains(r#"details=["model: unknown"]"#), "{text}"); - let long = format!(r#"{{"error":"{}"}}"#, "a".repeat(2000)); - assert!(backend_api_error_text(&long).unwrap().len() < 400); - assert_eq!(backend_api_error_text(r#"{"success":true}"#), None); - assert_eq!(backend_api_error_text(""), None); -} - /// The exact 182-byte body behind TAURI-RUST-13BR (backend /// `gemini/liveSessions.ts`): balance below the Gemini Live session reserve. const GEMINI_LIVE_RESERVE_BODY: &str = r#"{"success":false,"error":"Gemini Live requires an available balance of at least $1.00 (reserved per open session)","errorCode":"USER_INSUFFICIENT_CREDITS","details":{"reserveUsd":1}}"#; +/// The transport's classifier on a raw body, parsed as the SDK hands it over +/// (JSON when it parses, otherwise the text as a JSON string). +fn backend_billing_refusal(status: u16, body: &str) -> Option { + let body = serde_json::from_str(body).unwrap_or_else(|_| Value::String(body.into())); + billing_refusal(status, &body) +} + #[test] fn backend_billing_refusal_classifies_the_live_voice_gates() { assert_eq!(GEMINI_LIVE_RESERVE_BODY.len(), 182); diff --git a/crates/openhuman-tinyhumans/src/client/classify.rs b/crates/openhuman-tinyhumans/src/client/classify.rs index 09c3391ee1f..9a1fec887b7 100644 --- a/crates/openhuman-tinyhumans/src/client/classify.rs +++ b/crates/openhuman-tinyhumans/src/client/classify.rs @@ -2,7 +2,7 @@ //! expected states (typed [`HostedApiError`]s), which are transient noise, and //! which are reported. -use crate::transport::BackendTransportError; +use crate::transport::{BackendTransportError, BillingRefusal}; use anyhow::{Context, Result}; use openhuman_embed::__host::core::observability::{ contains_transient_transport_phrase, is_transient_http_status_code, report_error, @@ -54,26 +54,6 @@ pub(super) fn backend_api_body_shape(body: &str) -> String { } } -/// Max bytes of each of the backend's `error` / `details` text echoed by the -/// opt-in diagnostic log (see [`backend_error_text_logging_enabled`]). -pub(super) const BACKEND_API_ERROR_TEXT_MAX_BYTES: usize = 300; - -/// Env flag that opts in to logging the backend's `error` / `details` text. -/// Off by default: those values are server-controlled free text and may echo -/// user content, so they are never put in Sentry reports. -const LOG_BACKEND_ERROR_TEXT_ENV: &str = "OPENHUMAN_LOG_BACKEND_ERROR_TEXT"; - -fn backend_error_text_logging_enabled() -> bool { - std::env::var(LOG_BACKEND_ERROR_TEXT_ENV) - .map(|v| { - matches!( - v.trim().to_ascii_lowercase().as_str(), - "1" | "true" | "yes" | "on" - ) - }) - .unwrap_or(false) -} - /// The backend's `errorCode`, only when it is a short ASCII identifier (an /// enum-like code such as `INVALID_ARGUMENT`), so it is safe for telemetry. pub(super) fn backend_api_error_code(body: &str) -> Option { @@ -82,66 +62,6 @@ pub(super) fn backend_api_error_code(body: &str) -> Option { is_schema_like_key(code).then(|| code.to_string()) } -/// The backend's `error` and `details` text (the standard -/// `{success,error,errorCode,details}` failure envelope), each truncated. -/// Contains server-controlled values: for the opt-in local log only. -pub(super) fn backend_api_error_text(body: &str) -> Option { - let value = serde_json::from_str::(body.trim()).ok()?; - let render = |v: &Value| match v { - Value::String(s) => s.clone(), - other => other.to_string(), - }; - let mut parts = Vec::new(); - for key in ["error", "details"] { - if let Some(v) = value.get(key).filter(|v| !v.is_null()) { - let text = render(v); - parts.push(format!( - "{key}={}", - truncate_at_byte_boundary(&text, BACKEND_API_ERROR_TEXT_MAX_BYTES) - )); - } - } - (!parts.is_empty()).then(|| parts.join("; ")) -} - -/// The backend `errorCode` for an account whose balance is below what the -/// route reserves (e.g. Gemini Live's per-session reserve). -const INSUFFICIENT_CREDITS_ERROR_CODE: &str = "USER_INSUFFICIENT_CREDITS"; - -/// A billing refusal the backend signals on a gated hosted feature. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(super) enum BillingRefusal { - /// Balance below the route's reserve. - InsufficientCredits, - /// The feature needs a paid plan. - PaidPlanRequired, -} - -/// Classify a non-2xx response as a billing refusal: an -/// `errorCode: USER_INSUFFICIENT_CREDITS` envelope on any status -/// (TAURI-RUST-13BR, whose message matches no budget phrase), or a 403 whose -/// `error` text asks to add credits or names a paid plan (the voice-agent -/// signed-url gate, TAURI-RUST-11G3, which answers with `errorCode: FORBIDDEN`). -/// Only the `error` field is read for 403s, so a body that merely echoes a -/// phrase elsewhere does not match. -pub(super) fn backend_billing_refusal(status: u16, body: &str) -> Option { - let value = serde_json::from_str::(body.trim()).ok()?; - if value.get("errorCode").and_then(Value::as_str) == Some(INSUFFICIENT_CREDITS_ERROR_CODE) { - return Some(BillingRefusal::InsufficientCredits); - } - if status != 403 { - return None; - } - let error = value.get("error").and_then(Value::as_str)?; - if error.to_ascii_lowercase().contains("paid plan") { - Some(BillingRefusal::PaidPlanRequired) - } else if tinyinference_providers::is_budget_exhausted_message(error) { - Some(BillingRefusal::InsufficientCredits) - } else { - None - } -} - /// A JSON key safe to echo into telemetry: a short ASCII identifier. fn is_schema_like_key(key: &str) -> bool { const MAX_KEY_LEN: usize = 40; @@ -252,6 +172,47 @@ impl BackendClient { message_id, })); } + // The transport classifies billing refusals (it owns what a backend + // response means); surfacing them as typed errors is ours. + Err(BackendTransportError::BillingRefusal { + refusal, + status, + body, + }) => { + tracing::info!( + domain = "backend_api", + operation = "authed_json", + method = method.as_str(), + path = url.path(), + status, + failure = "non_2xx", + kind = ?refusal, + "[backend_api] billing refusal {status} on {} {}: {refusal:?}, not reporting to Sentry", + method.as_str(), + url.path(), + ); + let text = match body { + Value::String(text) => text, + other => serde_json::to_string(&other).unwrap_or_default(), + }; + let (method, path) = (method.as_str().to_string(), url.path().to_string()); + let body = + truncate_at_byte_boundary(&text, BACKEND_API_ERROR_BODY_MAX_BYTES).to_string(); + return Err(anyhow::Error::new(match refusal { + BillingRefusal::InsufficientCredits => HostedApiError::InsufficientCredits { + method, + path, + status, + body, + }, + BillingRefusal::PaidPlanRequired => HostedApiError::PaidPlanRequired { + method, + path, + status, + body, + }, + })); + } Err(BackendTransportError::Status { status, body }) => (status, body), Err(error) => { return Err(anyhow::Error::new(error).context(format!( @@ -297,41 +258,6 @@ impl BackendClient { let is_transient_infra = is_transient_http_status_code(status_code); let is_budget_exhausted = status_code == 400 && tinyinference_providers::is_budget_exhausted_message(&text); - // Checked before the budget-text path: an explicit - // `USER_INSUFFICIENT_CREDITS` code wins even when the message also - // matches a budget phrase. Budget 400s without it fall through as before - // (the 403 text match never overlaps the 400-only budget check). - if let Some(refusal) = backend_billing_refusal(status_code, &text) { - tracing::info!( - domain = "backend_api", - operation = "authed_json", - method = method.as_str(), - path = url.path(), - status = status_code, - failure = "non_2xx", - kind = ?refusal, - "[backend_api] billing refusal {status} on {} {}: {refusal:?}, not reporting to Sentry", - method.as_str(), - url.path(), - ); - let (method, path) = (method.as_str().to_string(), url.path().to_string()); - let body = - truncate_at_byte_boundary(&text, BACKEND_API_ERROR_BODY_MAX_BYTES).to_string(); - return Err(anyhow::Error::new(match refusal { - BillingRefusal::InsufficientCredits => HostedApiError::InsufficientCredits { - method, - path, - status: status_code, - body, - }, - BillingRefusal::PaidPlanRequired => HostedApiError::PaidPlanRequired { - method, - path, - status: status_code, - body, - }, - })); - } if is_budget_exhausted { tracing::info!( method = method.as_str(), @@ -377,18 +303,6 @@ impl BackendClient { method.as_str(), url.path(), ); - if backend_error_text_logging_enabled() { - if let Some(detail) = backend_api_error_text(&text) { - tracing::debug!( - method = method.as_str(), - path = url.path(), - status = status_code, - "[backend_api] {} {} failed ({status}): {detail}", - method.as_str(), - url.path(), - ); - } - } report_error( format!( "{} {} failed ({status}); response_body_len={}; body_shape={}{}", diff --git a/crates/openhuman-tinyhumans/src/transport/README.md b/crates/openhuman-tinyhumans/src/transport/README.md index 0f9767e729f..92a662c53fb 100644 --- a/crates/openhuman-tinyhumans/src/transport/README.md +++ b/crates/openhuman-tinyhumans/src/transport/README.md @@ -56,9 +56,12 @@ catch-all), so the classifiers in `client/classify.rs` and the integrations client see the same shapes they would see calling the SDK directly. -One case gets a typed variant here because only this backend's wire behavior -says what it means: a 404 on a channel-message path -(`.../channels//messages/`). +Two cases get a typed variant here because only this backend's wire behavior +says what they mean: a 404 on a channel-message path +(`.../channels//messages/`), and a billing refusal +(`billing_refusal`: `errorCode: USER_INSUFFICIENT_CREDITS` on any non-401 +status, or a 403 whose `error` asks for credits or a paid plan), which becomes +`BillingRefusal { refusal, status, body }`. ```text 404 on .../channels/

/messages/ @@ -81,7 +84,7 @@ The client recovers from the two differently (`HostedApiError` variants in | --- | --- | | [`port.rs`](port.rs) | The port: `BackendTransport`, `BackendRequest`, `BackendTransportError`, `TransportProfile`, `BaseUrlPurpose`, `QueryParam`. | | [`mod.rs`](mod.rs) | `SdkBackendTransport` and its `BackendTransport` impl. | -| [`error.rs`](error.rs) | `map_sdk_error`, plus the channel-message path parser and the unmatched-route check. | +| [`error.rs`](error.rs) | `map_sdk_error`, plus the channel-message path parser, the unmatched-route check and the billing-refusal classifier. | ## Key types and entry points diff --git a/crates/openhuman-tinyhumans/src/transport/error.rs b/crates/openhuman-tinyhumans/src/transport/error.rs index 7d3f84bd10d..574fb0add72 100644 --- a/crates/openhuman-tinyhumans/src/transport/error.rs +++ b/crates/openhuman-tinyhumans/src/transport/error.rs @@ -3,8 +3,9 @@ //! the integrations client see exactly the shapes they saw when they called //! the SDK directly. -use super::port::BackendTransportError; +use super::port::{BackendTransportError, BillingRefusal}; use reqwest::Method; +use serde_json::Value; use tinyhumans_sdk::Error as SdkError; /// Extract the provider and message id from a channel-message route, allowing @@ -28,6 +29,37 @@ fn is_unmatched_route_404(body: &serde_json::Value) -> bool { matches!(body, serde_json::Value::String(_)) } +/// The backend `errorCode` for an account whose balance is below what the +/// route reserves (e.g. Gemini Live's per-session reserve). +const INSUFFICIENT_CREDITS_ERROR_CODE: &str = "USER_INSUFFICIENT_CREDITS"; + +/// Classify a non-2xx response as a billing refusal: an +/// `errorCode: USER_INSUFFICIENT_CREDITS` envelope on any status but 401 +/// (TAURI-RUST-13BR, whose message matches no budget phrase; a 401 stays a +/// credential failure), or a 403 whose `error` text asks to add credits or +/// names a paid plan (the voice-agent signed-url gate, TAURI-RUST-11G3, which +/// answers with `errorCode: FORBIDDEN`). +/// Only the `error` field is read for 403s, so a body that merely echoes a +/// phrase elsewhere does not match. +pub(crate) fn billing_refusal(status: u16, body: &Value) -> Option { + if status != 401 + && body.get("errorCode").and_then(Value::as_str) == Some(INSUFFICIENT_CREDITS_ERROR_CODE) + { + return Some(BillingRefusal::InsufficientCredits); + } + if status != 403 { + return None; + } + let error = body.get("error").and_then(Value::as_str)?; + if error.to_ascii_lowercase().contains("paid plan") { + Some(BillingRefusal::PaidPlanRequired) + } else if tinyinference_providers::is_budget_exhausted_message(error) { + Some(BillingRefusal::InsufficientCredits) + } else { + None + } +} + /// Map the SDK's error for `method path` onto the core-owned transport error. /// /// A `404` on a channel-message route becomes a typed variant here, because @@ -62,7 +94,17 @@ pub fn map_sdk_error(error: SdkError, method: &Method, path: &str) -> BackendTra match error { SdkError::Url(e) => BackendTransportError::Url(e.to_string()), SdkError::Http(e) => BackendTransportError::Http(e), - SdkError::Status { status, body } => BackendTransportError::Status { status, body }, + SdkError::Status { status, body } => match billing_refusal(status, &body) { + Some(refusal) => { + log::debug!("[tinyhumans-transport] {method} {path}: billing refusal {refusal:?}"); + BackendTransportError::BillingRefusal { + refusal, + status, + body, + } + } + None => BackendTransportError::Status { status, body }, + }, SdkError::Header(e) => BackendTransportError::Header(e.to_string()), SdkError::Decode(e) => BackendTransportError::Decode(e.to_string()), SdkError::RouteNotExposed(method, path) => { diff --git a/crates/openhuman-tinyhumans/src/transport/mod.rs b/crates/openhuman-tinyhumans/src/transport/mod.rs index cf496272cf6..c531acaf9d0 100644 --- a/crates/openhuman-tinyhumans/src/transport/mod.rs +++ b/crates/openhuman-tinyhumans/src/transport/mod.rs @@ -23,10 +23,12 @@ mod port; #[path = "memory_bearer_tests.rs"] mod memory_bearer_tests; +#[cfg(test)] +pub(crate) use error::billing_refusal; pub use error::map_sdk_error; pub use port::{ - BackendRequest, BackendTransport, BackendTransportError, BaseUrlPurpose, QueryParam, - TransportProfile, + BackendRequest, BackendTransport, BackendTransportError, BaseUrlPurpose, BillingRefusal, + QueryParam, TransportProfile, }; /// One `reqwest::Client` per [`TransportProfile`], each built from diff --git a/crates/openhuman-tinyhumans/src/transport/port.rs b/crates/openhuman-tinyhumans/src/transport/port.rs index 491e799814b..1625ade6bc9 100644 --- a/crates/openhuman-tinyhumans/src/transport/port.rs +++ b/crates/openhuman-tinyhumans/src/transport/port.rs @@ -143,6 +143,15 @@ pub enum BaseUrlPurpose { Inference, } +/// A billing refusal the backend signals on a gated hosted feature. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BillingRefusal { + /// Balance below the route's reserve. + InsufficientCredits, + /// The feature needs a paid plan. + PaidPlanRequired, +} + /// Failure of a single backend round-trip, as seen by the core. #[derive(Debug, thiserror::Error)] pub enum BackendTransportError { @@ -184,6 +193,14 @@ pub enum BackendTransportError { /// Provider message id from the path. message_id: String, }, + /// A non-2xx billing refusal on a gated hosted feature (see + /// [`BillingRefusal`]). `body` as in [`Self::Status`]. + #[error("http {status}: {body}")] + BillingRefusal { + refusal: BillingRefusal, + status: u16, + body: Value, + }, /// The response carried a `{success:false, ...}` envelope on a 2xx status. #[error("backend reported failure: {error}")] Envelope { @@ -210,7 +227,7 @@ impl BackendTransportError { /// The HTTP status when this error is a [`Self::Status`]. pub fn status(&self) -> Option { match self { - Self::Status { status, .. } => Some(*status), + Self::Status { status, .. } | Self::BillingRefusal { status, .. } => Some(*status), Self::ChannelMessageNotFound { .. } | Self::ChannelMessageRouteMissing { .. } => { Some(404) }