Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
136 changes: 136 additions & 0 deletions FINDINGS-gemini-live.md
Original file line number Diff line number Diff line change
@@ -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 `<METHOD> <path> failed (<status>): <body>`
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=<errorCode>` 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.
84 changes: 84 additions & 0 deletions FINDINGS-voice-signed-url.md
Original file line number Diff line number Diff line change
@@ -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=<code|none>` 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.
2 changes: 2 additions & 0 deletions app/src/features/human/LiveVoiceControls.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
6 changes: 6 additions & 0 deletions app/src/features/human/LiveVoiceControls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand Down
3 changes: 3 additions & 0 deletions app/src/lib/i18n/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}',
Expand Down
4 changes: 4 additions & 0 deletions app/src/lib/i18n/bn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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} ব্যর্থ হয়েছে',
Expand Down
4 changes: 4 additions & 0 deletions app/src/lib/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
2 changes: 2 additions & 0 deletions app/src/lib/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
Loading
Loading