This guide documents the app-side voice UI, which ships in the workspace UI built from the separate allternit-ai repository (Allternit Desktop, ai.allternit.com and the m.allternit.com PWA). Paths below are relative to that repo unless they start with allternit/. The wire protocol is allternit-ai docs/VOICE_SESSION_PROTOCOL.md (frozen v1); “design doc §” references are to the Voice Stage design notes in allternit-ai docs/VOICE_STAGE_DESIGN.md.

The rule

Voice is input/output only. The agent loop doesn’t move.
  • A finished spoken turn (turn.ended) is sent through the same function the composer’s Send button calls. Tools, approvals, steering and the thread behave as if it were typed.
  • The assistant reply the thread already renders is streamed to the engine as speak.delta / speak.done.
  • Barge-in (speak.interrupted) calls the composer’s Stop.
There is no separate voice path to the model.

Modules (src/lib/voice/)

UI lives in src/components/voice/ (VoiceSession hosts VoiceBar and VoiceFullScreen; VoiceOrb wraps the brand AllternitOrb; SpokenLabel) and src/components/settings/VoiceSettingsPanel.tsx.

Live mode speaker

  • VoiceSpeaker draws the face at full size (208 px desktop, 148 px phone) with a speaker look around it. With a bot the face is its avatar in that bot’s look (useSpeakerLookFor(botId)). In a plain chat the face is VoiceOrb (the brand mark) in the default look (useSpeakerLookFor(undefined), no botColor, so Bot’s colour keeps the spectrum), in VoiceFullScreen and in VoiceBar (compact). The look’s square is SPEAKER_SCALE (1.78) times the face.
  • Looks: the six voice-ring (npm, MIT, pinned 0.1.2) VoiceOrb types (ring is its aura/VoiceRing; orbit, sash, signal, swell, pixel take color), and three canvas looks of our own (blocks, ascii, glow). still draws nothing.
  • Each look renders once into a hidden source canvas. Every frame it is copied to a back canvas behind the face and a front canvas masked to the lower part of the face, so the look passes in front of the body. VoiceOrb’s canvas is wider than its box (room to lean), so the copy uses the canvas’s real box.
  • voice-ring paints the Ring in its own spectrum; a palette recolours it in the copy (color blend, then destination-in with the source).
  • Levels come from the session getters (level while you talk, outputLevel while the bot speaks). No microphone is opened for the look. --voice-lv drives the rim light and contact shadow. Reduced motion pauses the looks and the recolour.
  • Settings (src/lib/voice/speaker-style.ts, useSettingsValue keys): voice.speakerStyle, voice.ringPalette, voice.captionSize, and per bot voice.speakerStyle.for.bot:<id> / voice.ringPalette.for.bot:<id> (null = Same as Settings). useSpeakerLookFor(botId) resolves the look.
  • VoiceCaptions is the phone caption band (paced word reveal, roll-up past two lines). VoiceTranscript + useVoiceTurns is the wide transcript built from the session’s turns. SpeakerLookPicker holds the Settings tiles, colour swatches and the SpeakerLookSwitch popover on the stage.
  • iPhone (surfaces/allternit-mobile/ios): VoiceSpeakerView draws the Ring with the vendored VoiceRingKit (Packages/VoiceRingKit, pinned commit) and Orbit, Sash, Signal, Swell and Pixel with OrbView (our port of the five ink types in OrbTypes.swift); Blocks, ASCII and Glow are SwiftUI canvases. Levels come from VoiceLevels (the existing mic taps and the voice session’s playback mix). A palette tints the look (light ink, then the colour multiplied in). Settings live in SpeakerLookStore (same keys as the web). A plain chat wraps VoiceMarkFace (the ThinkingOrb mark, scaled to the face) in VoiceSpeakerView with the default look, at 148 in VoiceModeView.plainStage and 28 compact in VoiceQuickBar.
  • Android (surfaces/allternit-mobile/android/feature/chat/.../voice): VoiceSpeakerView (VoiceSpeaker.kt) draws every look. A plain chat wraps PlainVoiceFace (the ThinkingOrb mark) in the default look from SpeakerLookStore.look(null), at 148 in PlainStage and 28 compact in VoiceQuickBar.
  • Dev preview with a scripted call: /preview-live-mode.html (?phone=1, ?theme=dark, ?look=, ?palette=, ?panel=settings, ?bar=1).

Voice identity and preview (design doc §4.6)

VOICE_NAMES (in settings.ts) maps every Kokoro speaker id (src/lib/voice/local/voices.ts) to a plain texture name (“Gentle”, “Crisp”, “Calm”); the test suite fails if the engine gains an id the map doesn’t name. Settings rows show the mapped name with the accent (af_/am_ American, bf_/bm_ British) and the raw id in small type. Custom voices (custom:<id>) keep their owner-given name and stay in the same Voice list, with a disabled Preview button and its reason. previewVoice() speaks one fixed sentence (VOICE_PREVIEW_TEXT) through the best available real path, never a Voice Session: the Desktop sidecar has no arbitrary-TTS endpoint, so there the preview plays the engine’s baked sample clip for that voice; in the browser the fixed sentence is synthesized in the page’s own Kokoro worker (speak role only — a stub answers for the listen role, so previews never download the recognition models). Custom voices have no one-shot path, so they don’t preview. previewVoiceAvailability() decides the disabled state and its reason; starting a preview cancels the one in flight.

First-run sheet (design doc §4.7)

VoiceIntroSheet is mounted by VoiceSession, so every entry point (composer mic, Talk button, full-screen) shows the “Talk with Allternit” sheet exactly once. It renders only while the persisted voiceIntroSeen flag is false; every dismissal — Start voice, Choose where voice runs (opens Settings › Voice via allternit:open-settings), Esc, the close button — sets the flag. It portals over the voice UI (z-index above VoiceFullScreen) and uses the voice tokens: white surface, neutral-fill controls.

Surfaces

All three surfaces build from the same components: Phone sizing comes from useIsPhoneViewport(): full-screen controls are 60 px round, padding respects env(safe-area-inset-*), and the PWA’s interactive-widget=resizes-content viewport keeps the bar above the keyboard. Under prefers-reduced-motion the orb is still (its own CSS) and the level ring is off; every state is also text (role="status").

Endpoint resolution

  • Device, in the browser (web and PWA): no bridge → resolveDeviceEndpoint() returns engine: 'device', wsUrl: 'local://voice'. VoiceSessionClient opens that URL as a LocalSocket (src/lib/voice/local/socket.ts), a WebSocket-shaped in-process transport, so reconnects, playback and barge-in are the same code as for a real socket. See “On-device voice in the browser” below.
  • Device (Desktop): window.allternit.voice.getSessionEndpoint() → { wsUrl?, httpUrl?, port?, token? } from the preload bridge. Desktop builds without that bridge fall back to http://127.0.0.1:8001 (this repo’s PORTS.VOICE, allternit/surfaces/allternit-desktop/src/main/config.ts) and no token. isAvailable() false → engine-not-installed. Web and the PWA never connect to loopback.
  • Your own provider (BYOK): Allternit hosts no voice (Eoj, 2026-11-04: no Cloud Voice minutes; the client-side ticket path is gone). where: 'openai' → resolveOpenAiEndpoint() returns engine: 'openai', wsUrl: 'byok://openai'; where: 'elevenlabs' → resolveElevenLabsEndpoint() returns engine: 'elevenlabs', wsUrl: 'byok://elevenlabs?device=<device wsUrl>'. VoiceSessionClient opens byok:// URLs as a ByokSocket (src/lib/voice/byok/socket.ts), a WebSocket-shaped in-process transport that speaks the Voice Session protocol, so live mode, captions, the transcript and the speaker ring (level / outputLevel) are unchanged.
    • OpenAI: POST https://api.openai.com/v1/realtime/client_secrets with the user’s key → { value }, a short-lived client secret for a transcription session (gpt-4o-transcribe, server_vad, 24 kHz PCM). The socket then opens wss://api.openai.com/v1/realtime?intent=transcription with subprotocols realtime and openai-insecure-api-key.<secret>, so the long-lived key never rides the WebSocket. Mic frames are resampled 16 → 24 kHz and sent as input_audio_buffer.append; input_audio_buffer.speech_started/stopped and conversation.item.input_audio_transcription.delta/completed become speech.*, transcript.delta/final and turn.ended. Replies: speak.delta text is cut into sentences (takeSentences) and each is read by POST /v1/audio/speech (gpt-4o-mini-tts, response_format: "pcm", streamed 24 kHz PCM16). Kokoro ids that share an OpenAI voice name (af_alloy, af_nova, am_echo, am_onyx, bm_fable) pick that voice; others use alloy. The bot’s own model still writes the reply; Realtime is not used as the brain, so the thread and what is spoken match.
    • ElevenLabs: listening stays on the device engine (the device URL, a LocalSocket in the browser or the Desktop sidecar); its speech.*, transcript.* and turn.ended pass through, its speak.* and audio are dropped, and session.ready is rewritten to engine: 'elevenlabs', outputSampleRate: 24000. Replies go to POST https://api.elevenlabs.io/v1/text-to-speech/{voiceId}/stream?output_format=pcm_24000 (xi-api-key, eleven_flash_v2_5). Barge-in: the device’s speech.started cancels the TTS in flight and emits speak.interrupted.
    • Keys: src/lib/voice/byok/keys.ts, localStorage allternit_voice_api_keys (openai, elevenlabs, elevenlabsVoiceId), the same pattern as the image and video provider keys. Read only by the page and sent only to the vendor. Both vendors allow browser CORS; the web CSP (public/_headers) allows https://api.openai.com, wss://api.openai.com and https://api.elevenlabs.io; Desktop’s CSP already allows https: and wss:.
    • Errors: a missing key → provider-key-missing before any request; 401/403, 402/429 from either vendor → a fatal error with code byok*, which the client reports as provider (Settings › Voice action); network failures close the socket so the client reconnects with backoff.
  • Automatic (chooseEngine): the device when packs report ready (in the browser also deviceAuto: the engine can run here, phones included; packs download on first use). A measured RTF above 0.9 still runs on the device; the reason suggests your own OpenAI. Otherwise engine: null with a reason that points to Settings › Voice (download the voice, or connect your own provider). Never a hosted engine. A stored where: 'cloud' from older builds migrates to 'auto' (persist version 1).
  • iPhone app (surfaces/allternit-mobile/ios/Core/Voice/VoiceRouter.swift): Automatic and This device try [.device, .legacy] (the in-process Moonshine engine, then Apple’s recognizer and the system voice). There is no cloud route; VoiceCloudClient.swift is gone. Your own OpenAI tries [.openai, .device, .legacy] and Your own ElevenLabs [.elevenlabs, .device, .legacy]; a missing key, a rejected key or no credit falls back to the phone with that reason in the status line. Both live in Core/Voice/ByokVoice.swift: ByokVoiceTransport is a VoiceTransport, so VoiceSessionClient, live mode, captions, barge-in and VoiceLevels are shared. It wraps a LocalVoiceEngine whose synthesizer is VendorSpeechSynthesizer (the same OpenAI /v1/audio/speech and ElevenLabs /stream?output_format=pcm_24000 requests as the web, streamed as 24 kHz PCM16 through VoiceAudioIO). OpenAI: the transport mints the client secret, opens the Realtime transcription socket (URLSessionWebSocketTask with the same two subprotocols), resamples mic frames 16 → 24 kHz and maps the same events; the inner engine only speaks, and its speak.ended after a barge-in cancel is reported as speak.interrupted. ElevenLabs: the inner engine is the normal on-device listener (Silero VAD + the Listening recognizer) with ElevenLabs as its voice. Keys: VoiceProviderKeys in the Keychain (KeychainHelper, accounts voice.byok.openai, voice.byok.elevenlabs, voice.byok.elevenlabsVoiceId), entered in Settings › Voice › Your own provider (secure field, masked when saved, Remove). Errors match the web: 401/403 and 402/429 are fatal and name Settings › Voice.
RTF is measured only on audio received after the client sent speak.done, so waiting for model text doesn’t count against the device.

Engine HTTP contract assumed by the UI (Phase 1 engine)

Parsed defensively; confirm or adjust with the engine owner.
  • GET /v1/models → { ready?: boolean, packs: [{ id, name, sizeBytes, state: "installed"|"downloading"|"available", progress?: 0–1 or 0–100 }] }. A missing endpoint is shown as “Voice engine not installed”.
  • POST /v1/models/{id}/download starts a pack download. The “Get Accurate pack” button looks for a pack whose id is accurate.
  • GET /v1/voices → ["af_heart", …] or { voices: [{ id, name?, language?, sampleUrl? }] }. Samples default to GET /v1/voices/{id}/sample (any browser-playable audio).

Errors and states

Phone calls: joinCallAudio

Call controls (sendCallControl in src/lib/gateway/call.ts) post straight to cloud-api POST /api/v1/voice/calls/{callId}/control through cloudApiFetch, which attaches the signed-in user’s Clerk token. They do not go through the local gateway, so Desktop, ai.allternit.com’s phone layout and the m.allternit.com PWA share this one path. A refusal or network failure throws CallControlError (status 0 when the request never completed) and CallScreen shows “Couldn’t send that. Try again.” joinCallAudio(callId, { mode: 'listen' | 'talk', token, url, room }) in src/lib/gateway/call-webrtc.ts. The caller (CallScreen) gets {token, url, room} from the listen or takeover call control and passes them in; the function doesn’t fetch tokens. It lazy-loads livekit-client (Apache-2.0), connects to url (production: wss://livekit.allternit.com), plays every remote audio track through hidden <audio data-call-audio> elements, unlocks playback with startAudio() (the call runs from a click), publishes the mic only in talk, and returns { callId, leave }. It resolves null (and disconnects) when credentials are missing, the connect fails, or the mic is refused in talk, so the UI never claims a person is on the call when they aren’t.

Tests

src/lib/voice/__tests__/: an in-memory mock Voice Session server (mock-voice-server.ts) drives session-client.test.ts; conversation.test.ts, voice-lib.test.ts (PCM, the shipped playback worklet, endpoints, Automatic mode, engine parsing), voice-names.test.ts (the identity map covers every engine voice id, voiceIntroSeen), preview.test.ts (preview availability reasons, one-at-a-time cancellation, sample and synthesized paths) and call-audio.test.ts (fake LiveKit room). UI: src/components/voice/__tests__/ (including voice-intro.test.tsx for the first-run sheet’s gate and every dismissal path); src/components/settings/__tests__/VoiceSettingsPanel.test.tsx.

What replaced what

The quick voice bar and full-screen voice replace components/chat/VoiceModeOverlay.tsx and components/ai-elements/voice-call-mode.tsx. The orphaned ai-elements/voice-{presence,overlay,session,toolbar,controls,selector,visualizer,provider}.tsx were removed with the ShellApp VoicePresence mount. Dictation (useComposerVoice) keeps Desktop’s IPC transcription and uses a Voice Session elsewhere instead of a loopback /v1/stt. The legacy providers/voice-provider + services/voice (bot voice previews/TTS on Desktop) remain for the bot voice settings panel.

On-device voice in the browser

src/lib/voice/local/. The Voice Session protocol, spoken in-process:
  • engine.ts — LocalVoiceEngine: takes the client frames (JSON + PCM16 mic audio), emits session.ready (engine device), speech.*, transcript.final, turn.ended, speak.* and binary PCM16 speech. Turns end on VAD silence (vad mode; “smart” is treated as vad for now). Speech is synthesized sentence by sentence (takeSentences). Barge-in: VAD speech start while speaking cancels synthesis and sends speak.interrupted. The heavy work sits behind the EngineBackend interface, which tests fake.
  • worker-backend.ts + worker.ts — two module Web Workers running sherpa-onnx WebAssembly: listen (Silero VAD + Moonshine tiny, 45 MB) and speak (Kokoro-82M int8 model.int8.onnx 114 MB, pack 166 MB). Separate workers keep VAD live while Kokoro synthesizes. A synthesis call can’t be interrupted mid-sentence; chunks that arrive after a cancel are dropped, and the next sentence isn’t started.
  • model-store.ts / manifest.ts — one object per file at {VITE_VOICE_MODEL_BASE}/v1/{vad|stt|tts}/{path} (default https://runtime.allternit.com/voice-models; the host needs Access-Control-Allow-Origin). Each file is hashed while streaming (sha256.ts), checked against the pinned size and sha256 in manifest.ts, then stored in the Cache API (allternit-voice-models-v1). scripts/voice-models-mirror.mjs builds that layout and manifest from the same pinned archives as the native packs (services/voice/src/models.rs); upload its output to the host.
  • capability.ts — assessCapability(): Worker, WebAssembly + SIMD, AudioWorklet, Cache API, secure context, at least 2 GB deviceMemory when reported; phone detection. Automatic and “This device” both use the engine wherever it can run, phones included: the first session downloads the ~210 MB of packs with progress in the voice bar and full screen. pruneStaleModels() deletes cached files the manifest no longer lists (the old 326 MB fp32 model.onnx). The measured-RTF rule still applies.
  • vite-plugins/voice-engine.ts — serves the browser build of sherpa-onnx wasm and its wrapper scripts under /voice-engine/ (dev middleware and emitted build assets), never in the JS bundle, from VOICE_ENGINE_DIR (default vite-plugins/voice-engine-build/: sherpa-onnx-wasm.{js,wasm} plus the upstream sherpa-onnx-{asr,tts,vad}.js). With the directory absent it serves nothing. The served set carries LICENSE-GPL-3.0.txt and SOURCE.txt: the sherpa-onnx wasm links espeak-ng (GPL-3.0-or-later), so it is its own clearly licensed asset, used only through postMessage. The PWA build emits the same assets on its own origin.
  • Browser engine build and the flag. The engine is built and checked in a real browser. vite-plugins/voice-engine-build/ holds the browser WebAssembly (sherpa-onnx v1.13.8 build-wasm-simd-web.sh, emscripten 4.0.23, MEMFS, no models embedded; VAD + Moonshine + Kokoro in one module, 14 MB wasm + 91 KB glue) plus the unmodified upstream sherpa-onnx-{asr,tts,vad}.js wrappers; the vite plugin serves them under /voice-engine/ with LICENSE-GPL-3.0.txt and SOURCE.txt. The npm package sherpa-onnx cannot be used (its wasm is the Node/NODERAWFS build). The exact build recipe is published in Allternit/allternit-tts (wasm/BUILD.md). The engine stays off until VITE_VOICE_BROWSER_ENGINE=on is set for the build (unset → Settings says “isn’t available in the browser yet”, Automatic never picks it); with it on, set VITE_VOICE_MODEL_BASE only if the models are not at runtime.allternit.com/voice-models. To rebuild the wasm, follow the recipe and copy sherpa-onnx-wasm-web.{js,wasm} to sherpa-onnx-wasm.{js,wasm} in that directory. Real-browser check (headless Chrome, fake mic from a 16 kHz wav, models from a local CORS server): session ready ~12 s cold on a busy machine, a spoken question became the exact transcript, turn.ended fired within 0.1 s of speech end, and speak.delta produced Kokoro PCM (first audio ~4 s for one sentence on that busy machine; single-threaded wasm).
  • Service workers: the model cache is not a SW cache. public/sw.js, public/fabric-session-service-worker.js and public/boot.js leave caches named allternit-voice-models-* alone when they clear old caches; the SW never precaches model or engine files.
  • native-stt.ts — native listening (Settings › Voice › Speech to text, localStorage allternit-voice-listening, automatic by default). In Safari and every iOS/iPadOS browser (WebKit, Apple’s speech engine; isWebKitSpeechBrowser), withNativeListening() wraps the worker backend in NativeListenBackend: Web Speech SpeechRecognition (continuous: false, interimResults: true, restarted after each result; processLocally set where supported; passed our own mic track where WebKit accepts start(track)) supplies the words, and the listen worker gets {t: 'stt', on: false} so it keeps running Silero VAD but skips Moonshine. Partials become transcript.delta, finals transcript.final + turn.ended under the same segmentId; session.ready reports models.stt: "apple-speech". Never used in Chrome/Edge (their recognizer uploads audio to Google), Electron or Firefox. Echo: results count only after our VAD (on the echo-cancelled getUserMedia stream) reported user speech since the last turn, so the bot’s own voice can’t become a turn; barge-in still comes from that VAD. Level: the speaker ring still reads audio-io’s mic level from our own graph. Mute: mic.mute calls backend.setMuted, which stops the system recognizer. Fallback: a non-benign recognizer error (not-allowed, service-not-allowed, audio-capture, network, language-not-supported, …), a restart loop or our mic track muting/ending switches back to Moonshine (stt: on) for the rest of the session with one console.info line.
  • iPhone app (surfaces/allternit-mobile/ios/Core/Voice/LocalVoiceBackends.swift): the “This device” engine keeps Silero VAD, turn-taking and barge-in in LocalVoiceEngine; only the recognizer changes. SystemFirstRecognizer sends each VAD segment to Apple’s recognizer: SpeechAnalyzer + SpeechTranscriber (.transcription preset, model retention processLifetime) on iOS 26+, with the locale’s model installed through AssetInventory in the background; SFSpeechRecognizer with requiresOnDeviceRecognition on iOS 17–25 when supportsOnDeviceRecognition is true. Segments come from the voice-processing (echo-cancelled) mic, so the bot’s speech isn’t transcribed; VoiceLevels still drives the ring. Not ready (model installing, permission not granted) uses Moonshine for that segment; an error switches to Moonshine for the session (os log category voice-stt). SettingsStore.listening (allternit-settings-voice-listening) picks Automatic or Allternit on-device.
Tests: src/lib/voice/local/__tests__/ (protocol conformance with a fake backend, model download/verify, capability and Automatic rules).

On-device Kokoro on iPhone

The iPhone app (surfaces/allternit-mobile/ios) reads replies with Kokoro-82M on iOS 18+ devices, with no espeak-ng: sherpa-onnx’s Kokoro needs espeak-ng (GPL-3), which an App Store build can’t carry.
  • Engine: Packages/KokoroKit vendors kokoro-ios at 4d6d1d8 (main after 1.0.9, MIT, Kokoro on MLX Swift), MisakiSwift 1.0.6 (Apache-2.0, English G2P: gold/silver lexicons plus a BART fallback network) and MLXUtilsLibrary 0.0.6 (Apache-2.0) at pinned commits, on mlx-swift 0.30.2 (MIT). They are vendored because upstream declares iOS 18 while the app targets iOS 17. Patches: Misaki data loads from MisakiResources.directory, fp16 weights are upcast to fp32 at load, the espeak G2P file and NpyzReader are removed (no ZIPFoundation). Package.swift lists the commits and how to update.
  • Seam: KokoroSpeechSynthesizer (Core/Voice/KokoroSpeech.swift) is a LocalSynthesizer, so LocalVoiceEngine drives it like the system voice: one sentence at a time from SpeechSentenceChunker, PCM16 24 kHz in 200 ms chunks into the session audio, so the speaker ring’s output level, echo cancellation and barge-in are unchanged. A barge-in drops the rest of the sentence; the sentence being computed finishes on its queue and is discarded. Sentences over 300 characters are cut at word boundaries (Kokoro takes at most 510 phonemes).
  • Voice: the bot’s config.voice.voice_id (or config.voice_id), else the phone’s pick (UserDefaults allternit-settings-voice-kokoro), else af_heart. af_/am_ voices use US English, bf_/bm_ British.
  • Models: VoicePackManager.kokoro downloads voice-models/ios/v1/ from runtime.allternit.com (R2 allternit-runtime; ALLTERNIT_VOICE_MODEL_BASE overrides the host) into Application Support voice/kokoro-v1, sha256-checked, with progress, never in the app bundle: kokoro/kokoro-v1_0-fp16.safetensors (164 MB), kokoro/voices-v1_0-fp16.safetensors (7 MB, the 28 stock voices) and misaki/ (US and GB lexicons and BART, 19 MB). The first voice session starts the download on Wi-Fi only (allowsExpensiveNetworkAccess = false); Settings › Voice › Reply voice downloads on any network. scripts/build-ios-kokoro-pack.sh rebuilds the files from pinned upstream sources byte for byte and prints the upload commands.
  • Fallback: iOS 17, the simulator (MLX has no simulator GPU), pack not downloaded, under 900 MB of free memory, the app in the background (no GPU work allowed) or any MLX error: SystemSpeechSynthesizer reads that sentence, with one os log line (category voice-tts). A load or MLX error keeps the system voice until the app restarts. The weights load once per process and are dropped on a memory warning.

Your own key: storage, sync and QR handoff

Connect, the vendor checks (vendors.ts), the voice picker, the QR handoff (handoff.ts) and the account sync (accountSync.ts) are in src/lib/voice/byok/ and src/components/settings/ (VoiceKeyConnect, VoicePicker, VoiceKeyHandoffCard). The user flow is in Talk to your bots.

Storage per surface

Android uses the PWA.

Account sync (opt-in, off by default)

With “Save to my Allternit account” on, the app sends keys to cloud-api and other signed-in devices read them. Turning it off calls DELETE /api/v1/voice/keys; devices keep their local copies. The routes (routes/voice_keys.rs) need a signed-in session. Platform API keys get 403. Responses are Cache-Control: no-store. See Voice Keys API. Migration 128_voice_keys.sql adds two tables:
  • user_voice_keys: one row per user and provider (openai or elevenlabs). The key is sealed with AES-256-GCM through CredentialCipher, using ALLTERNIT_CREDENTIALS_KEY (the same cipher as user_inference_keys). key_nonce is the 12-byte nonce.
  • voice_key_handoffs: the QR relay. It holds sid, the owner and the receiver’s one-time public key, and lives 120 seconds. Migration 135_voice_handoff_sealed.sql adds sealed_nonce, sealed_ciphertext and delivered_at for the sealed key. Expired rows read as not found and are pruned on insert.

QR handoff protocol (v1, one scan)

The user scans once. The key is end-to-end encrypted between the two devices and goes through cloud-api only in that sealed form, so cloud-api cannot read it. The sender’s public key travels only in QR1, never to the server, and the 6-digit check is what keeps a relay from substituting its own key.
  1. The sender (computer) generates its P-256 key pair, calls POST /api/v1/voice/handoff and gets sid. It shows QR1.
  2. The receiver (iPhone) generates its own P-256 key pair, scans QR1 and PUTs its public key to /handoff/:sid/receiver.
  3. The sender polls GET /handoff/:sid until receiver_pubkey appears.
  4. Both sides show the 6-digit confirm code. The user taps Codes match on the sender.
  5. The sender derives the shared key, encrypts, and PUTs {nonce,ciphertext} to /handoff/:sid/sealed.
  6. The receiver polls GET /handoff/:sid/sealed, takes the sealed key once, decrypts it and shows Connected.
QR2 is still shown on the sender as a fallback for iPhone builds that only read QR2. On those builds the receiver scans QR2 instead of polling. The crypto and docs/voice-handoff-vectors.json are unchanged by the relay. Wire details:
  • Curve P-256. Public keys are uncompressed SEC1 points (65 bytes, 0x04 || X || Y), base64url without padding.
  • Key derivation: ECDH, then HKDF-SHA256 over the shared x coordinate with info = allternit-voice-key-handoff-v1, salt = sid (UTF-8), 32 bytes out.
  • Encryption: AES-256-GCM, 12-byte nonce, 16-byte tag, no AAD. The plaintext is JSON {"provider","api_key","voice_id"?}.
  • Confirm code: SHA-256 of utf8(sid) || pubA_raw || pubB_raw; the first 4 bytes as a big-endian uint32, mod 1000000, zero-padded to 6 digits.
  • QR1: allternit-voice:1:<sid>:<senderPub>. QR2: allternit-voice:2:<sid>:<nonce>:<ciphertext+tag>. All fields base64url.
  • Sending from the iPhone to a computer isn’t offered.
docs/voice-handoff-vectors.json in the platform repo is the shared test vector (keys, confirm code, HKDF output, ciphertext, QR strings). The web, iOS and cloud-api tests all check it; the file is generated by docs/voice-handoff-vectors.gen.mjs, so don’t edit it by hand.