diff --git a/FINDINGS-gemini-live.md b/FINDINGS-gemini-live.md new file mode 100644 index 00000000000..2ed26a06c51 --- /dev/null +++ b/FINDINGS-gemini-live.md @@ -0,0 +1,136 @@ +# FINDINGS: gemini live/sessions 400 (TAURI-RUST-13BR, #8501) + +## 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. +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) + 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; + "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, 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 +`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/FINDINGS-voice-signed-url.md b/FINDINGS-voice-signed-url.md new file mode 100644 index 00000000000..aa21a6edc23 --- /dev/null +++ b/FINDINGS-voice-signed-url.md @@ -0,0 +1,84 @@ +# 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 + `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. + +## 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 + 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` + (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). +- `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/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 99295df632f..2cd21e68485 100644 --- a/app/src/lib/i18n/ar.ts +++ b/app/src/lib/i18n/ar.ts @@ -4268,6 +4268,9 @@ 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 be4254eb5bc..bacbcc945d4 100644 --- a/app/src/lib/i18n/bn.ts +++ b/app/src/lib/i18n/bn.ts @@ -4354,6 +4354,10 @@ 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 8781f5afb7b..498c64b8a0c 100644 --- a/app/src/lib/i18n/de.ts +++ b/app/src/lib/i18n/de.ts @@ -4496,6 +4496,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.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 a4cb0a336cf..5609bb88534 100644 --- a/app/src/lib/i18n/en.ts +++ b/app/src/lib/i18n/en.ts @@ -4634,6 +4634,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 882e1a22a72..2e0a042a421 100644 --- a/app/src/lib/i18n/es.ts +++ b/app/src/lib/i18n/es.ts @@ -4448,6 +4448,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.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 15988a6eba6..bcb196c2d40 100644 --- a/app/src/lib/i18n/fr.ts +++ b/app/src/lib/i18n/fr.ts @@ -4471,6 +4471,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.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 a7b5617d7b2..fde872d6f16 100644 --- a/app/src/lib/i18n/hi.ts +++ b/app/src/lib/i18n/hi.ts @@ -4359,6 +4359,10 @@ 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 e3a08cf6ece..4cd438bac98 100644 --- a/app/src/lib/i18n/id.ts +++ b/app/src/lib/i18n/id.ts @@ -4397,6 +4397,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.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 cb59ec229ae..ee1864ebf1c 100644 --- a/app/src/lib/i18n/it.ts +++ b/app/src/lib/i18n/it.ts @@ -4432,6 +4432,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.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 b382c1807dd..ee498220005 100644 --- a/app/src/lib/i18n/ja.ts +++ b/app/src/lib/i18n/ja.ts @@ -4640,6 +4640,10 @@ 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 98b871c6006..ca4190cd1b3 100644 --- a/app/src/lib/i18n/ko.ts +++ b/app/src/lib/i18n/ko.ts @@ -4304,6 +4304,10 @@ 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 fd291ff7d89..a24841a724b 100644 --- a/app/src/lib/i18n/pl.ts +++ b/app/src/lib/i18n/pl.ts @@ -4419,6 +4419,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.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 c8876616ee8..bde6d7bcbfc 100644 --- a/app/src/lib/i18n/pt.ts +++ b/app/src/lib/i18n/pt.ts @@ -4421,6 +4421,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.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 cc1d27d5363..c932e8f2cd7 100644 --- a/app/src/lib/i18n/ru.ts +++ b/app/src/lib/i18n/ru.ts @@ -4403,6 +4403,10 @@ 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 560914a7cb7..e444033ccaf 100644 --- a/app/src/lib/i18n/tr.ts +++ b/app/src/lib/i18n/tr.ts @@ -4291,6 +4291,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.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 522c06c6165..c67f7a23032 100644 --- a/app/src/lib/i18n/zh-CN.ts +++ b/app/src/lib/i18n/zh-CN.ts @@ -4108,6 +4108,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 b2bba466fc1..f94479f4938 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_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_expected_error_classification.rs b/crates/openhuman-core/src/core/observability_expected_error_classification.rs index c64c956f351..def69326621 100644 --- a/crates/openhuman-core/src/core/observability_expected_error_classification.rs +++ b/crates/openhuman-core/src/core/observability_expected_error_classification.rs @@ -241,7 +241,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-core/src/core/observability_tests.rs b/crates/openhuman-core/src/core/observability_tests.rs index 0fe5c59f833..8e2bde786f2 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_composio_backoff_tests.rs"] mod error_classification_composio_backoff; #[path = "observability_error_classification_core_tests.rs"] 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 a8fa8c098df..b8bbafbdc78 100644 --- a/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs +++ b/crates/openhuman-tinyhumans/src/client/backend_client_tests.rs @@ -1,8 +1,10 @@ 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_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}; @@ -394,3 +396,180 @@ 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_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); +} + +/// 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); + 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( + "/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 { + ( + 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}" + ); + + // 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 + .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 b38b3c0ff56..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,6 +54,14 @@ pub(super) fn backend_api_body_shape(body: &str) -> String { } } +/// 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()) +} + /// 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; @@ -164,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!( @@ -238,13 +287,30 @@ 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(); + // 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(), + ); 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", 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/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) } 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"); +}