Separate detected speech limits from continuous microphone silence while preserving transport bounds and absolute commit fencing. Handle verified OpenAI cancellation races and terminal items, preserve causal close outcomes, and share bounded cleanup ownership with safe diagnostics. Add regression coverage and align the API contract and frontend handoff. Validation: 61 focused unit tests passed; staged diff whitespace checks passed. Live browser acceptance remains outstanding.
13 KiB
Authenticated voice integration
The backend selects Gemini Live or OpenAI Realtime with VOICE_PROVIDER. Gemini
is the temporary default while an OpenAI Realtime voice key is unavailable. Extraction, embeddings, calibration and canonical
search retain their existing providers and frozen profiles. The browser never
receives a provider credential, event, model selector or private call ID.
Use the client module and audio worklet, served on the configured same origin. This is a developer example, not a production interface.
import {VoiceClient} from './voice-client.js';
const client = new VoiceClient(event => console.log(event.type));
await client.login(username, password); // supply credentials from your local form
client.newCreationAttempt(); // exposes IDs before C01 and retains immutable payloads
await client.reserve(); // after an ambiguous response: await client.retryCreation()
await client.connect(); // call from a user gesture permitting AudioContext
// On explicit stop: await client.close(); await client.poll();
// On media loss: await client.recover(); await client.freshSession();
// On logout: await client.logout();
GET /api/v1/me refreshes actual expiry and CSRF. HTTP mutations use the opaque
cookie and CSRF; WebSocket upgrade uses that cookie plus the browser's Origin.
The API accepts no bearer or query token. Preserve the same normalized payload
and request ID after ambiguous creation; V03 recovers without opening a provider connection.
Connected/terminal recovery does not restore media/provider context. Close the
old reservation before requesting a fresh conversation and session.
The exercised schemas are session_ready, transcript (role user/assistant,
status partial/completed), sources, user_speech_started, audio_started,
audio_ended, turn_interrupted, error, and the sole client control
playback_progress with audio_ref and cumulative played_ms. Transcripts
and sources are retrieved/current-session information, not durable full history.
The client waits for session_ready before opening the microphone. It verifies
an actual 24 kHz AudioContext, which resamples device capture; the worklet mixes
channels and emits aligned mono PCM16LE 480-byte frames. Unsupported context
rates fail explicitly. Capture enforces dual capacity bounds of 96000 raw PCM bytes
AND 100 messages across capture handoff and outgoing WebSocket buffering. The worklet
tracks both pending messages and pending bytes (rejecting with overflow if either limit
would be exceeded). Capture handoff does not falsely imply network completion: the client
polls socket.bufferedAmount and delivers {type: 'accepted', bytes} to the worklet only
upon verified conservative buffer drain (captureBytes - bufferedAmount >= packetBytes).
Capacity is released exactly once on verified drain or terminal cleanup. Ordered
binary playback belongs to the last audio_started reference and is sealed by
audio_ended. The client reserves playback capacity before PCM conversion and counts pending
MessagePort handoffs. The worklet independently enforces 96000 raw PCM bytes AND
100 messages across references, retaining a partially consumed packet in the
message count. Consumed-sample acknowledgements release byte reservations; only
completed/discarded packets release message reservations, exactly once. Admission
and flush acknowledgements never imply heard audio. The worklet reports the floor of actual
consumed samples / 24, never estimated elapsed time or generated samples.
Interruption flushes queued audio and reports each reference's final consumed
position. Explicit close stops capture and tracks, flushes actual final playback progress
while the socket is usable, commits HTTP V04, and then closes transport/audio.
Requests wait at most five seconds each, flush at most 250 ms and AudioContext
close at most one second; a genuine transport loss stays a failure.
Connection generations own their audio, tracks and callbacks. Late permission
results are stopped immediately, cleanup is coalesced, and callbacks from an old
socket cannot close a newer session. Logout always attempts A02 even if identity
refresh or V04 fails, then clears local resources and identity. Valid sessions
retain CSRF enforcement; expired/repeated logout still validates Origin.
Canonical search errors for an eligible turn are displayed while its authorized spoken explanation and later interaction continue. Setup/transport/overflow, authority and context synchronization failures stop resources. Error fatality is not inferred from retryable alone. The client does not retry tool execution. Identical durable technical results replay only after fresh backend eligibility checks; cancelled/revoked/stale-parent results cannot continue.
Gemini setup readiness requires native setupComplete, not an echoed requested configuration. This profile requires native voiceActivity with usable offsets; missing boundaries fail safely. Input transcripts without offsets become ambiguous after more than one input; that fails rather than rebinding delayed speech. Output transcripts use outputTranscription. There is no verified sample-level Gemini context truncation: interruption/context cleanup closes the session and requires freshSession. Seamless barge-in is not certified. Diagnostic text smoke uses native clientContent; first correlated model/tool output proves input consumption. It never fabricates an item acknowledgement.
Technical fake-wire/worklet checks, retrieval quality and real-browser speech acceptance are separate. Real microphone/Persian audio/network behavior remains unverified until explicit provider opt-in, approved corpus, measured compatible calibration and budgets are supplied. See the repair report.
Creation attempts and recovery
newCreationAttempt() explicitly selects new C01 and V01 request IDs and retains
C01's immutable payload before either request. creationAttempt,
conversationRequestID and requestID are inspectable after failure. Once C01's
response supplies the owned conversation ID, V01's immutable payload is stored
before sending V01. retryCreation() (or reserve() with the existing attempt)
replays identical payloads and IDs after a committed response is lost. Calls with
changed IDs require an explicit new attempt; payload mutation is rejected locally,
and changed payloads at the backend retain IDEMPOTENCY_CONFLICT behavior.
recover() uses V03 and never connects automatically; a lost C01 response may
precede V01, so recovery can return SESSION_NOT_FOUND until identical C01/V01 retry.
freshSession() explicitly closes/reconciles the old reservation, creates a new
attempt and connects. Retain the attempt in application storage if page reload
recovery is required; this example retains it only in the current JS instance.
Backend configuration and supported startup
Gemini deployment (no OpenAI voice key required):
VOICE_PROVIDER=gemini
GEMINI_API_KEY=<server-only-key>
GEMINI_MODEL=gemini-2.0-flash-exp
GEMINI_VOICE=Aoede
# GEMINI_PROXY=https://trusted-proxy.example:443
OpenAI deployment (no Gemini key required):
VOICE_PROVIDER=openai
OPENAI_REALTIME_API_KEY=<server-only-voice-key>
OPENAI_REALTIME_MODEL=gpt-realtime-mini
OPENAI_REALTIME_VOICE=shimmer
# OPENAI_REALTIME_PROXY=https://trusted-proxy.example:443
Existing GEMINI_* names and legacy PROVIDER remain valid. Matching provider
aliases are accepted; conflicting VOICE_PROVIDER/PROVIDER across environment
and dotenv configuration fail. Explicit constructor settings otherwise take
priority over environment, then dotenv. OPENAI_API_KEY is not a voice alias:
embedding and other provider configuration remain independent. A compatible
measured SEARCH_CALIBRATION_REPORT and the existing origin/host/cookie settings
are still required. Do not put secrets in browser configuration. Model defaults
are compatibility defaults, not claims of current live service availability.
Reservation snapshots pin selected provider/model/voice/native rates plus search
profile; stream admission rejects a changed configuration. Durable V01 replay
still returns the original reservation without reinterpreting it.
.venv/bin/python -m app.server --host 0.0.0.0 --port 8000
# Separate ingestion process:
.venv/bin/python -m app.worker
Docker Compose uses the same API entrypoint. Run exactly one API process and no API reload/multiple workers: media admission and runtime registry are process-local, not distributed ownership. The ingestion worker is a separate process. For production use trusted same-origin HTTPS/cookie settings and bounded reverse proxy configuration; a proxy cannot substitute for backend message reassembly limits.
The supported entrypoint explicitly selects BoundedWebSocketProtocol over the
installed Uvicorn legacy WebSocket implementation, configured with validated
LIVE_* RuntimeSettings. It performs bounded reassembly using finite scratch
storage (bytearray) and an incremental UTF-8 decoder without retaining an unbounded
list of continuation metadata (preventing long empty-continuation memory retention).
Cancellation and connection termination release all scratch and assembly resources.
The parser rejects binary messages above max_binary_message_bytes (default 9600 bytes)
and UTF-8 text above max_client_control_bytes (default 4096 bytes), including aggregate
fragments, from declared frame lengths before reading payload/decoding. Compression is not
negotiated; any RSV/compression bit is rejected from the first two header bytes.
Total receive capacity strictly accounts for assembling, queued, and delivered/in-flight
messages against max_queued_audio_messages and max_queued_audio_bytes. Delivering a
message to the ASGI application retains its reservation until the next recv() call,
preventing an unmonitored runtime audio backlog. Queue depth is configured as
max(1, max_queued_audio_messages - 2) when the budget exceeds two, or one for small
budgets, preventing zero-capacity deadlocks on message budgets of one and two while
retaining deterministic wire backpressure. TCP/StreamReader scratch and kernel
buffers are separate finite transport buffers, not playback or commitment evidence.
Application checks remain defense in depth. Generic uvicorn app.main:app, ws=auto
and alternate/sansio backends are outside this supported policy. The selected legacy
backend is deprecated upstream: rerun real loopback tests on dependency upgrades;
replacement needs equivalent pre-payload enforcement, not renamed flags alone.
Authority-check saturation, timeout and SQL failure stop the session with
SEARCH_SATURATED, SEARCH_TIMEOUT and DEPENDENCY_UNAVAILABLE respectively; unverified
content/continuation is withheld. Verified revocation uses CONTEXT_REVOKED. Technical
failures persist failed with matching close reason/error code; committed terminal
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
saturation, but a database outage can still prevent a durable write and is logged.
Continuous microphone input
The example continuously sends 24 kHz mono PCM16LE after readiness, including silence. The 2026-10-10 input-accounting repair supersedes the earlier deterministic 10-second idle overflow. The 480000-byte limit now bounds trusted detected uncommitted speech intervals, including VAD padding. Local queued/in-flight input remains bounded to 96000 bytes and 100 messages, with existing send deadlines. Silence outside detected speech does not consume the speech allowance. A completed send releases local transport storage only; it is neither provider consumption nor commitment.
Keep sending the original timeline; no RMS gate, new VAD, buffer clear or invented silence acknowledgment is required. Genuine long speech, missing stop/commit, transport saturation and expiry still fail safely. Browser/provider acceptance remains necessary; seamless Gemini context truncation remains unsupported.
Automated fake-provider/loopback/worklet results prove technical boundaries only. Real provider access, measured retrieval quality, Persian speech, microphone, heard audio and browser/hardware acceptance require their separate explicit opt-ins and prerequisites; frontend readiness is not certified.
Document workflow integration
Use the Phase 3 HTTP handoff and delivered DocumentClient with this VoiceClient. F01 exposes current OCR policy; document polling exposes its frozen policy and actual review state. Automatic OCR admission does not imply human review, factual authority, readiness or activation. Read K01 before replacing selection; removal revokes active voice context.