Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: talk to bots through OpenAI or Gemini realtime voice
leepokai43fcd870f463
diff --git a/CLAUDE.md b/CLAUDE.mdindex b831b3ca..ecdb8b33 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -31,7 +31,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- Multiple computers per account are future work, not a current priority: the product targets one computer. The multi-computer structure (`AccountStore`, `BotReference`) stays because relay/accounts/SSH build on it; don't extend or polish multi-computer features unless asked.- Environments: **dev** (`dev-api.codync.dev`, Clerk development instance, Debug builds) and **main** (`api.codync.dev`, Clerk production, Release builds); `apps/shared/Config/<env>.plist` becomes `AccountConfig.plist`. Details: [spec §14.0](docs/reference/remote-relay.md).- Push: iOS registers its APNs token with `relay/` → gets an AES-GCM ticket → gives it (plus its X25519 push key) to the host; the host seals title/body to that key and a Notification Service Extension opens it, so `relay/` sees only generic text. Alert kinds: *needs you*, *done*, and *failed*, suppressed while the iOS app is connected. Delivery and lifecycle: [notification design](docs/design/push-and-live-activity.md).-- Voice call (iPhone): on-device speech in, bot's final replies read aloud; the host sees plain messages. Grok-style call bar; bring-your-own-key realtime design: [docs/features/voice-call.md](docs/features/voice-call.md).+- Voice call (iPhone, Mac): on-device speech, or OpenAI / Gemini realtime on the user's own key (kept in the host's vault, which mints per-call credentials; audio goes device ↔ provider); the host sees plain messages. Grok-style call bar: [docs/features/voice-call.md](docs/features/voice-call.md).- Usage: local only — `claude -p /usage --no-session-persistence`, the Claude status line (`codync-host statusline`, wrapping any existing one), Claude ACP `usage_update` rate-limit meta, Codex rollout files. Never call provider APIs with agent credentials.- macOS app is thin: embeds `codync-host` in `Contents/MacOS` (Xcode post-build script runs cargo), installs it as a launchd agent via `codync-host install`; menu bar shows status/pairing/usage and opens the native chat window (NavigationSplitView over `CodyncUI`). Not sandboxed, not Mac App Store (the host must spawn CLIs).diff --git a/apps/Codync.xcodeproj/project.pbxproj b/apps/Codync.xcodeproj/project.pbxprojindex 64923b3b..ab486791 100644--- a/apps/Codync.xcodeproj/project.pbxproj+++ b/apps/Codync.xcodeproj/project.pbxproj@@ -56,6 +56,7 @@BF77DD7946621D8818EDAB9B /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A87B0091DAF0E4807D62017 /* SettingsView.swift */; };C263D5693212EB0812A232D9 /* CodyncMacApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7AB018B7D7F8E8137E0A1012 /* CodyncMacApp.swift */; };C7ED489193AC0934515D2E85 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = D0DE72EEAEC947C1D3CA237F /* PrivacyInfo.xcprivacy */; };+ D51C32451FB38C337707E3A5 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 124AB371AB16E5E232DE0A07 /* SettingsView.swift */; };EBB0417A5FB2CE6D514D21BE /* ClerkKit in Frameworks */ = {isa = PBXBuildFile; productRef = D9AB2F442A5F243653EAE936 /* ClerkKit */; };EC14C7513A8D2999D97D5ABA /* Screen.app in Embed Dependencies */ = {isa = PBXBuildFile; fileRef = 741B706007BA1B91CB853699 /* Screen.app */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };F171F16563D1FF6308697173 /* CodyncUI in Frameworks */ = {isa = PBXBuildFile; productRef = 06C9F37C6502131CAF0F145E /* CodyncUI */; };@@ -129,6 +130,7 @@0829A4FCADAC108E8C2DB2F1 /* Widgets.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widgets.entitlements; sourceTree = "<group>"; };08D070CB1CE05D4848C09C52 /* com.pokai.Codync.screen.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = com.pokai.Codync.screen.plist; sourceTree = "<group>"; };0A87B0091DAF0E4807D62017 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };+ 124AB371AB16E5E232DE0A07 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };1318104275E5BEC47B7088AD /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };14B7967A8F027FF28EAEA893 /* HostController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostController.swift; sourceTree = "<group>"; };1E47C60032C326157E0386B8 /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; };@@ -413,6 +415,7 @@children = (B71D3227DAFDD03155870401 /* ChatWindow.swift */,9F70117FA3097C5A6F28C89B /* ComputersView.swift */,+ 124AB371AB16E5E232DE0A07 /* SettingsView.swift */,);path = Views;sourceTree = "<group>";@@ -759,6 +762,7 @@8D83C54A832018932F7261DE /* ComputersView.swift in Sources */,2244021EF712DF568374AB04 /* HostController.swift in Sources */,B4373612F918A3158E69A8E3 /* SSHTunnel.swift in Sources */,+ D51C32451FB38C337707E3A5 /* SettingsView.swift in Sources */,AF21AAA6549D150D18C8927F /* UpdatesManager.swift in Sources */,);runOnlyForDeploymentPostprocessing = 0;@@ -857,11 +861,14 @@CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;GENERATE_INFOPLIST_FILE = YES;INFOPLIST_FILE = macos/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = Codync;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Talk to your bots in a voice call.";+ INFOPLIST_KEY_NSSpeechRecognitionUsageDescription = "Your words are transcribed on this Mac and sent to your bot as a message.";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",@@ -1142,11 +1149,14 @@CURRENT_PROJECT_VERSION = "$(MARKETING_VERSION)";ENABLE_APP_SANDBOX = NO;ENABLE_HARDENED_RUNTIME = YES;+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;GENERATE_INFOPLIST_FILE = YES;INFOPLIST_FILE = macos/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = Codync;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";INFOPLIST_KEY_NSHumanReadableCopyright = "";+ INFOPLIST_KEY_NSMicrophoneUsageDescription = "Talk to your bots in a voice call.";+ INFOPLIST_KEY_NSSpeechRecognitionUsageDescription = "Your words are transcribed on this Mac and sent to your bot as a message.";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",diff --git a/apps/ios/Views/SettingsView.swift b/apps/ios/Views/SettingsView.swiftindex efc97794..41891e02 100644--- a/apps/ios/Views/SettingsView.swift+++ b/apps/ios/Views/SettingsView.swift@@ -20,6 +20,7 @@ struct SettingsView: View {@State private var access: AccessTarget?@State private var confirmStartOver = false@State private var confirmRemoveCopy: CloudComputer?+ @State private var voice: VoiceTarget?var body: some View {CardForm {@@ -55,6 +56,20 @@ struct SettingsView: View {.buttonStyle(.plain)}+ let online = accounts.computers.compactMap { accounts.store(for: $0.id) }.filter { $0.connection == .online }+ if !online.isEmpty {+ CardSection("Voice chat", footer: "Apple speech on this iPhone, or OpenAI and Gemini on your own API key, kept on the computer.") {+ ForEach(online, id: \.computer.id) { store in+ Button { voice = VoiceTarget(store: store) } label: {+ LinkRow {+ Label(online.count > 1 ? "Voice chat on \(store.hostName)" : "Voice and API keys", systemImage: "waveform")+ }+ }+ .buttonStyle(.plain)+ }+ }+ }+CardSection("Notifications", footer: "Get a result summary, a request for input, or a failure notice. Notification previews follow your iOS settings.") {Toggle("Push notifications", isOn: $notificationsEnabled).toggleStyle(.codync)@@ -114,6 +129,7 @@ struct SettingsView: View {.codyncSheet(isPresented: $addingComputer) {PairingView(inModal: true)}+ .codyncSheet(item: $voice) { target in VoiceChatSettingsView().environment(target.store) }.codyncSheet(item: $access) { target inAccessRequestView(computer: target.computer, pending: accounts.pendingAccess[target.id] != nil)}@@ -142,6 +158,16 @@ struct SettingsView: View {}+ private struct VoiceTarget: Identifiable {+ let store: BotStore+ let id: String++ @MainActor init(store: BotStore) {+ self.store = store+ id = store.computer.id+ }+ }+private struct AccessTarget: Identifiable {let computer: CloudComputervar id: ComputerID { computer.computerId }@@ -209,6 +235,7 @@ private struct ComputerRow: View {let remove: () -> Void@Environment(AccountStore.self) private var accounts@State private var coloring = false+ @State private var voiceSettings = falsevar body: some View {HStack(spacing: 12) {@@ -263,6 +290,7 @@ private struct ComputerRow: View {]if store.connection == .online {items.append(MenuItem("Marketplace", icon: "storefront", action: openMarketplace))+ items.append(MenuItem("Voice chat", icon: "waveform") { voiceSettings = true })}if store.screen != nil, store.connection == .online {items.append(MenuItem("Screen", icon: "display", action: openScreen))@@ -273,6 +301,7 @@ private struct ComputerRow: View {items.append(MenuItem("Remove", icon: "trash", destructive: true, divider: revoke == nil, action: remove))return items}+ .codyncSheet(isPresented: $voiceSettings) { VoiceChatSettingsView().environment(store) }.codyncOverlay(isPresented: $coloring) { close inZStack {Color.black.opacity(0.35).ignoresSafeArea().onTapGesture(perform: close)diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 43ab561c..9b21c462 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -10,7 +10,13 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o### zh-Hant- 新建立的 bot 預設會自動核准工具請求;想逐一確認的話,可以在 bot 設定裡改成「Ask me」。+- 多台電腦時,點電腦標題可以收合它的 bot;長按標題可以把整台電腦連同 bot 一起拖曳排序。+- 語音通話可以改用 OpenAI 或 Gemini 的即時語音:在通話的齒輪裡填入你自己的 API key 並挑選模型,就能直接插話、問 bot 現在在做什麼;key 加密存在你的電腦上,Mac 版也能語音通話。+- 設定畫面換上更乾淨的分組版面,每個選項都附上簡短說明。### en-US- New bots approve tool requests automatically. Switch a bot to "Ask me" in its settings to review each one.+- With several computers, tap a computer's heading to fold its bots away, or long-press it to drag the whole computer up or down.+- Voice calls can use OpenAI or Gemini realtime voice: add your own API key and pick a model in the call's settings to talk over replies and ask what the bot is doing. The key is stored encrypted on your computer, and the Mac app can make voice calls too.+- Settings get a cleaner grouped layout, with a short note under each option.diff --git a/apps/project.yml b/apps/project.ymlindex 35963c5a..54cedf9d 100644--- a/apps/project.yml+++ b/apps/project.yml@@ -80,7 +80,11 @@ targets:INFOPLIST_KEY_CFBundleDisplayName: CodyncINFOPLIST_KEY_LSApplicationCategoryType: public.app-category.developer-toolsINFOPLIST_KEY_NSHumanReadableCopyright: ""+ INFOPLIST_KEY_NSMicrophoneUsageDescription: Talk to your bots in a voice call.+ INFOPLIST_KEY_NSSpeechRecognitionUsageDescription: Your words are transcribed on this Mac and sent to your bot as a message.ENABLE_HARDENED_RUNTIME: YES+ # Voice calls: the hardened runtime blocks the microphone without this entitlement.+ ENABLE_RESOURCE_ACCESS_AUDIO_INPUT: YESENABLE_APP_SANDBOX: NOASSETCATALOG_COMPILER_APPICON_NAME: AppIcon# Black / white instead of the system blue wherever macOS draws the app's accent.diff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex db05c578..c145ffcf 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -1,11 +1,13 @@# Voice call-A hands-free call with one bot from the iPhone chat (the waveform button in an empty composer).+A hands-free call with one bot from the iPhone or Mac chat (the waveform button in an empty composer).+Linux and the terminal UI have no calls: neither has an audio stack (GTK app, TUI); they show the+"Voice chat · 00:16" notice like every client.The bot is the same agent on the computer; the call only changes how you talk to it.-## Implemented: on the phone+## On-device voice-- `kit/Sources/CodyncUI/Call/`: `CallSession` (audio loop) + `CallView` (the call bar).+- `kit/Sources/CodyncUI/Call/`: `CallView` (the call bar) over a `VoiceEngine`; `OnDeviceEngine` is the default audio loop.- UI follows Grok Bot: a floating capsule over the top of the chat (`ThreadView` overlay), and thechat stays readable and usable underneath. Left to right: the bot's avatar (pulses whilespeaking; tap it to interrupt), a dotted level line (your voice while listening, a ripple while@@ -17,7 +19,7 @@ The bot is the same agent on the computer; the call only changes how you talk to- Each new final reply (`data.final`) is read aloud with `AVSpeechSynthesizer` in the reply's ownlanguage; markdown and code blocks are dropped (`SpokenText`). The mic pauses while it speaks.An approval request is announced, answered in the chat.-- Gear: pause length before sending (1 / 1.5 / 2.5 s) and reading speed; kept on the phone.+- Gear: voice engine (below), and for On device the pause length before sending (1 / 1.5 / 2.5 s) and reading speed; kept on the phone.- Ending the call calls `logCall {botId, seconds}`; the host adds a notice (`callSeconds`) thatevery client shows as "Voice chat · 00:16".- The host receives recognized text; the Cloudflare transport sees encrypted channel frames.@@ -68,67 +70,101 @@ evidence Apple requested. A `simctl io ... recordVideo` probe on 2026-09-30produced an H.264 video track with no audio track. Transport regression testsverify background reply delivery and retirement, not iOS audio behavior.-## Design: realtime voice with your own key (not implemented)+## Realtime voice with your own keyBetter recognition (mixed Chinese/English, code terms) and a real conversation (barge-in, "what are-you doing?" answered from the transcript) need a realtime speech model. Users bring their own-provider key; Codync never resells minutes for it.+you doing?" answered from the transcript) need a realtime speech model. Codync is free, so users+bring their own provider key; Codync never pays for or resells minutes.### Engines-The gear's first section becomes **Voice engine**:--| Engine | Needs | Transport |-| --- | --- | --- |-| On device (default) | nothing | what ships today |-| OpenAI Realtime | OpenAI API key | WebRTC, phone ↔ OpenAI |-| Gemini Live | Google AI Studio key | WebSocket, phone ↔ Google |--Picking a cloud engine without a key opens its key form: a secure field, a link to the provider's-key page, **Test** (one cheap authenticated call; shows "Key works" or the provider's error), and a-voice picker. The call bar shows the provider's small wordmark-free label ("OpenAI") next to the-dots whenever audio leaves the phone.+The gear's first section is **Voice engine** (applies from the next call):++| Engine | Needs | Transport | Code |+| --- | --- | --- | --- |+| On device (default) | nothing | Apple speech, as above | `OnDeviceEngine` |+| OpenAI | OpenAI API key on the computer | WebRTC, device ↔ OpenAI (default `gpt-realtime-2.1`) | `OpenAIRealtimeEngine` |+| Gemini | Google AI Studio key on the computer | WebSocket, device ↔ Google (default `gemini-3.8-live`) | `GeminiLiveEngine` |++Each cloud engine has two **modes**:++- **Realtime**: a live conversation with the provider's realtime model (below), talk over replies.+- **Speech** (`CloudSpeechEngine`): the on-device loop with the provider's models instead of Apple's.+ The microphone is cut into utterances at a pause (energy VAD; under 0.4 s of voice is dropped as+ noise, and 0.4 s after playback is ignored as echo), each one goes to the provider's+ speech-to-text and is sent as an ordinary message; replies are read with its text-to-speech. Both+ run on the computer (`voiceTranscribe`, `voiceSpeak`), so the key never leaves it; utterances stop+ at 20 s and replies are spoken in clips (OpenAI 600 characters as AAC, Gemini 150 as WAV) so every+ request and answer fits one 1 MiB channel message. Defaults: `gpt-4o-transcribe` ++ `gpt-4o-mini-tts`, `gemini-3.8-flash` + `gemini-3.8-flash-tts`.++Voice settings (`VoiceChatSettingsView`) open from the call bar's gear and from settings: on the+iPhone, **Computers & settings → Voice chat**; on the Mac, **Account → Voice chat** (this Mac's+computer) or the waveform button on a computer's card in **Computers & devices**. Keys are entered+on the computer only: the host takes `setVoiceKey` from loopback, and the iPhone shows whether a key+is there and can test it. Picking a cloud engine shows its key form instead of the on-device settings: a secure field, a link+to the provider's key page, **Test** (the computer checks a new key with the provider and keeps it+only if it works, otherwise the provider's error is shown; with a key saved, it mints a call+credential for the chosen model and voice), a model picker, a voice picker, and minutes used this month.+Speech mode adds speech-to-text and text-to-speech pickers and the pause length. The model list comes from the provider through the computer (`voiceModels`: OpenAI `GET /v1/models`+ids sorted into realtime, transcribe and tts models; Gemini `GET v1beta/models` by+`bidiGenerateContent` / `generateContent` and name; translation and diarization models left out), fetched after a successful test and each time the form opens. The call bar+shows the provider's name next to the dots whenever audio leaves the device.### Where the key lives-- On the iPhone only, in the Keychain (`kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly`, not- synced). It is never sent to the host, the relay or our cloud, and never written to logs.-- The long-lived key is used for one thing: minting a short-lived client credential at call start- (OpenAI `POST /v1/realtime/client_secrets`, Gemini ephemeral auth tokens). The audio session only- ever sees that credential.-- Rejected: key on the host with audio proxied through it. Audio would cross the encrypted channel- and the relay (latency, relay bandwidth), and a Linux server host has no microphone reason to- hold it.+- On the computer, in the host's vault (`host/src/voice.rs`, slot `voice`: encrypted in+ `codync.db` with the vault key from Keychain / Secret Service), so one key serves the iPhone and the+ Mac. It reaches the host once, over the encrypted channel, and never leaves it again; it is never+ logged and never sent to the relay or our cloud.+- Host methods (control scope): `voiceStatus` (which providers have a key), `setVoiceKey+ {provider, key}` (checked with one credential mint before it's kept; empty removes it),+ `voiceSession {provider, model, voice}` → `{credential}`, `voiceModels {provider}` → `{models,+ transcribe, speech}`, `voiceTranscribe {provider, model, audio}` (base64 16 kHz WAV) → `{text}`,+ `voiceSpeak {provider, model, voice, text}` → `{audio, format}`.+- The long-lived key is used for minting a short-lived credential at call start (OpenAI+ `POST /v1/realtime/client_secrets`, 10 minutes; Gemini `POST v1alpha/auth_tokens`, one use) and+ listing models. The client's audio session only ever sees that credential.+- Audio is not proxied through the host: it would cross the encrypted channel and the relay+ (latency, relay bandwidth). The device streams to the provider directly.### How the call works-The realtime model is an operator in front of the bot, not a replacement for it:+The realtime model is an operator in front of the bot, not a replacement for it (`CallOperator`):- Session instructions: who the bot is (name, description), that coding is done by the bot, replyin the user's language, keep spoken answers short.-- Tools the phone implements locally against `BotStore`: `send_to_bot(text)` (an ordinary message,- same path as today), `bot_status()` (idle/working, activity line, pending approval),+- Tools the client implements against `BotStore`: `send_to_bot(text)` (an ordinary message, same path+ as on-device calls), `bot_status()` (status, activity line, pending approval and its options),`recent_messages(count)` (chat-visible entries only), `answer_approval(option)` (only after the- user said which).-- Each new final reply is pushed into the realtime conversation as a context item; the model speaks- it (shortened for speech). Barge-in is the provider's own voice activity detection.+ user said which; matched by option name).+- Each new final reply is added to the realtime conversation as `[<bot> replied] …` and an approval+ as `[Notice] …` (`BotStore` hands them over as `speak` / `announce`); the model says them,+ shortened for speech. They wait while the model is talking, so they don't cut it off.+- Barge-in is the provider's voice activity detection (OpenAI semantic VAD; Gemini's automatic+ VAD, with the voice-processing input cancelling the device's own playback). Tapping the avatar+ cancels the response locally.+- Gemini connections are replaced before the server's limit: `goAway` closes the socket and the+ session resumes on a fresh token with its resumption handle; context window compression lifts the+ 15-minute audio session cap.- The chat stays the record: only `send_to_bot` messages and the bot's replies are entries. Theoperator's small talk isn't saved; the call still ends with the "Voice chat" notice.### Failure and cost-- Invalid key, quota or network failure at start → the call falls back to On device with a one-line- notice under the bar; mid-call failure does the same without dropping the call.-- Usage is billed by the provider to the user. The gear shows minutes used this month (counted on- the phone) next to the engine, as an estimate, not a bill.--### Code layout--- `kit/Sources/CodyncUI/Call/VoiceEngine.swift`: `protocol VoiceEngine` (start, end, mute,- interrupt, `phase`, `level`, `onUserMessage`, `speak(reply:)`); `OnDeviceEngine` is today's- `CallSession`; `OpenAIRealtimeEngine` (WebRTC, the app already links WebRTC for Remote screen)- and `GeminiLiveEngine` (URLSessionWebSocketTask).-- `kit/Sources/CodyncKit/Client/VoiceKeys.swift`: Keychain storage + credential minting.-- `CallView` only talks to `VoiceEngine`; nothing on the host changes.-- A later Codync Pro plan can add a second credential source (our server mints the client token after- checking the entitlement) behind the same engines.+- No key on the computer, invalid key, quota or network failure at start, or a dropped connection mid-call: the+ call switches to On device without hanging up, with a one-line notice under the bar.+- Usage is billed by the provider to the user. The key form shows minutes used this month+ (`VoiceUsage`, counted on each device while a cloud engine is live) as an estimate, not a bill.++### Verification++On 2026-10-04 the OpenAI path was checked with a real key from a Mac (aiortc driving the same+client secret → `/v1/realtime/calls` SDP → `oai-events` sequence): session update with the four tools,+a spoken reply, and `send_to_bot` called for a Chinese request. The iOS Simulator's voice-processing+audio unit can abort with an RPC timeout when WebRTC starts its audio; use a physical iPhone for audio.++`StoreTests` cover the operator's tools against a scripted host (send, status with an approval,+option matching, recent messages) and approvals reaching a call as notices. Provider audio isn't+simulated: on a physical iPhone, check both engines with a real key (talk over a reply, ask "what+are you doing?", approve by voice, and turn off Wi-Fi mid-call to see the fallback).diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex d98d0ea7..aecf61ca 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -35,6 +35,8 @@ const LOCAL_ONLY: &[&str] = &["installHostUpdate","setHostAutomaticUpdates","setScreenEnabled",+ // Voice keys are entered on the computer itself; phones only use them.+ "setVoiceKey","pairing","computerCall","teamCall",diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 03a480d7..70bb2b6d 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -249,6 +249,8 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -|| method == "setComposioKey"|| method.starts_with("credential")|| method == "computerCall"+ || method.starts_with("voice")+ || method == "setVoiceKey"|| matches!(method, "agentAuth" | "agentAuthenticate" | "setAgentEnv"){market::vault::unlock(hub.clone()).await?;@@ -333,6 +335,33 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -"composioCall" => {json!({"result": market::composio::call(&hub.store, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?})}+ "voiceStatus" => crate::voice::status(&hub.store)?,+ "setVoiceKey" => {+ let provider = crate::voice::Provider::parse(str_arg(&b, "provider")?)?;+ crate::voice::set_key(&hub.store, provider, b["key"].as_str().unwrap_or_default()).await?+ }+ "voiceSession" => {+ let provider = crate::voice::Provider::parse(str_arg(&b, "provider")?)?;+ crate::voice::session(&hub.store, provider, str_arg(&b, "model")?, str_arg(&b, "voice")?).await?+ }+ "voiceModels" => {+ crate::voice::models(&hub.store, crate::voice::Provider::parse(str_arg(&b, "provider")?)?).await?+ }+ "voiceTranscribe" => {+ let provider = crate::voice::Provider::parse(str_arg(&b, "provider")?)?;+ crate::voice::transcribe(&hub.store, provider, str_arg(&b, "model")?, str_arg(&b, "audio")?).await?+ }+ "voiceSpeak" => {+ let provider = crate::voice::Provider::parse(str_arg(&b, "provider")?)?;+ crate::voice::speak(+ &hub.store,+ provider,+ str_arg(&b, "model")?,+ str_arg(&b, "voice")?,+ str_arg(&b, "text")?,+ )+ .await?+ }"composioStatus" => market::composio::status(&hub.store)?,"setComposioKey" => market::composio::set_key(&hub.store, b["key"].as_str().unwrap_or_default()).await?,"composioToolkits" => {diff --git a/host/src/main.rs b/host/src/main.rsindex b7ae7236..4a3dd118 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -15,6 +15,7 @@ mod store;mod tui;mod update;mod usage;+mod voice;use agent::{backends, registry};use remote::{identity, relay};diff --git a/host/src/voice.rs b/host/src/voice.rsnew file mode 100644index 00000000..3b9ba836--- /dev/null+++ b/host/src/voice.rs@@ -0,0 +1,454 @@+//! Realtime voice for calls on the user's own provider keys (`OpenAI` Realtime,+//! Gemini Live). The keys stay in this computer's vault; a client starting a+//! call gets a short-lived credential minted here and then streams audio to the+//! provider directly, so audio never crosses the channel or the relay.++use crate::market::vault;+use crate::store::Store;+use anyhow::{Result, anyhow, bail};+use base64::{Engine, engine::general_purpose::STANDARD};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::time::Duration;++const SLOT: &str = "voice";+const TIMEOUT: Duration = Duration::from_secs(15);+/// Speech to text: keep the speaker's language and script, and coding terms as written.+const TRANSCRIBE_HINT: &str = "Keep the speaker's language and script (Traditional Chinese stays Traditional Chinese, 繁體中文). Keep code, file and product names as written.";++#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub enum Provider {+ #[serde(rename = "openai")]+ OpenAi,+ #[serde(rename = "gemini")]+ Gemini,+}++impl Provider {+ const ALL: [Self; 2] = [Self::OpenAi, Self::Gemini];++ pub fn parse(s: &str) -> Result<Self> {+ match s {+ "openai" => Ok(Self::OpenAi),+ "gemini" => Ok(Self::Gemini),+ _ => bail!("unknown voice provider `{s}`"),+ }+ }++ fn id(self) -> &'static str {+ match self {+ Self::OpenAi => "openai",+ Self::Gemini => "gemini",+ }+ }++ fn name(self) -> &'static str {+ match self {+ Self::OpenAi => "OpenAI",+ Self::Gemini => "Gemini",+ }+ }++ /// Used until the user picks one from the provider's list.+ fn default_model(self) -> &'static str {+ match self {+ Self::OpenAi => "gpt-realtime-2.1",+ Self::Gemini => "gemini-3.8-live",+ }+ }+}++#[derive(Default, Serialize, Deserialize)]+struct Keys {+ #[serde(default)]+ openai: String,+ #[serde(default)]+ gemini: String,+}++impl Keys {+ fn get(&self, p: Provider) -> &str {+ match p {+ Provider::OpenAi => &self.openai,+ Provider::Gemini => &self.gemini,+ }+ }++ fn set(&mut self, p: Provider, key: String) {+ match p {+ Provider::OpenAi => self.openai = key,+ Provider::Gemini => self.gemini = key,+ }+ }+}++fn load(store: &Store) -> Result<Keys> {+ Ok(vault::read(store, SLOT)?+ .filter(|s| !s.is_empty())+ .map(|s| serde_json::from_str(&s))+ .transpose()?+ .unwrap_or_default())+}++fn key(store: &Store, p: Provider) -> Result<String> {+ let keys = load(store)?;+ let key = keys.get(p);+ if key.is_empty() {+ bail!("No {} key on this computer. Add one in the call settings.", p.name());+ }+ Ok(key.to_owned())+}++/// Model ids and voices go into provider requests: letters, digits, `-`, `.`, `_`.+fn checked(s: &str) -> Result<&str> {+ let ok = !s.is_empty() && s.len() <= 100 && s.chars().all(|c| c.is_ascii_alphanumeric() || "-._".contains(c));+ if ok { Ok(s) } else { bail!("`{s}` isn't a model or voice name") }+}++async fn send(p: Provider, req: reqwest::RequestBuilder) -> Result<Value> {+ let res = req.timeout(TIMEOUT).send().await.map_err(|_| anyhow!("Can't reach {}.", p.name()))?;+ let status = res.status();+ let v: Value = serde_json::from_str(&res.text().await.unwrap_or_default()).unwrap_or(Value::Null);+ if !status.is_success() {+ // The provider's own message ("Incorrect API key provided…") says what to fix.+ let message =+ v["error"]["message"].as_str().map_or_else(|| format!("{} answered {status}.", p.name()), str::to_owned);+ bail!(message);+ }+ Ok(v)+}++/// A credential for one call's audio session: an `OpenAI` client secret (10 minutes)+/// or a one-use Gemini ephemeral token.+async fn mint(p: Provider, key: &str, model: &str, voice: &str) -> Result<String> {+ let v = match p {+ Provider::OpenAi => {+ let body = json!({+ "expires_after": {"anchor": "created_at", "seconds": 600},+ "session": {"type": "realtime", "model": model, "audio": {"output": {"voice": voice}}},+ });+ send(+ p,+ crate::http().post("https://api.openai.com/v1/realtime/client_secrets").bearer_auth(key).json(&body),+ )+ .await?+ }+ Provider::Gemini => {+ let now = chrono::Utc::now();+ let body = json!({+ "uses": 1,+ "expireTime": (now + chrono::Duration::minutes(30)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),+ "newSessionExpireTime": (now + chrono::Duration::minutes(1)).to_rfc3339_opts(chrono::SecondsFormat::Secs, true),+ });+ send(+ p,+ crate::http()+ .post("https://generativelanguage.googleapis.com/v1alpha/auth_tokens")+ .header("x-goog-api-key", key)+ .json(&body),+ )+ .await?+ }+ };+ let field = match p {+ Provider::OpenAi => "value",+ Provider::Gemini => "name",+ };+ v[field]+ .as_str()+ .filter(|s| !s.is_empty())+ .map(str::to_owned)+ .ok_or_else(|| anyhow!("{} sent no session credential.", p.name()))+}++/// Which providers have a key here, with their default models.+pub fn status(store: &Store) -> Result<Value> {+ let keys = load(store)?;+ let providers: Vec<Value> = Provider::ALL+ .iter()+ .map(|&p| json!({"provider": p.id(), "configured": !keys.get(p).is_empty(), "defaultModel": p.default_model()}))+ .collect();+ Ok(json!({"providers": providers}))+}++/// Checks the key with the provider (one credential mint), then keeps it. An empty key removes it.+pub async fn set_key(store: &Store, p: Provider, key: &str) -> Result<Value> {+ let key = key.trim();+ if !key.is_empty() {+ let voice = match p {+ Provider::OpenAi => "marin",+ Provider::Gemini => "Kore",+ };+ mint(p, key, p.default_model(), voice).await?;+ }+ {+ let _guard = store.connector_lock.lock().map_err(|_| anyhow!("credential storage is busy"))?;+ let mut keys = load(store)?;+ keys.set(p, key.to_owned());+ vault::write(store, SLOT, &serde_json::to_string(&keys)?)?;+ }+ status(store)+}++/// A credential for a call starting now.+pub async fn session(store: &Store, p: Provider, model: &str, voice: &str) -> Result<Value> {+ let key = key(store, p)?;+ Ok(json!({"credential": mint(p, &key, checked(model)?, checked(voice)?).await?}))+}++/// Models the key can use, from the provider's own list: realtime (conversation),+/// transcribe (speech to text) and speech (text to speech).+pub async fn models(store: &Store, p: Provider) -> Result<Value> {+ let key = key(store, p)?;+ let entries: Vec<Model> = match p {+ Provider::OpenAi => {+ let v = send(p, crate::http().get("https://api.openai.com/v1/models").bearer_auth(&key)).await?;+ v["data"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| m["id"].as_str())+ .map(|id| Model { id: id.to_owned(), live: id.contains("realtime"), generate: true })+ .collect()+ }+ Provider::Gemini => {+ let req = crate::http()+ .get("https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000")+ .header("x-goog-api-key", &key);+ let v = send(p, req).await?;+ v["models"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| {+ let methods = m["supportedGenerationMethods"].as_array()?;+ Some(Model {+ id: m["name"].as_str()?.trim_start_matches("models/").to_owned(),+ live: methods.iter().any(|x| x == "bidiGenerateContent"),+ generate: methods.iter().any(|x| x == "generateContent"),+ })+ })+ .collect()+ }+ };+ let (realtime, transcribe, speech) = classify(p, &entries);+ Ok(json!({"models": realtime, "transcribe": transcribe, "speech": speech}))+}++struct Model {+ id: String,+ /// Holds a live conversation (`OpenAI` `realtime`, Gemini `bidiGenerateContent`).+ live: bool,+ generate: bool,+}++/// Sorts a provider's model list into what each voice mode can use. Translation,+/// diarization and live-transcription models can't serve either mode.+fn classify(p: Provider, models: &[Model]) -> (Vec<String>, Vec<String>, Vec<String>) {+ let has = |id: &str, words: &[&str]| words.iter().any(|w| id.contains(w));+ let pick = |f: &dyn Fn(&Model) -> bool| {+ let mut ids: Vec<String> = models.iter().filter(|m| f(m)).map(|m| m.id.clone()).collect();+ ids.sort();+ ids.dedup();+ ids+ };+ let realtime = pick(&|m| m.live && !has(&m.id, &["translate", "whisper", "transcribe", "tts"]));+ let (transcribe, speech) = match p {+ Provider::OpenAi => (+ pick(&|m| {+ (m.id.contains("transcribe") || m.id == "whisper-1") && !has(&m.id, &["diarize", "live", "realtime"])+ }),+ pick(&|m| m.id.contains("tts")),+ ),+ Provider::Gemini => (+ pick(&|m| {+ m.generate+ && m.id.starts_with("gemini")+ && m.id.contains("flash")+ && !has(&m.id, &["tts", "live", "image", "embedding", "native-audio", "translate"])+ }),+ pick(&|m| m.generate && m.id.contains("tts")),+ ),+ };+ (realtime, transcribe, speech)+}++/// Speech to text for one utterance (`audio`: base64 WAV, 16 kHz mono).+pub async fn transcribe(store: &Store, p: Provider, model: &str, audio: &str) -> Result<Value> {+ let key = key(store, p)?;+ let model = checked(model)?;+ let wav = STANDARD.decode(audio).map_err(|_| anyhow!("audio must be base64"))?;+ let text = match p {+ Provider::OpenAi => {+ let boundary = format!("codync-{}", uuid::Uuid::new_v4().simple());+ let mut body = Vec::with_capacity(wav.len() + 512);+ body.extend_from_slice(+ format!("--{boundary}\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\n{model}\r\n").as_bytes(),+ );+ // Keeps Traditional Chinese from coming back Simplified, and code terms intact.+ body.extend_from_slice(+ format!("--{boundary}\r\nContent-Disposition: form-data; name=\"prompt\"\r\n\r\n{TRANSCRIBE_HINT}\r\n")+ .as_bytes(),+ );+ body.extend_from_slice(+ format!(+ "--{boundary}\r\nContent-Disposition: form-data; name=\"file\"; filename=\"speech.wav\"\r\nContent-Type: audio/wav\r\n\r\n"+ )+ .as_bytes(),+ );+ body.extend_from_slice(&wav);+ body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());+ let req = crate::http()+ .post("https://api.openai.com/v1/audio/transcriptions")+ .bearer_auth(&key)+ .header("Content-Type", format!("multipart/form-data; boundary={boundary}"))+ .body(body);+ send(p, req).await?["text"].as_str().unwrap_or_default().to_owned()+ }+ Provider::Gemini => {+ let body = json!({"contents": [{"parts": [+ {"text": format!("Transcribe this audio exactly as spoken. {TRANSCRIBE_HINT} Reply with the transcript only; reply with nothing if there is no speech.")},+ {"inlineData": {"mimeType": "audio/wav", "data": audio}},+ ]}]});+ let v = send(p, gemini_generate(&key, model).json(&body)).await?;+ v["candidates"][0]["content"]["parts"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|part| part["text"].as_str())+ .collect::<String>()+ }+ };+ Ok(json!({"text": text.trim()}))+}++/// Text to speech for one stretch of a reply: `{audio: base64, format: "aac" | "wav"}`.+pub async fn speak(store: &Store, p: Provider, model: &str, voice: &str, text: &str) -> Result<Value> {+ let key = key(store, p)?;+ let (model, voice) = (checked(model)?, checked(voice)?);+ if text.trim().is_empty() || text.len() > 4000 {+ bail!("text must be 1–4000 bytes");+ }+ match p {+ Provider::OpenAi => {+ let body = json!({"model": model, "voice": voice, "input": text, "response_format": "aac"});+ let res = crate::http()+ .post("https://api.openai.com/v1/audio/speech")+ .bearer_auth(&key)+ .json(&body)+ .timeout(TIMEOUT * 4)+ .send()+ .await+ .map_err(|_| anyhow!("Can't reach {}.", p.name()))?;+ let status = res.status();+ let bytes = res.bytes().await.map_err(|_| anyhow!("{} sent no audio.", p.name()))?;+ if !status.is_success() {+ let v: Value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);+ bail!(+ v["error"]["message"]+ .as_str()+ .map_or_else(|| format!("{} answered {status}.", p.name()), str::to_owned)+ );+ }+ Ok(json!({"audio": STANDARD.encode(&bytes), "format": "aac"}))+ }+ Provider::Gemini => {+ let body = json!({+ "contents": [{"parts": [{"text": text}]}],+ "generationConfig": {+ "responseModalities": ["AUDIO"],+ "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice}}},+ },+ });+ let v = send(p, gemini_generate(&key, model).json(&body)).await?;+ let pcm = v["candidates"][0]["content"]["parts"]+ .as_array()+ .into_iter()+ .flatten()+ .find_map(|part| part["inlineData"]["data"].as_str())+ .ok_or_else(|| anyhow!("{} sent no audio.", p.name()))?;+ let pcm = STANDARD.decode(pcm).map_err(|_| anyhow!("{} sent unreadable audio.", p.name()))?;+ Ok(json!({"audio": STANDARD.encode(wav(&pcm, 24_000)), "format": "wav"}))+ }+ }+}++fn gemini_generate(key: &str, model: &str) -> reqwest::RequestBuilder {+ crate::http()+ .post(format!("https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"))+ .header("x-goog-api-key", key)+ .timeout(TIMEOUT * 4)+}++/// 16-bit mono PCM wrapped in a WAV header (Gemini speech is raw PCM).+fn wav(pcm: &[u8], rate: u32) -> Vec<u8> {+ let len = u32::try_from(pcm.len()).unwrap_or(u32::MAX);+ let mut out = Vec::with_capacity(pcm.len() + 44);+ out.extend_from_slice(b"RIFF");+ out.extend_from_slice(&(36 + len).to_le_bytes());+ out.extend_from_slice(b"WAVEfmt ");+ out.extend_from_slice(&16u32.to_le_bytes());+ out.extend_from_slice(&1u16.to_le_bytes()); // PCM+ out.extend_from_slice(&1u16.to_le_bytes()); // mono+ out.extend_from_slice(&rate.to_le_bytes());+ out.extend_from_slice(&(rate * 2).to_le_bytes());+ out.extend_from_slice(&2u16.to_le_bytes());+ out.extend_from_slice(&16u16.to_le_bytes());+ out.extend_from_slice(b"data");+ out.extend_from_slice(&len.to_le_bytes());+ out.extend_from_slice(pcm);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ids(p: Provider, ids: &[&str]) -> (Vec<String>, Vec<String>, Vec<String>) {+ let models: Vec<Model> = ids+ .iter()+ .map(|id| Model { id: (*id).to_owned(), live: id.contains("realtime"), generate: true })+ .collect();+ classify(p, &models)+ }++ #[test]+ fn openai_models_sort_by_mode() {+ let (realtime, transcribe, speech) = ids(+ Provider::OpenAi,+ &[+ "gpt-realtime-2.1",+ "gpt-realtime-translate",+ "gpt-realtime-whisper",+ "gpt-realtime",+ "gpt-4o-transcribe",+ "gpt-4o-transcribe-diarize",+ "gpt-live-transcribe",+ "whisper-1",+ "gpt-4o-mini-tts",+ "gpt-5",+ ],+ );+ assert_eq!(realtime, ["gpt-realtime", "gpt-realtime-2.1"]);+ assert_eq!(transcribe, ["gpt-4o-transcribe", "whisper-1"]);+ assert_eq!(speech, ["gpt-4o-mini-tts"]);+ }++ #[test]+ fn wav_header_matches_pcm() {+ let out = wav(&[0, 0, 1, 0], 24_000);+ assert_eq!(out.len(), 48);+ assert_eq!(&out[..4], b"RIFF");+ assert_eq!(u32::from_le_bytes([out[40], out[41], out[42], out[43]]), 4);+ }++ #[test]+ fn names_are_checked() {+ assert!(checked("gpt-realtime-2.1").is_ok());+ assert!(checked("Kore").is_ok());+ assert!(checked("x\"}").is_err());+ assert!(checked("").is_err());+ assert!(Provider::parse("openai").is_ok());+ assert!(Provider::parse("anthropic").is_err());+ }+}diff --git a/kit/Package.swift b/kit/Package.swiftindex 5b2d99d3..aabbdb66 100644--- a/kit/Package.swift+++ b/kit/Package.swift@@ -9,7 +9,7 @@ let package = Package(.library(name: "CodyncUI", targets: ["CodyncUI"]),],dependencies: [- // libwebrtc for the remote screen viewer (hardware H.264 over WebRTC).+ // libwebrtc for the remote screen viewer (hardware H.264 over WebRTC) and realtime voice calls..package(url: "https://github.com/stasel/WebRTC.git", exact: "153.0.0"),// Terminal emulator for agent install and sign-in. 1.19+ adds a build-tool// plugin every Xcode build would have to trust.@@ -21,7 +21,7 @@ let package = Package(name: "CodyncUI",dependencies: ["CodyncKit",- .product(name: "WebRTC", package: "WebRTC", condition: .when(platforms: [.iOS])),+ .product(name: "WebRTC", package: "WebRTC"),.product(name: "SwiftTerm", package: "SwiftTerm"),],resources: [.process("Resources")]diff --git a/kit/Sources/CodyncKit/Models/Voice.swift b/kit/Sources/CodyncKit/Models/Voice.swiftnew file mode 100644index 00000000..d8b064c8--- /dev/null+++ b/kit/Sources/CodyncKit/Models/Voice.swift@@ -0,0 +1,150 @@+import Foundation++// Realtime voice on the user's own provider keys (host/src/voice.rs). The keys stay on the+// computer; a call asks the host for a short-lived credential and streams audio to the provider.++public enum VoiceProvider: String, CaseIterable, Codable, Sendable {+ case openAI = "openai"+ case gemini++ public var name: String {+ switch self {+ case .openAI: "OpenAI"+ case .gemini: "Gemini"+ }+ }++ public var keyPage: URL {+ switch self {+ case .openAI: URL(string: "https://platform.openai.com/api-keys")!+ case .gemini: URL(string: "https://aistudio.google.com/apikey")!+ }+ }++ public var keyPrompt: String {+ switch self {+ case .openAI: "sk-…"+ case .gemini: "AIza…"+ }+ }++ /// Used until the user picks one from the provider's list (the host knows the same default).+ public var model: String {+ switch self {+ case .openAI: "gpt-realtime-2.1"+ case .gemini: "gemini-3.8-live"+ }+ }++ /// Speech-to-text and text-to-speech defaults for the non-realtime mode.+ public var transcribeModel: String {+ switch self {+ case .openAI: "gpt-4o-transcribe"+ case .gemini: "gemini-3.8-flash"+ }+ }++ public var speechModel: String {+ switch self {+ case .openAI: "gpt-4o-mini-tts"+ case .gemini: "gemini-3.8-flash-tts"+ }+ }++ /// Longest stretch of a reply turned into audio at once: each clip has to fit one channel+ /// message (1 MiB). Gemini returns uncompressed PCM, OpenAI AAC.+ public var speechChunk: Int {+ switch self {+ case .openAI: 600+ case .gemini: 150+ }+ }++ public var voices: [String] {+ switch self {+ case .openAI: ["marin", "cedar", "alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse"]+ case .gemini: ["Kore", "Puck", "Charon", "Fenrir", "Aoede", "Leda", "Orus", "Zephyr"]+ }+ }+}++public struct VoiceStatus: Decodable, Sendable {+ public struct Provider: Decodable, Sendable {+ public var provider: VoiceProvider+ public var configured: Bool+ }++ public var providers: [Provider]++ public func configured(_ provider: VoiceProvider) -> Bool {+ providers.first { $0.provider == provider }?.configured == true+ }+}++public struct VoiceModels: Codable, Sendable {+ /// Realtime conversation models.+ public var models: [String]+ public var transcribe: [String]+ public var speech: [String]++ public init(models: [String], transcribe: [String], speech: [String]) {+ self.models = models+ self.transcribe = transcribe+ self.speech = speech+ }+}++public extension HostClient {+ func voiceStatus() async throws -> VoiceStatus { try await call("voiceStatus") }++ /// Checks the key with the provider before the computer keeps it; an empty key removes it.+ func setVoiceKey(_ key: String, for provider: VoiceProvider) async throws -> VoiceStatus {+ try await call("setVoiceKey", ["provider": provider.rawValue, "key": key], timeout: 30)+ }++ /// A short-lived credential for one call's audio session.+ func voiceSession(_ provider: VoiceProvider, model: String, voice: String) async throws -> String {+ struct Session: Decodable { var credential: String }+ let s: Session = try await call("voiceSession", ["provider": provider.rawValue, "model": model, "voice": voice], timeout: 30)+ return s.credential+ }++ /// The models the computer's key can use, per voice mode.+ func voiceModels(_ provider: VoiceProvider) async throws -> VoiceModels {+ try await call("voiceModels", ["provider": provider.rawValue], timeout: 30)+ }++ /// Speech to text for one utterance (a WAV file), with the computer's key.+ func voiceTranscribe(_ provider: VoiceProvider, model: String, wav: Data) async throws -> String {+ struct Text: Decodable { var text: String }+ let t: Text = try await call("voiceTranscribe", ["provider": provider.rawValue, "model": model,+ "audio": wav.base64EncodedString()], timeout: 60)+ return t.text+ }++ /// Text to speech for a stretch of a reply: audio data and its format (`aac` or `wav`).+ func voiceSpeak(_ provider: VoiceProvider, model: String, voice: String, text: String) async throws -> (Data, String) {+ struct Clip: Decodable { var audio: String; var format: String }+ let c: Clip = try await call("voiceSpeak", ["provider": provider.rawValue, "model": model, "voice": voice,+ "text": text], timeout: 90)+ guard let data = Data(base64Encoded: c.audio) else { throw HostError.http(0, "Unreadable audio.") }+ return (data, c.format)+ }+}++/// Minutes of realtime voice used this month, counted on this device: an estimate, not a bill.+public enum VoiceUsage {+ private static func key(_ provider: VoiceProvider, _ date: Date) -> String {+ "callUsage.\(provider.rawValue).\(date.formatted(.iso8601.year().month()))"+ }++ public static func add(seconds: Int, for provider: VoiceProvider, at date: Date = .now) {+ guard seconds > 0 else { return }+ let k = key(provider, date)+ UserDefaults.standard.set(UserDefaults.standard.integer(forKey: k) + seconds, forKey: k)+ }++ public static func minutes(for provider: VoiceProvider, at date: Date = .now) -> Int {+ (UserDefaults.standard.integer(forKey: key(provider, date)) + 59) / 60+ }+}diff --git a/kit/Sources/CodyncUI/Call/CallOperator.swift b/kit/Sources/CodyncUI/Call/CallOperator.swiftnew file mode 100644index 00000000..14874991--- /dev/null+++ b/kit/Sources/CodyncUI/Call/CallOperator.swift@@ -0,0 +1,111 @@+import CodyncKit+import Foundation++/// A realtime model is an operator in front of the bot, not a replacement for it: the bot does the+/// work, the operator talks. Its tools run here against `BotStore`; only `send_to_bot` messages and+/// the bot's replies become chat entries.+@MainActor+struct CallOperator {+ let model: BotStore+ let botId: String++ var instructions: String {+ let bot = model.bots[botId]+ let name = bot?.name ?? "the bot"+ let about = bot.map { $0.description.isEmpty ? "" : " (\($0.description))" } ?? ""+ return """+ You are the voice on a phone call between the user and \(name)\(about), a coding agent \+ running on the user's computer. \(name) does all the actual work; you relay.+ - When the user asks for something to be done, changed, checked or answered about their \+ code or computer, call send_to_bot with their request in their own words (keep details, \+ names and code terms exactly). Don't do the work or invent results yourself.+ - Use bot_status and recent_messages for "what are you doing?" or "what did it say?".+ - Call answer_approval only after the user has clearly said which option to pick.+ - Messages starting with [\(name) replied] or [Notice] come from the computer: tell the \+ user what they say, shortened for speech (no code blocks, no long lists, no URLs).+ - Reply in the user's language. Keep spoken answers short and natural.+ """+ }++ /// Function declarations in JSON Schema form (both providers take the same shape).+ static let tools: [(name: String, description: String, parameters: [String: any Sendable])] = [+ ("send_to_bot", "Send a message to the bot on the computer, exactly as if the user typed it. Its reply arrives later.",+ ["type": "object", "properties": ["text": ["type": "string", "description": "The message"]], "required": ["text"]]),+ ("bot_status", "Whether the bot is idle or working, what it is doing, and any approval it is waiting for.",+ ["type": "object", "properties": [String: any Sendable]()]),+ ("recent_messages", "The latest messages in the chat with the bot, oldest first.",+ ["type": "object", "properties": ["count": ["type": "integer", "description": "How many, 1–20"]]]),+ ("answer_approval", "Answer the bot's pending approval request with one of its options.",+ ["type": "object", "properties": ["option": ["type": "string", "description": "The option's name"]], "required": ["option"]]),+ ]++ /// Runs one tool call; the result is a JSON string.+ func call(_ name: String, arguments: [String: Any]) -> String {+ let result: [String: Any] = switch name {+ case "send_to_bot": send(arguments["text"] as? String ?? "")+ case "bot_status": status()+ case "recent_messages": recent(arguments["count"] as? Int ?? 6)+ case "answer_approval": answer(arguments["option"] as? String ?? "")+ default: ["error": "Unknown tool \(name)."]+ }+ let data = (try? JSONSerialization.data(withJSONObject: result)) ?? Data("{}".utf8)+ return String(decoding: data, as: UTF8.self)+ }++ /// How a reply is handed to the operator.+ func reply(_ text: String) -> String {+ "[\(model.bots[botId]?.name ?? "Bot") replied] \(SpokenText.from(text))"+ }++ func notice(_ text: String) -> String { "[Notice] \(text)" }++ private func send(_ text: String) -> [String: Any] {+ let text = text.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !text.isEmpty else { return ["error": "Nothing to send."] }+ model.send(text, to: botId)+ return ["sent": true, "note": "The bot's reply will arrive as a separate message."]+ }++ private func status() -> [String: Any] {+ guard let bot = model.bots[botId] else { return ["error": "The bot isn't available."] }+ var out: [String: Any] = ["status": bot.status, "activity": bot.activity]+ if let card = pendingApproval {+ out["approval"] = [+ "request": card.data.title ?? card.data.command ?? "",+ "options": (card.data.options ?? []).map(\.name),+ ]+ }+ return out+ }++ private func recent(_ count: Int) -> [String: Any] {+ let name = model.bots[botId]?.name ?? "bot"+ let messages = model.chat(botId).filter(\.isChat).suffix(min(max(count, 1), 20)).map { e -> [String: String] in+ let from = switch e.kind {+ case "user": "user"+ case "agent": name+ case "permission": "approval request"+ default: "notice"+ }+ return ["from": from, "text": SpokenText.from(e.data.text ?? e.data.title ?? "")]+ }+ return ["messages": Array(messages)]+ }++ private func answer(_ option: String) -> [String: Any] {+ guard let card = pendingApproval else { return ["error": "Nothing is waiting for approval."] }+ let options = card.data.options ?? []+ let wanted = option.lowercased()+ guard let pick = options.first(where: { $0.name.lowercased() == wanted || $0.optionId == option })+ ?? options.first(where: { $0.name.lowercased().contains(wanted) || wanted.contains($0.name.lowercased()) })+ else {+ return ["error": "No such option.", "options": options.map(\.name)]+ }+ model.respond(card, option: pick.optionId)+ return ["answered": pick.name]+ }++ private var pendingApproval: Entry? {+ model.chat(botId).last { $0.kind == "permission" && $0.data.status == "pending" }+ }+}diff --git a/kit/Sources/CodyncUI/Call/CallView.swift b/kit/Sources/CodyncUI/Call/CallView.swiftindex 5616f807..191dcb1e 100644--- a/kit/Sources/CodyncUI/Call/CallView.swift+++ b/kit/Sources/CodyncUI/Call/CallView.swift@@ -1,4 +1,3 @@-#if os(iOS)import AVFoundationimport CodyncKitimport SwiftUI@@ -13,9 +12,13 @@ struct CallView: View {let close: () -> Void@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion- @State private var session: CallSession?+ @State private var session: (any VoiceEngine)?@State private var callID = UUID()@State private var startedAt = Date.now+ /// When the current cloud engine started, for this month's minutes.+ @State private var cloudStartedAt: Date?+ /// One line under the bar, e.g. why the call fell back to on-device voice.+ @State private var notice: String?@State private var settings = falseprivate var bot: Bot? { model.bots[botId] }@@ -25,35 +28,21 @@ struct CallView: View {VStack(spacing: 6) {barif case .failed(let message) = session?.phase {- Text(message)- .font(.footnote)- .foregroundStyle(Palette.danger)- .multilineTextAlignment(.center)- .padding(.horizontal, 12)- .padding(.vertical, 8)- .glass(in: Capsule())- .transition(.opacity)+ line(message, color: Palette.danger)+ } else if let notice {+ line(notice, color: Palette.secondary)}}.padding(.horizontal, 12).animation(Motion.reduced(Motion.fade, reduceMotion), value: session?.phase)+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: notice).onAppear {- let session = CallSession { [model, botId] in model.send($0, to: botId) }- session.onActivityChanged = { [weak session, model, botId, callID] active in- if active {- model.beginVoiceCall(callID, botId: botId,- speak: { [weak session] in session?.speak($0) },- end: { [weak session] in session?.end() })- } else {- model.endVoiceCall(callID)- }- }- self.session = sessionstartedAt = .now- Task { await session.start() }+ begin(cloud: VoiceSettings.provider)}.onDisappear {session?.end()+ countCloudMinutes()isSpeaking = falseinterrupt = nilmodel.endVoiceCall(callID)@@ -62,8 +51,78 @@ struct CallView: View {.onChange(of: session?.phase) { _, phase inisSpeaking = phase == .speakinginterrupt = phase == .speaking ? { session?.interrupt() } : nil+ // A cloud engine that can't start or drops mid-call hands over to on-device voice.+ if case .failed(let message) = phase, let provider = session?.provider {+ countCloudMinutes()+ notice = "\(provider.name) isn't available (\(message)). Using on-device voice."+ begin(cloud: nil)+ }}- .codyncSheet(isPresented: $settings) { CallSettingsView() }+ .codyncSheet(isPresented: $settings) { VoiceChatSettingsView() }+ }++ /// Starts the engine: a realtime provider on the key kept by the computer, or on-device speech.+ private func begin(cloud provider: VoiceProvider?) {+ let op = CallOperator(model: model, botId: botId)+ let engine: any VoiceEngine+ if let provider, VoiceSettings.isSpeechMode(provider) {+ let transcribe = VoiceSettings.transcribeModel(provider)+ let speechModel = VoiceSettings.speechModel(provider)+ let voice = VoiceSettings.voice(provider)+ let client = { [model] () throws -> HostClient in+ guard let client = model.client else { throw VoiceError("Not connected to \(model.hostName).") }+ return client+ }+ engine = CloudSpeechEngine(provider: provider, speech: .init(+ transcribe: { try await client().voiceTranscribe(provider, model: transcribe, wav: $0) },+ speak: { try await client().voiceSpeak(provider, model: speechModel, voice: voice, text: $0) },+ send: { [model, botId] in model.send($0, to: botId) }+ ))+ cloudStartedAt = .now+ } else if let provider {+ let chosen = VoiceSettings.model(provider)+ let voice = VoiceSettings.voice(provider)+ let credential: @MainActor () async throws -> String = { [model] in+ guard let client = model.client else { throw VoiceError("Not connected to \(model.hostName).") }+ return try await client.voiceSession(provider, model: chosen, voice: voice)+ }+ engine = switch provider {+ case .openAI: OpenAIRealtimeEngine(credential: credential, op: op)+ case .gemini: GeminiLiveEngine(model: chosen, voice: voice, credential: credential, op: op)+ }+ cloudStartedAt = .now+ } else {+ engine = OnDeviceEngine { [model, botId] in model.send($0, to: botId) }+ }+ engine.onActivityChanged = { [weak engine, model, botId, callID] active in+ if active {+ model.beginVoiceCall(callID, botId: botId,+ speak: { [weak engine] in engine?.speak(reply: $0) },+ announce: { [weak engine] in engine?.announce($0) },+ end: { [weak engine] in engine?.end() })+ } else {+ model.endVoiceCall(callID)+ }+ }+ session = engine+ Task { await engine.start() }+ }++ private func countCloudMinutes() {+ guard let provider = session?.provider, let since = cloudStartedAt else { return }+ VoiceUsage.add(seconds: Int(Date.now.timeIntervalSince(since)), for: provider)+ cloudStartedAt = nil+ }++ private func line(_ text: String, color: Color) -> some View {+ Text(text)+ .font(.footnote)+ .foregroundStyle(color)+ .multilineTextAlignment(.center)+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ .composerSurface(in: Capsule())+ .transition(.opacity)}private var bar: some View {@@ -71,26 +130,40 @@ struct CallView: View {avatarCallLevelDots(level: session?.level ?? 0, speaking: session?.phase == .speaking,working: bot?.isWorking == true, color: color, reduceMotion: reduceMotion)- .frame(maxWidth: .infinity, minHeight: 20, maxHeight: 20)+ .frame(minWidth: Self.dotsWidth, maxWidth: Self.dotsMaxWidth, minHeight: Self.dotsHeight, maxHeight: Self.dotsHeight).accessibilityLabel(statusText)+ // Audio leaves the phone: say where.+ if let provider = session?.provider {+ Text(provider.name)+ .appFont(.caption2.weight(.semibold))+ .foregroundStyle(Palette.secondary)+ .accessibilityLabel("Voice by \(provider.name)")+ }round("Call settings", "gearshape") { settings = true }let muted = session?.muted == trueround(muted ? "Unmute" : "Mute", muted ? "mic.slash" : "mic", on: muted) { session?.muted.toggle() }Button(action: close) {Image(systemName: "xmark")- .font(.system(size: 17, weight: .semibold))+ .font(.system(size: Self.iconSize, weight: .semibold)).foregroundStyle(.white)- .frame(width: 46, height: 46)+ .frame(width: Self.buttonSize, height: Self.buttonSize).background(Palette.danger, in: Circle())}.buttonStyle(PressScale()).accessibilityLabel("End call")+ .help("End call")}- .padding(.leading, 14)- .padding(.trailing, 7)- .padding(.vertical, 7)- .glass(in: Capsule())- .shadow(color: .black.opacity(0.08), radius: 16, y: 6)+ .padding(.leading, InterfaceMetrics.value(mac: 18, mobile: 14))+ .padding(.trailing, InterfaceMetrics.value(mac: 10, mobile: 7))+ .padding(.vertical, InterfaceMetrics.value(mac: 10, mobile: 7))+ #if os(macOS)+ // Floats over the chat like the title pill: frosted, raised, sized to its content.+ .frosted(in: Capsule())+ .shadow(color: .black.opacity(0.25), radius: 20, y: 8)+ #else+ .glass(in: Capsule())+ .shadow(color: .black.opacity(0.08), radius: 16, y: 6)+ #endif}/// The bot; tapping it while it talks cuts the reply short.@@ -110,16 +183,31 @@ struct CallView: View {private func round(_ label: String, _ symbol: String, on: Bool = false, action: @escaping () -> Void) -> some View {Button(action: action) {Image(systemName: symbol)- .font(.system(size: 17, weight: .medium))- .foregroundStyle(on ? Palette.onAccent : Palette.text)+ .font(.system(size: Self.iconSize, weight: .medium))+ .foregroundStyle(on ? Palette.onAccent : Self.buttonInk).contentTransition(.symbolEffect(.replace))- .frame(width: 46, height: 46)- .background(on ? Palette.accentFill : Palette.background, in: Circle())+ .frame(width: Self.buttonSize, height: Self.buttonSize)+ .background(on ? Palette.accentFill : Self.buttonFill, in: Circle())}.buttonStyle(PressScale()).accessibilityLabel(label)+ .help(label)}+ // The phone's bar spans the screen; the Mac's is a compact panel (Grok's desktop call bar).+ private static let buttonSize = InterfaceMetrics.value(mac: 40, mobile: 46)+ private static let iconSize = InterfaceMetrics.value(mac: 16, mobile: 17)+ private static let dotsHeight = InterfaceMetrics.value(mac: 16, mobile: 20)+ private static let dotsWidth = InterfaceMetrics.value(mac: 120, mobile: 0)+ private static let dotsMaxWidth: CGFloat = InterfaceMetrics.value(mac: 120, mobile: .infinity)+ #if os(macOS)+ private static let buttonFill = Palette.bubbleUser+ private static let buttonInk = Palette.secondary+ #else+ private static let buttonFill = Palette.background+ private static let buttonInk = Palette.text+ #endif+private var statusText: String {switch session?.phase {case .starting, nil: "Connecting"@@ -167,27 +255,3 @@ private struct CallLevelDots: View {}}}--/// The call bar's gear: how long a pause sends what you said, and how fast replies are read.-private struct CallSettingsView: View {- @AppStorage(CallSession.pauseKey) private var pause = 1.5- @AppStorage(CallSession.rateKey) private var rate = Double(AVSpeechUtteranceDefaultSpeechRate)-- var body: some View {- VStack(spacing: 0) {- ModalHeader("Voice chat")- CardForm {- CardSection("Send after a pause of", footer: "Longer gives you time to think mid-sentence.") {- SegmentedChoice(selection: $pause, options: [(1.0, "1 s"), (1.5, "1.5 s"), (2.5, "2.5 s")])- }- CardSection("Reading speed") {- SegmentedChoice(selection: $rate, options: [- (0.42, "Slower"), (Double(AVSpeechUtteranceDefaultSpeechRate), "Normal"), (0.56, "Faster"),- ])- }- }- }- .background(Palette.background)- }-}-#endifdiff --git a/kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift b/kit/Sources/CodyncUI/Call/CloudSpeechEngine.swiftnew file mode 100644index 00000000..da461aaa--- /dev/null+++ b/kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift@@ -0,0 +1,305 @@+import AVFoundation+import CodyncKit+import Foundation+import Observation+import os++private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")++/// The provider's speech models without a live conversation: each utterance is cut at a pause,+/// transcribed with the provider's speech-to-text, and sent as an ordinary message; the bot's+/// replies are read aloud with its text-to-speech. Both go through the computer, which holds the key.+@MainActor+@Observable+final class CloudSpeechEngine: VoiceEngine {+ private(set) var phase: VoicePhase = .starting {+ didSet { onActivityChanged?(!ended && phase.isActive) }+ }+ private(set) var level: Float = 0+ var muted = false {+ didSet {+ guard muted != oldValue else { return }+ if muted { dropUtterance() }+ }+ }+ let provider: VoiceProvider?+ @ObservationIgnored var onActivityChanged: ((Bool) -> Void)?++ struct Speech {+ let transcribe: @MainActor (Data) async throws -> String+ let speak: @MainActor (String) async throws -> (Data, String)+ let send: @MainActor (String) -> Void+ }++ private let speech: Speech+ private let chunk: Int+ private let engine = AVAudioEngine()+ private var audioRunning = false+ private var ended = false++ // Listening: PCM since speech began (plus a little before), and when it last went quiet.+ private var preroll = Data()+ private var utterance = Data()+ private var speaking = false+ private var quietSince: Date?+ /// How much of the utterance was actually loud (bytes of PCM above the threshold).+ private var voiced = 0+ /// Playback just ended; the room's echo of it isn't speech.+ private var deafUntil = Date.distantPast+ /// Transcriptions finish in the order they were spoken.+ private var transcribing: Task<Void, Never>?++ // Speaking: the reply's clips, fetched one ahead of the one playing.+ private var queue: [String] = []+ private var player: AVAudioPlayer?+ private var playDone: PlayDone?+ private var next: Task<(Data, String)?, Never>?+ private var speakGeneration = 0++ private static let threshold: Float = 0.3+ private static let prerollBytes = 16000 * 2 * 3 / 10+ /// An utterance has to fit one channel message once base64-encoded.+ private static let maxBytes = 16000 * 2 * 20+ /// Under 0.4 s of voice is a cough or noise, not something to send (and speech-to-text models+ /// invent words for noise).+ private static let minVoicedBytes = 16000 * 2 * 4 / 10++ private var endOfUtterance: TimeInterval {+ let seconds = UserDefaults.standard.double(forKey: OnDeviceEngine.pauseKey)+ return seconds > 0 ? seconds : 1.5+ }++ init(provider: VoiceProvider, speech: Speech) {+ self.provider = provider+ self.speech = speech+ chunk = provider.speechChunk+ }++ func start() async {+ guard await AVAudioApplication.requestRecordPermission() else {+ return fail("Allow the microphone for Codync in Settings to talk to your bots.")+ }+ guard !ended else { return }+ do {+ #if os(iOS)+ let session = AVAudioSession.sharedInstance()+ try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])+ try session.setActive(true)+ #endif+ let input = engine.inputNode+ let format = input.outputFormat(forBus: 0)+ input.installTap(onBus: 0, bufferSize: 2048, format: format, block: MicTap.pcm16k(from: format) { [weak self] pcm, level in+ Task { @MainActor in self?.heard(pcm, level: level) }+ })+ engine.prepare()+ try engine.start()+ audioRunning = true+ } catch {+ return fail("Couldn't use the microphone: \(error.localizedDescription)")+ }+ phase = .listening+ }++ func end() {+ ended = true+ onActivityChanged?(false)+ stopSpeaking()+ transcribing?.cancel()+ if audioRunning {+ engine.inputNode.removeTap(onBus: 0)+ engine.stop()+ audioRunning = false+ }+ #if os(iOS)+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)+ #endif+ }++ func interrupt() {+ guard phase == .speaking else { return }+ stopSpeaking()+ phase = .listening+ }++ func speak(reply: String) { say(SpokenText.from(reply)) }++ func announce(_ notice: String) { say(notice) }++ // MARK: listening++ private func heard(_ pcm: Data, level: Float) {+ guard !ended, !muted, phase == .listening, Date.now >= deafUntil else { return }+ self.level = level+ if level > Self.threshold {+ speaking = true+ quietSince = nil+ voiced += pcm.count+ } else if speaking, quietSince == nil {+ quietSince = .now+ }+ if speaking {+ utterance.append(pcm)+ let paused = quietSince.map { Date.now.timeIntervalSince($0) >= endOfUtterance } ?? false+ if paused || utterance.count >= Self.maxBytes { submit() }+ } else {+ preroll.append(pcm)+ if preroll.count > Self.prerollBytes { preroll.removeFirst(preroll.count - Self.prerollBytes) }+ }+ }++ private func submit() {+ let wav = MicTap.wav(preroll + utterance)+ let enough = voiced >= Self.minVoicedBytes+ dropUtterance()+ guard enough else { return }+ let previous = transcribing+ let speech = speech+ transcribing = Task { [weak self] in+ await previous?.value+ do {+ let text = try await speech.transcribe(wav).trimmingCharacters(in: .whitespacesAndNewlines)+ guard let self, !self.ended, !text.isEmpty else { return }+ speech.send(text)+ } catch {+ log.error("transcribe: \(error.localizedDescription, privacy: .public)")+ self?.fail(error.localizedDescription)+ }+ }+ }++ private func dropUtterance() {+ preroll = Data()+ utterance = Data()+ speaking = false+ quietSince = nil+ voiced = 0+ level = 0+ }++ // MARK: speaking++ /// Queues text in clips the provider can turn into one channel message each.+ private func say(_ text: String) {+ guard !ended, !phase.isFailed, phase != .starting, !text.isEmpty else { return }+ queue += Self.clips(text, limit: chunk)+ if player == nil, next == nil { playNext() }+ }++ private func playNext() {+ guard !ended else { return }+ let generation = speakGeneration+ let pending = next ?? fetch(queue.isEmpty ? nil : queue.removeFirst())+ next = nil+ Task { [weak self] in+ guard let clip = await pending.value else {+ guard let self, generation == self.speakGeneration else { return }+ self.finishedSpeaking()+ return+ }+ guard let self, generation == self.speakGeneration, !self.ended else { return }+ self.play(clip)+ if !self.queue.isEmpty { self.next = self.fetch(self.queue.removeFirst()) }+ }+ }++ private func fetch(_ text: String?) -> Task<(Data, String)?, Never> {+ let speech = speech+ return Task { @MainActor in+ guard let text else { return nil }+ do {+ return try await speech.speak(text)+ } catch {+ log.error("speak: \(error.localizedDescription, privacy: .public)")+ return nil+ }+ }+ }++ private func play(_ clip: (Data, String)) {+ // Audio from a file with the right extension: AVAudioPlayer reads the container from it.+ let url = FileManager.default.temporaryDirectory.appendingPathComponent("codync-speech-\(UUID().uuidString).\(clip.1)")+ do {+ try clip.0.write(to: url)+ let player = try AVAudioPlayer(contentsOf: url)+ try? FileManager.default.removeItem(at: url)+ let generation = speakGeneration+ let done = PlayDone { [weak self] in Task { @MainActor in self?.played(generation) } }+ player.delegate = done+ playDone = done+ self.player = player+ dropUtterance()+ phase = .speaking+ player.play()+ } catch {+ try? FileManager.default.removeItem(at: url)+ log.error("play: \(error.localizedDescription, privacy: .public)")+ playNext()+ }+ }++ private func played(_ generation: Int) {+ guard generation == speakGeneration else { return }+ player = nil+ if queue.isEmpty, next == nil { finishedSpeaking() } else { playNext() }+ }++ private func finishedSpeaking() {+ player = nil+ deafUntil = .now.addingTimeInterval(0.4)+ if phase == .speaking { phase = .listening }+ }++ private func stopSpeaking() {+ speakGeneration += 1+ queue.removeAll()+ next?.cancel()+ next = nil+ player?.stop()+ player = nil+ }++ private func fail(_ message: String) {+ end()+ phase = .failed(message)+ }++ /// Sentences grouped into clips of at most `limit` characters (longer sentences are cut).+ static func clips(_ text: String, limit: Int) -> [String] {+ var out: [String] = []+ var current = ""+ var sentence = ""+ func flush(_ s: inout String) {+ let t = s.trimmingCharacters(in: .whitespacesAndNewlines)+ if !t.isEmpty { out.append(t) }+ s = ""+ }+ func add(_ piece: String) {+ if current.count + piece.count > limit { flush(¤t) }+ var piece = piece+ while piece.count > limit {+ out.append(String(piece.prefix(limit)))+ piece = String(piece.dropFirst(limit))+ }+ current += piece+ }+ for ch in text {+ sentence.append(ch)+ if ".!?。!?\n".contains(ch) {+ add(sentence)+ sentence = ""+ }+ }+ add(sentence)+ flush(¤t)+ return out+ }+}++/// Player delegate: a clip that played to its end moves on to the next one.+private final class PlayDone: NSObject, AVAudioPlayerDelegate, Sendable {+ let onFinish: @Sendable () -> Void++ init(onFinish: @escaping @Sendable () -> Void) { self.onFinish = onFinish }++ func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { onFinish() }+}diff --git a/kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift b/kit/Sources/CodyncUI/Call/GeminiLiveEngine.swiftnew file mode 100644index 00000000..954a1fb7--- /dev/null+++ b/kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift@@ -0,0 +1,339 @@+import AVFoundation+import CodyncKit+import Foundation+import Observation+import os++private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")++/// Gemini Live over a WebSocket, phone ↔ Google directly: 16 kHz PCM up, 24 kHz PCM down,+/// echo-cancelled by the voice-processing input so you can talk over it. The user's key stays on the+/// computer, which mints one-use ephemeral tokens; a session the server ends (`goAway`) is resumed with a fresh one.+@MainActor+@Observable+final class GeminiLiveEngine: VoiceEngine {+ private(set) var phase: VoicePhase = .starting {+ didSet { onActivityChanged?(!ended && phase.isActive) }+ }+ private(set) var level: Float = 0+ var muted = false {+ didSet {+ guard muted != oldValue else { return }+ level = 0+ if muted { send(["realtimeInput": ["audioStreamEnd": true]]) }+ }+ }+ var provider: VoiceProvider? { .gemini }+ @ObservationIgnored var onActivityChanged: ((Bool) -> Void)?++ /// A short-lived credential for the provider, minted by the computer that holds the key.+ private let credential: @MainActor () async throws -> String+ private let model: String+ private let voice: String+ private let op: CallOperator+ private var socket: URLSessionWebSocketTask?+ /// Setup is done on the current socket.+ private var ready = false+ private var resumeHandle: String?+ private var reconnects = 0+ private let engine = AVAudioEngine()+ private let player = AVAudioPlayerNode()+ private var audioRunning = false+ /// Buffers scheduled and not played yet; bumping the generation drops late callbacks.+ private var queued = 0+ private var playGeneration = 0+ /// The model finished its turn (nothing more is coming until we or the user speak).+ private var turnDone = true+ /// After a local interrupt, the rest of the turn's audio is dropped.+ private var dropping = false+ private var pending: [String] = []+ private var ended = false++ private static let playFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 24000, channels: 1, interleaved: false)++ init(model: String, voice: String, credential: @escaping @MainActor () async throws -> String, op: CallOperator) {+ self.credential = credential+ self.model = model+ self.voice = voice+ self.op = op+ }++ func start() async {+ guard await AVAudioApplication.requestRecordPermission() else {+ return fail("Allow the microphone for Codync in Settings to talk to your bots.")+ }+ await connect()+ }++ private func connect() async {+ do {+ let token = try await credential()+ guard !ended else { return }+ var url = URLComponents(string: "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained")+ url?.queryItems = [URLQueryItem(name: "access_token", value: token)]+ guard let url = url?.url else { throw VoiceError( "Couldn't reach Gemini.") }+ let socket = URLSession.shared.webSocketTask(with: url)+ socket.maximumMessageSize = 16 << 20+ self.socket = socket+ ready = false+ socket.resume()+ receive(socket)+ sendSetup(on: socket)+ } catch {+ guard !ended else { return }+ fail(error.localizedDescription)+ }+ }++ private func sendSetup(on socket: URLSessionWebSocketTask) {+ let tools: [[String: Any]] = CallOperator.tools.map { tool in+ var declaration: [String: Any] = ["name": tool.name, "description": tool.description]+ if let properties = tool.parameters["properties"] as? [String: any Sendable], !properties.isEmpty {+ declaration["parameters"] = Self.geminiSchema(tool.parameters)+ }+ return declaration+ }+ let setup: [String: Any] = [+ "model": "models/\(model)",+ "generationConfig": [+ "responseModalities": ["AUDIO"],+ "speechConfig": ["voiceConfig": ["prebuiltVoiceConfig": ["voiceName": voice]]],+ ] as [String: Any],+ "systemInstruction": ["parts": [["text": op.instructions]]],+ "tools": [["functionDeclarations": tools]],+ // Audio sessions are otherwise capped at 15 minutes.+ "contextWindowCompression": ["slidingWindow": [String: Any]()],+ "sessionResumption": resumeHandle.map { ["handle": $0] } ?? [:],+ ]+ send(["setup": setup], on: socket)+ }++ func end() {+ ended = true+ onActivityChanged?(false)+ socket?.cancel(with: .normalClosure, reason: nil)+ socket = nil+ stopPlayback()+ if audioRunning {+ engine.inputNode.removeTap(onBus: 0)+ engine.stop()+ audioRunning = false+ }+ #if os(iOS)+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)+ #endif+ }++ func interrupt() {+ guard phase == .speaking else { return }+ stopPlayback()+ dropping = !turnDone+ phase = .listening+ }++ func speak(reply: String) {+ guard !ended, !phase.isFailed else { return }+ pending.append(op.reply(reply))+ flush()+ }++ func announce(_ notice: String) {+ guard !ended, !phase.isFailed else { return }+ pending.append(op.notice(notice))+ flush()+ }++ // MARK: socket++ private func receive(_ socket: URLSessionWebSocketTask) {+ Task { [weak self] in+ while true {+ let message: URLSessionWebSocketTask.Message+ do {+ message = try await socket.receive()+ } catch {+ self?.closed(socket)+ return+ }+ guard let self, self.socket === socket else { return }+ switch message {+ case .data(let data): self.received(data)+ case .string(let text): self.received(Data(text.utf8))+ @unknown default: break+ }+ }+ }+ }++ private func closed(_ socket: URLSessionWebSocketTask) {+ guard !ended, self.socket === socket else { return }+ self.socket = nil+ ready = false+ let reason = socket.closeReason.map { String(decoding: $0, as: UTF8.self) } ?? ""+ log.info("gemini closed: \(reason, privacy: .public)")+ if resumeHandle != nil, reconnects < 3 {+ reconnects += 1+ Task { await connect() }+ } else {+ fail(reason.isEmpty ? "Lost the connection to Gemini." : reason)+ }+ }++ private func received(_ data: Data) {+ guard !ended, let msg = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return }+ if msg["setupComplete"] != nil {+ ready = true+ reconnects = 0+ if !audioRunning {+ do {+ try startAudio()+ } catch {+ return fail("Couldn't use the microphone: \(error.localizedDescription)")+ }+ }+ if phase == .starting { phase = .listening }+ flush()+ }+ if let content = msg["serverContent"] as? [String: Any] {+ if content["interrupted"] as? Bool == true {+ stopPlayback()+ dropping = false+ if phase == .speaking { phase = .listening }+ }+ if let parts = (content["modelTurn"] as? [String: Any])?["parts"] as? [[String: Any]] {+ turnDone = false+ for part in parts {+ if let audio = (part["inlineData"] as? [String: Any])?["data"] as? String, !dropping { play(audio) }+ }+ }+ if content["turnComplete"] as? Bool == true {+ turnDone = true+ dropping = false+ if queued == 0, phase == .speaking { phase = .listening }+ flush()+ }+ }+ if let calls = (msg["toolCall"] as? [String: Any])?["functionCalls"] as? [[String: Any]] {+ let responses: [[String: Any]] = calls.compactMap { call in+ guard let id = call["id"] as? String, let name = call["name"] as? String else { return nil }+ let output = op.call(name, arguments: call["args"] as? [String: Any] ?? [:])+ let result = (try? JSONSerialization.jsonObject(with: Data(output.utf8))) ?? [:]+ return ["id": id, "name": name, "response": ["result": result]]+ }+ send(["toolResponse": ["functionResponses": responses]])+ }+ if let update = msg["sessionResumptionUpdate"] as? [String: Any],+ update["resumable"] as? Bool == true, let handle = update["newHandle"] as? String {+ resumeHandle = handle+ }+ if msg["goAway"] != nil {+ // The server ends this connection soon; carry on in a resumed one.+ socket?.cancel(with: .normalClosure, reason: nil)+ }+ }++ private func send(_ message: [String: Any], on socket: URLSessionWebSocketTask? = nil) {+ guard let socket = socket ?? (ready ? self.socket : nil),+ let data = try? JSONSerialization.data(withJSONObject: message) else { return }+ socket.send(.string(String(decoding: data, as: UTF8.self))) { error in+ if let error { log.error("gemini send: \(error.localizedDescription, privacy: .public)") }+ }+ }++ /// Replies wait for the model to finish talking; `turnComplete` here would cut it off.+ private func flush() {+ guard ready, turnDone, queued == 0, !pending.isEmpty else { return }+ let text = pending.joined(separator: "\n\n")+ pending.removeAll()+ turnDone = false+ send(["clientContent": ["turns": [["role": "user", "parts": [["text": text]]]], "turnComplete": true] as [String: Any]])+ }++ // MARK: audio++ private func startAudio() throws {+ #if os(iOS)+ let session = AVAudioSession.sharedInstance()+ try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])+ try session.setActive(true)+ #endif+ let input = engine.inputNode+ try input.setVoiceProcessingEnabled(true)+ engine.attach(player)+ engine.connect(player, to: engine.mainMixerNode, format: Self.playFormat)+ let format = input.outputFormat(forBus: 0)+ input.installTap(onBus: 0, bufferSize: 2048, format: format, block: MicTap.pcm16k(from: format) { [weak self] pcm, level in+ let audio = pcm.base64EncodedString()+ Task { @MainActor in self?.captured(audio, level: level) }+ })+ engine.prepare()+ try engine.start()+ player.play()+ audioRunning = true+ }++ private func captured(_ audio: String, level: Float) {+ guard !ended, !muted, phase.isActive else { return }+ self.level = phase == .speaking ? 0 : level+ send(["realtimeInput": ["audio": ["data": audio, "mimeType": "audio/pcm;rate=16000"]]])+ }++ private func play(_ base64: String) {+ guard let format = Self.playFormat, let data = Data(base64Encoded: base64), data.count >= 2 else { return }+ let frames = data.count / 2+ guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(frames)),+ let out = buffer.floatChannelData?[0] else { return }+ buffer.frameLength = AVAudioFrameCount(frames)+ data.withUnsafeBytes { raw in+ for i in 0..<frames {+ let sample = Int16(littleEndian: raw.loadUnaligned(fromByteOffset: i * 2, as: Int16.self))+ out[i] = Float(sample) / 32768+ }+ }+ queued += 1+ level = 0+ phase = .speaking+ let generation = playGeneration+ player.scheduleBuffer(buffer, completionCallbackType: .dataPlayedBack) { [weak self] _ in+ Task { @MainActor in self?.played(generation) }+ }+ }++ private func played(_ generation: Int) {+ guard generation == playGeneration, !ended else { return }+ queued = max(0, queued - 1)+ guard queued == 0, turnDone else { return }+ if phase == .speaking { phase = .listening }+ flush()+ }++ private func stopPlayback() {+ playGeneration += 1+ queued = 0+ if audioRunning {+ player.stop()+ player.play()+ }+ }++ private func fail(_ message: String) {+ end()+ phase = .failed(message)+ }++ // MARK: helpers++ /// Gemini's schema spells types in capitals (`OBJECT`, `STRING`).+ private static func geminiSchema(_ schema: [String: any Sendable]) -> [String: Any] {+ var out: [String: Any] = [:]+ for (key, value) in schema {+ switch value {+ case let type as String where key == "type": out[key] = type.uppercased()+ case let nested as [String: any Sendable] where key == "properties":+ out[key] = nested.mapValues { ($0 as? [String: any Sendable]).map(geminiSchema) ?? [:] }+ default: out[key] = value+ }+ }+ return out+ }+}diff --git a/kit/Sources/CodyncUI/Call/CallSession.swift b/kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftsimilarity index 89%rename from kit/Sources/CodyncUI/Call/CallSession.swiftrename to kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftindex 7cc454e7..1470c1ab 100644--- a/kit/Sources/CodyncUI/Call/CallSession.swift+++ b/kit/Sources/CodyncUI/Call/OnDeviceEngine.swift@@ -1,5 +1,5 @@-#if os(iOS)import AVFoundation+import CodyncKitimport NaturalLanguageimport Observationimport os@@ -11,17 +11,11 @@ private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")/// sent as an ordinary message, and the bot's final replies are read aloud. The host sees text only.@MainActor@Observable-final class CallSession {- enum Phase: Equatable {- case starting- case listening- case speaking- case failed(String)- }-- private(set) var phase: Phase = .starting {- didSet { onActivityChanged?(!ended && (phase == .listening || phase == .speaking)) }+final class OnDeviceEngine: VoiceEngine {+ private(set) var phase: VoicePhase = .starting {+ didSet { onActivityChanged?(!ended && phase.isActive) }}+ var provider: VoiceProvider? { nil }/// Keep the transport attached while audio is active, even without a visible UI update.@ObservationIgnored var onActivityChanged: ((Bool) -> Void)?/// What you're saying right now (live caption).@@ -77,13 +71,15 @@ final class CallSession {return fail("Speech recognition isn't available for this language right now.")}guard !ended else { return }- do {- let audio = AVAudioSession.sharedInstance()- try audio.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])- try audio.setActive(true)- } catch {- return fail("Couldn't start audio: \(error.localizedDescription)")- }+ #if os(iOS)+ do {+ let audio = AVAudioSession.sharedInstance()+ try audio.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])+ try audio.setActive(true)+ } catch {+ return fail("Couldn't start audio: \(error.localizedDescription)")+ }+ #endiflisten()}@@ -92,11 +88,13 @@ final class CallSession {onActivityChanged?(false)stopListening()synthesizer.stopSpeaking(at: .immediate)- try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)+ #if os(iOS)+ try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)+ #endif}/// Reads a reply aloud (the bot's final message), pausing the microphone meanwhile.- func speak(_ markdown: String) {+ func speak(reply markdown: String) {let text = SpokenText.from(markdown)guard !ended, !text.isEmpty, phase != .starting, !(phase.isFailed) else { return }stopListening()@@ -109,6 +107,8 @@ final class CallSession {synthesizer.speak(utterance)}+ func announce(_ notice: String) { speak(reply: notice) }+/// Cuts the reply short and goes back to listening.func interrupt() {guard phase == .speaking else { return }@@ -202,7 +202,7 @@ final class CallSession {}}- private nonisolated static func results(_ session: CallSession, generation: Int) -> @Sendable (SFSpeechRecognitionResult?, (any Error)?) -> Void {+ private nonisolated static func results(_ session: OnDeviceEngine, generation: Int) -> @Sendable (SFSpeechRecognitionResult?, (any Error)?) -> Void {{ result, _ inguard let result else { return }let text = result.bestTranscription.formattedString@@ -234,10 +234,6 @@ final class CallSession {}}-extension CallSession.Phase {- var isFailed: Bool { if case .failed = self { true } else { false } }-}-/// Synthesizer delegate: a finished utterance hands back to listening. Cancelled ones don't.private final class SpeechDone: NSObject, AVSpeechSynthesizerDelegate, Sendable {let onFinish: @Sendable () -> Void@@ -248,4 +244,3 @@ private final class SpeechDone: NSObject, AVSpeechSynthesizerDelegate, SendableonFinish()}}-#endifdiff --git a/kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift b/kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftnew file mode 100644index 00000000..a6bc12ac--- /dev/null+++ b/kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift@@ -0,0 +1,271 @@+import AVFoundation+import CodyncKit+import Foundation+import Observation+import os+@preconcurrency import WebRTC++private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")++/// OpenAI Realtime over WebRTC, phone ↔ OpenAI directly: the microphone is a WebRTC audio track,+/// the model's voice plays from the remote track, and events (tools, replies) go over `oai-events`.+/// The user's key stays on the computer, which mints the client secret; the host never sees audio.+@MainActor+@Observable+final class OpenAIRealtimeEngine: VoiceEngine {+ private(set) var phase: VoicePhase = .starting {+ didSet { onActivityChanged?(!ended && phase.isActive) }+ }+ private(set) var level: Float = 0+ var muted = false {+ didSet {+ mic?.isEnabled = !muted+ if muted { level = 0 }+ }+ }+ var provider: VoiceProvider? { .openAI }+ @ObservationIgnored var onActivityChanged: ((Bool) -> Void)?++ /// A short-lived credential for the provider, minted by the computer that holds the key.+ private let credential: @MainActor () async throws -> String+ private let op: CallOperator+ private var pc: RTCPeerConnection?+ private var events: RTCDataChannel?+ private var mic: RTCAudioTrack?+ private var delegate: RealtimeEvents?+ private var ended = false+ /// A response is being generated; new replies wait for it to finish.+ private var responding = false+ private var pending: [String] = []+ private var dropTimer: Task<Void, Never>?++ init(credential: @escaping @MainActor () async throws -> String, op: CallOperator) {+ self.credential = credential+ self.op = op+ }++ func start() async {+ guard await AVAudioApplication.requestRecordPermission() else {+ return fail("Allow the microphone for Codync in Settings to talk to your bots.")+ }+ do {+ let secret = try await credential()+ guard !ended else { return }+ try await connect(secret: secret)+ } catch {+ guard !ended else { return }+ fail(error.localizedDescription)+ }+ }++ private func connect(secret: String) async throws {+ #if os(iOS)+ let audio = RTCAudioSessionConfiguration.webRTC()+ audio.categoryOptions = [.defaultToSpeaker, .allowBluetoothHFP]+ RTCAudioSessionConfiguration.setWebRTC(audio)+ #endif++ let config = RTCConfiguration()+ config.sdpSemantics = .unifiedPlan+ config.bundlePolicy = .maxBundle+ let delegate = RealtimeEvents(owner: self)+ guard let pc = Self.factory.peerConnection(with: config, constraints: Self.noConstraints, delegate: delegate) else {+ throw VoiceError( "Couldn't start the call audio.")+ }+ self.delegate = delegate+ self.pc = pc+ let source = Self.factory.audioSource(with: Self.noConstraints)+ let mic = Self.factory.audioTrack(with: source, trackId: "mic")+ mic.isEnabled = !muted+ pc.add(mic, streamIds: ["call"])+ self.mic = mic+ let events = pc.dataChannel(forLabel: "oai-events", configuration: RTCDataChannelConfiguration())+ events?.delegate = delegate+ self.events = events++ let offer = try await pc.offer(for: Self.noConstraints)+ try await pc.setLocalDescription(offer)+ var request = URLRequest(url: URL(string: "https://api.openai.com/v1/realtime/calls")!)+ request.httpMethod = "POST"+ request.setValue("Bearer \(secret)", forHTTPHeaderField: "Authorization")+ request.setValue("application/sdp", forHTTPHeaderField: "Content-Type")+ request.httpBody = Data(offer.sdp.utf8)+ request.timeoutInterval = 15+ let (data, response) = try await URLSession.shared.data(for: request)+ guard !ended else { return }+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0+ guard (200..<300).contains(status) else {+ let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]+ let message = (json?["error"] as? [String: Any])?["message"] as? String+ throw VoiceError( message ?? "OpenAI answered \(status).")+ }+ try await pc.setRemoteDescription(RTCSessionDescription(type: .answer, sdp: String(decoding: data, as: UTF8.self)))+ dropTimer = Task { [weak self] in+ try? await Task.sleep(for: .seconds(15))+ guard let self, !Task.isCancelled, self.phase == .starting else { return }+ self.fail("Couldn't reach OpenAI.")+ }+ }++ func end() {+ ended = true+ onActivityChanged?(false)+ dropTimer?.cancel()+ events?.close()+ pc?.close()+ events = nil+ pc = nil+ mic = nil+ delegate = nil+ }++ func interrupt() {+ guard phase == .speaking else { return }+ send(["type": "response.cancel"])+ send(["type": "output_audio_buffer.clear"])+ phase = .listening+ }++ func speak(reply: String) {+ guard !ended, !phase.isFailed else { return }+ pending.append(op.reply(reply))+ flush()+ }++ func announce(_ notice: String) {+ guard !ended, !phase.isFailed else { return }+ pending.append(op.notice(notice))+ flush()+ }++ // MARK: events++ fileprivate func opened() {+ guard !ended else { return }+ dropTimer?.cancel()+ let tools: [[String: Any]] = CallOperator.tools.map {+ ["type": "function", "name": $0.name, "description": $0.description, "parameters": $0.parameters]+ }+ send([+ "type": "session.update",+ "session": [+ "type": "realtime",+ "instructions": op.instructions,+ "tools": tools,+ "audio": ["input": ["turn_detection": ["type": "semantic_vad"]]],+ ] as [String: Any],+ ])+ phase = .listening+ flush()+ }++ fileprivate func received(_ data: Data) {+ guard !ended, let msg = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return }+ switch msg["type"] as? String {+ case "input_audio_buffer.speech_started": level = muted ? 0 : 0.7+ case "input_audio_buffer.speech_stopped": level = 0+ case "output_audio_buffer.started": phase = .speaking+ case "output_audio_buffer.stopped", "output_audio_buffer.cleared": if phase == .speaking { phase = .listening }+ case "response.created": responding = true+ case "response.done":+ responding = false+ flush()+ case "response.function_call_arguments.done":+ guard let id = msg["call_id"] as? String, let name = msg["name"] as? String else { return }+ let args = (msg["arguments"] as? String).flatMap { try? JSONSerialization.jsonObject(with: Data($0.utf8)) } as? [String: Any]+ let output = op.call(name, arguments: args ?? [:])+ send(["type": "conversation.item.create", "item": ["type": "function_call_output", "call_id": id, "output": output]])+ // An empty entry asks for a response once this one is done, so the model speaks the result.+ pending.append("")+ case "error":+ let error = msg["error"] as? [String: Any]+ log.error("realtime: \(error?["message"] as? String ?? "?", privacy: .public)")+ default: break+ }+ }++ fileprivate func iceChanged(_ state: RTCIceConnectionState) {+ guard !ended else { return }+ switch state {+ case .connected, .completed: dropTimer?.cancel()+ case .disconnected:+ dropTimer?.cancel()+ dropTimer = Task { [weak self] in+ try? await Task.sleep(for: .seconds(5))+ guard let self, !Task.isCancelled else { return }+ self.fail("Lost the connection to OpenAI.")+ }+ case .failed: fail("Lost the connection to OpenAI.")+ default: break+ }+ }++ /// Hands waiting replies (and tool results, as empty entries) to the model once it's free.+ private func flush() {+ guard !responding, phase.isActive, events?.readyState == .open, !pending.isEmpty else { return }+ for text in pending where !text.isEmpty {+ send(["type": "conversation.item.create", "item": [+ "type": "message", "role": "user", "content": [["type": "input_text", "text": text]],+ ] as [String: Any]])+ }+ pending.removeAll()+ responding = true+ send(["type": "response.create"])+ }++ private func send(_ event: [String: Any]) {+ guard let events, events.readyState == .open,+ let data = try? JSONSerialization.data(withJSONObject: event) else { return }+ events.sendData(RTCDataBuffer(data: data, isBinary: false))+ }++ private func fail(_ message: String) {+ end()+ phase = .failed(message)+ }++ private static let factory: RTCPeerConnectionFactory = {+ RTCInitializeSSL()+ return RTCPeerConnectionFactory()+ }()++ private static let noConstraints = RTCMediaConstraints(mandatoryConstraints: nil, optionalConstraints: nil)+}++/// WebRTC callbacks arrive on its signaling thread; this hops them to the main actor.+private final class RealtimeEvents: NSObject, RTCPeerConnectionDelegate, RTCDataChannelDelegate, Sendable {+ private let owner: WeakEngine++ @MainActor init(owner: OpenAIRealtimeEngine) { self.owner = WeakEngine(owner) }++ func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream) {}+ func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]) {}+ func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel) {}++ func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState) {+ let owner = owner+ Task { @MainActor in owner.value?.iceChanged(newState) }+ }++ func dataChannelDidChangeState(_ dataChannel: RTCDataChannel) {+ guard dataChannel.readyState == .open else { return }+ let owner = owner+ Task { @MainActor in owner.value?.opened() }+ }++ func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer) {+ let data = buffer.data+ let owner = owner+ Task { @MainActor in owner.value?.received(data) }+ }+}++private final class WeakEngine: Sendable {+ @MainActor weak var value: OpenAIRealtimeEngine?+ @MainActor init(_ value: OpenAIRealtimeEngine) { self.value = value }+}diff --git a/kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift b/kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swiftnew file mode 100644index 00000000..06b41561--- /dev/null+++ b/kit/Sources/CodyncUI/Call/VoiceChatSettingsView.swift@@ -0,0 +1,310 @@+import AVFoundation+import CodyncKit+import SwiftUI++/// Voice chat settings: which voice carries calls (Apple's on this device, or OpenAI / Gemini on the+/// user's own key kept by the computer), the mode, models and voice. Opened from a call's gear and+/// from the computer's row in settings; the computer is the `BotStore` in the environment.+public struct VoiceChatSettingsView: View {+ /// False inside the Mac's Settings window, which titles the page itself.+ var showsHeader: Bool+ @AppStorage(VoiceSettings.engineKey) private var engine = "device"+ @AppStorage(OnDeviceEngine.rateKey) private var rate = Double(AVSpeechUtteranceDefaultSpeechRate)+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ public init(showsHeader: Bool = true) { self.showsHeader = showsHeader }++ public var body: some View {+ VStack(spacing: 0) {+ if showsHeader { ModalHeader("Voice chat") }+ CardForm {+ CardSection("Voice", footer: engineFooter) {+ ValueRow("Engine") {+ ChoicePicker(selection: $engine.animation(Motion.reduced(Motion.layout, reduceMotion)),+ options: [("device", "On device")] + VoiceProvider.allCases.map { ($0.rawValue, $0.name) })+ }+ if let provider = VoiceProvider(rawValue: engine) {+ ModeRows(provider: provider).id(provider)+ } else {+ ValueRow("Reading speed") {+ ChoicePicker(selection: $rate, options: [+ (0.42, "Slower"), (Double(AVSpeechUtteranceDefaultSpeechRate), "Normal"), (0.56, "Faster"),+ ])+ }+ PauseRow()+ }+ }+ if let provider = VoiceProvider(rawValue: engine) {+ ProviderVoiceSettings(provider: provider).id(provider)+ }+ }+ }+ .background(Palette.background)+ #if os(macOS)+ .frame(width: showsHeader ? 440 : nil, height: showsHeader ? 600 : nil)+ #endif+ }++ private var engineFooter: String {+ guard let provider = VoiceProvider(rawValue: engine) else {+ return "Apple speech, on this device. Applies from the next call."+ }+ return "Your own \(provider.name) key, billed by \(provider.name). Applies from the next call."+ }+}++/// A provider's mode, and the pause that ends what you say when it's Speech.+private struct ModeRows: View {+ @AppStorage private var mode: String+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ init(provider: VoiceProvider) {+ _mode = AppStorage(wrappedValue: "realtime", VoiceSettings.modeKey(provider))+ }++ var body: some View {+ ValueRow("Mode", detail: mode == "speech" ? "Sent when you pause, replies read aloud." : "A live conversation. Talk over replies.") {+ ChoicePicker(selection: $mode.animation(Motion.reduced(Motion.layout, reduceMotion)),+ options: [("realtime", "Realtime"), ("speech", "Speech")])+ }+ if mode == "speech" { PauseRow() }+ }+}++/// How long a silence ends what you say, before it's sent.+private struct PauseRow: View {+ @AppStorage(OnDeviceEngine.pauseKey) private var pause = 1.5++ var body: some View {+ ValueRow("Send after a pause of", detail: "Longer leaves time to think mid-sentence.") {+ ChoicePicker(selection: $pause, options: [(1.0, "1 s"), (1.5, "1.5 s"), (2.5, "2.5 s")])+ }+ }+}++/// One provider: mode, the key the computer keeps, models, voice and this month's minutes.+private struct ProviderVoiceSettings: View {+ let provider: VoiceProvider+ @Environment(BotStore.self) private var store+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @AppStorage private var mode: String+ /// nil while the computer hasn't answered yet.+ @State private var saved: Bool?+ @State private var replacing = false+ @State private var key = ""+ @State private var busy = false+ @State private var result: (ok: Bool, text: String)?+ @State private var voice = ""+ @State private var model = ""+ @State private var transcribeModel = ""+ @State private var speechModel = ""+ @State private var models = VoiceModels(models: [], transcribe: [], speech: [])++ init(provider: VoiceProvider) {+ self.provider = provider+ _mode = AppStorage(wrappedValue: "realtime", VoiceSettings.modeKey(provider))+ }++ private var speechMode: Bool { mode == "speech" }+ private var hasKey: Bool { saved == true }++ var body: some View {+ CardSection(provider.name, footer: hasKey ? nil : "Add a key to choose from \(provider.name)'s models.") {+ VStack(alignment: .leading, spacing: 8) {+ if hasKey && !replacing {+ savedKeyRow+ } else if Self.canEditKey {+ keyEntry+ } else if saved == false {+ missingKeyRow+ }+ if let result {+ Label(result.text, systemImage: result.ok ? "checkmark.circle.fill" : "exclamationmark.circle.fill")+ .appFont(.footnote)+ .foregroundStyle(result.ok ? Palette.secondary : Palette.danger)+ .transition(.opacity)+ }+ }+ Group {+ if speechMode {+ ValueRow("Speech to text") { picker($transcribeModel, models.transcribe) }+ ValueRow("Text to speech") { picker($speechModel, models.speech) }+ } else {+ ValueRow("Model") { picker($model, models.models) }+ }+ ValueRow("Voice") { ChoicePicker(selection: $voice, options: provider.voices.map { ($0, $0) }) }+ ValueRow("This month", value: "≈ \(VoiceUsage.minutes(for: provider)) min")+ }+ .disabled(!hasKey)+ .opacity(hasKey ? 1 : 0.55)+ }+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: replacing)+ .animation(Motion.reduced(Motion.fade, reduceMotion), value: result?.text)++ Color.clear.frame(height: 0)+ .task { await load() }+ .onChange(of: voice) { _, v in UserDefaults.standard.set(v, forKey: VoiceSettings.voiceKey(provider)) }+ .onChange(of: model) { _, m in UserDefaults.standard.set(m, forKey: VoiceSettings.modelKey(provider)) }+ .onChange(of: transcribeModel) { _, m in UserDefaults.standard.set(m, forKey: VoiceSettings.transcribeKey(provider)) }+ .onChange(of: speechModel) { _, m in UserDefaults.standard.set(m, forKey: VoiceSettings.speechKey(provider)) }+ }++ /// The key is on the computer: say so, and offer test / replace / remove.+ private var savedKeyRow: some View {+ HStack(spacing: 10) {+ Image(systemName: "key.fill")+ .foregroundStyle(Palette.secondary)+ .accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 1) {+ Text("Key saved").foregroundStyle(Palette.text).lineLimit(1)+ Text("Stays on \(store.hostName)").appFont(.caption).foregroundStyle(Palette.tertiary).lineLimit(1)+ }+ Spacer(minLength: 8)+ if busy {+ Spinner()+ } else {+ IconButton("Test key", systemImage: "checkmark.seal", action: test)+ if Self.canEditKey {+ IconButton("Replace key", systemImage: "pencil") { replacing = true; result = nil }+ IconButton("Remove key", systemImage: "trash", action: remove)+ }+ }+ }+ }++ /// Keys are entered on the computer itself (the host takes `setVoiceKey` from loopback only).+ #if os(macOS)+ private static let canEditKey = true+ #else+ private static let canEditKey = false+ #endif++ /// On the phone: where to add the key.+ private var missingKeyRow: some View {+ HStack(alignment: .top, spacing: 10) {+ Image(systemName: "key")+ .foregroundStyle(Palette.tertiary)+ .accessibilityHidden(true)+ VStack(alignment: .leading, spacing: 2) {+ Text("No \(provider.name) key on \(store.hostName)").foregroundStyle(Palette.text)+ Text("Add it in Codync on that computer: Computers & devices, then Voice chat.")+ .appFont(.caption)+ .foregroundStyle(Palette.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ }++ /// Paste a key; the computer checks it with the provider before keeping it.+ private var keyEntry: some View {+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 10, mobile: 12)) {+ HStack(spacing: 8) {+ SecureField("API key", text: $key, prompt: Text(provider.keyPrompt))+ .plainTextInput()+ .textFieldStyle(.plain)+ .onSubmit(test)+ if busy {+ Spinner()+ } else {+ Button("Save", action: test)+ .buttonStyle(.primary)+ .disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ HStack {+ WebLink("Get a key from \(provider.name)", url: provider.keyPage).appFont(.footnote)+ Spacer()+ if replacing {+ Button("Cancel") { replacing = false; key = ""; result = nil }+ .buttonStyle(.plain)+ .appFont(.footnote)+ .foregroundStyle(Palette.secondary)+ }+ }+ }+ }++ private func picker(_ selection: Binding<String>, _ list: [String]) -> some View {+ // The current choice stays listed before the provider's list arrives.+ let options = list.contains(selection.wrappedValue) ? list : [selection.wrappedValue] + list+ return ChoicePicker(selection: selection, options: options.map { ($0, $0) })+ }++ private func load() async {+ voice = VoiceSettings.voice(provider)+ model = VoiceSettings.model(provider)+ transcribeModel = VoiceSettings.transcribeModel(provider)+ speechModel = VoiceSettings.speechModel(provider)+ if let data = UserDefaults.standard.data(forKey: VoiceSettings.modelsKey(provider)),+ let cached = try? JSONDecoder().decode(VoiceModels.self, from: data) {+ models = cached+ }+ guard let client = store.client else {+ saved = false+ result = (false, "Not connected to \(store.hostName).")+ return+ }+ do {+ saved = try await client.voiceStatus().configured(provider)+ } catch {+ saved = false+ result = (false, error.localizedDescription)+ return+ }+ if hasKey { await loadModels(client) }+ }++ private func loadModels(_ client: HostClient) async {+ guard let list = try? await client.voiceModels(provider) else { return }+ models = list+ UserDefaults.standard.set(try? JSONEncoder().encode(list), forKey: VoiceSettings.modelsKey(provider))+ }++ /// A pasted key is checked with the provider by the computer before it's kept. With a key+ /// saved, Test starts a call credential with the chosen model and voice.+ private func test() {+ let typed = key.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !typed.isEmpty || hasKey else { return }+ run { client in+ if typed.isEmpty || !replacing && hasKey {+ if speechMode {+ _ = try await client.voiceSpeak(provider, model: speechModel, voice: voice, text: "OK")+ } else {+ _ = try await client.voiceSession(provider, model: model, voice: voice)+ }+ result = (true, "Key works")+ } else {+ saved = try await client.setVoiceKey(typed, for: provider).configured(provider)+ key = ""+ replacing = false+ result = (true, "Key works and is saved on \(store.hostName)")+ }+ await loadModels(client)+ }+ }++ private func remove() {+ run { client in+ saved = try await client.setVoiceKey("", for: provider).configured(provider)+ result = nil+ }+ }++ private func run(_ work: @escaping @MainActor (HostClient) async throws -> Void) {+ guard !busy else { return }+ guard let client = store.client else {+ result = (false, "Not connected to \(store.hostName).")+ return+ }+ busy = true+ result = nil+ Task {+ do {+ try await work(client)+ } catch {+ result = (false, error.localizedDescription)+ }+ busy = false+ }+ }+}diff --git a/kit/Sources/CodyncUI/Call/VoiceEngine.swift b/kit/Sources/CodyncUI/Call/VoiceEngine.swiftnew file mode 100644index 00000000..7f19b5bb--- /dev/null+++ b/kit/Sources/CodyncUI/Call/VoiceEngine.swift@@ -0,0 +1,130 @@+import AVFoundation+import CodyncKit+import Foundation++enum VoicePhase: Equatable {+ case starting+ case listening+ case speaking+ case failed(String)++ var isFailed: Bool { if case .failed = self { true } else { false } }+ var isActive: Bool { self == .listening || self == .speaking }+}++/// What carries a call's audio: on-device speech (default) or a realtime model on the user's own key.+/// `CallView` only talks to this; nothing on the host changes.+@MainActor+protocol VoiceEngine: AnyObject, Observable {+ var phase: VoicePhase { get }+ /// Microphone loudness, 0…1, while listening.+ var level: Float { get }+ var muted: Bool { get set }+ /// Where the audio goes when it leaves the phone; nil on device.+ var provider: VoiceProvider? { get }+ /// Keeps the transport attached while audio is active, even without a visible UI update.+ var onActivityChanged: ((Bool) -> Void)? { get set }+ func start() async+ func end()+ /// Cuts what's being said short.+ func interrupt()+ /// A new final reply from the bot to say.+ func speak(reply: String)+ /// A notice from the computer (an approval is waiting) to say.+ func announce(_ notice: String)+}++struct VoiceError: LocalizedError {+ let message: String+ init(_ message: String) { self.message = message }+ var errorDescription: String? { message }+}++/// The engine picked in the call settings, kept on this device.+enum VoiceSettings {+ static let engineKey = "callEngine"++ static var provider: VoiceProvider? {+ UserDefaults.standard.string(forKey: engineKey).flatMap(VoiceProvider.init(rawValue:))+ }++ static func modelKey(_ provider: VoiceProvider) -> String { "callModel.\(provider.rawValue)" }+ /// The provider's model list as last fetched with the user's key.+ static func modelsKey(_ provider: VoiceProvider) -> String { "callModels.\(provider.rawValue)" }++ static func model(_ provider: VoiceProvider) -> String {+ UserDefaults.standard.string(forKey: modelKey(provider)) ?? provider.model+ }++ /// `realtime` (a live conversation) or `speech` (speech to text, then the reply read aloud).+ static func modeKey(_ provider: VoiceProvider) -> String { "callMode.\(provider.rawValue)" }++ static func isSpeechMode(_ provider: VoiceProvider) -> Bool {+ UserDefaults.standard.string(forKey: modeKey(provider)) == "speech"+ }++ static func transcribeKey(_ provider: VoiceProvider) -> String { "callTranscribeModel.\(provider.rawValue)" }+ static func speechKey(_ provider: VoiceProvider) -> String { "callSpeechModel.\(provider.rawValue)" }++ static func transcribeModel(_ provider: VoiceProvider) -> String {+ UserDefaults.standard.string(forKey: transcribeKey(provider)) ?? provider.transcribeModel+ }++ static func speechModel(_ provider: VoiceProvider) -> String {+ UserDefaults.standard.string(forKey: speechKey(provider)) ?? provider.speechModel+ }++ static func voiceKey(_ provider: VoiceProvider) -> String { "callVoice.\(provider.rawValue)" }++ static func voice(_ provider: VoiceProvider) -> String {+ UserDefaults.standard.string(forKey: voiceKey(provider)).flatMap { provider.voices.contains($0) ? $0 : nil }+ ?? provider.voices[0]+ }+}++enum MicTap {+ /// Microphone → 16 kHz mono PCM16 (little-endian) with a loudness level, 0…1. Built off the+ /// main actor: the block runs on the audio thread.+ nonisolated static func pcm16k(from format: AVAudioFormat,+ out: @escaping @Sendable (Data, Float) -> Void) -> AVAudioNodeTapBlock {+ let target = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16000, channels: 1, interleaved: true)+ let converter = target.flatMap { AVAudioConverter(from: format, to: $0) }+ return { buffer, _ in+ guard let target, let converter else { return }+ let capacity = AVAudioFrameCount(Double(buffer.frameLength) * target.sampleRate / format.sampleRate) + 32+ guard let converted = AVAudioPCMBuffer(pcmFormat: target, frameCapacity: capacity) else { return }+ var given = false+ var error: NSError?+ converter.convert(to: converted, error: &error) { _, status in+ if given {+ status.pointee = .noDataNow+ return nil+ }+ given = true+ status.pointee = .haveData+ return buffer+ }+ guard converted.frameLength > 0, let samples = converted.int16ChannelData?[0] else { return }+ let n = Int(converted.frameLength)+ var sum: Float = 0+ for i in 0..<n {+ let v = Float(samples[i]) / 32768+ sum += v * v+ }+ // -50 dB (quiet room) … 0 dB mapped to 0…1.+ let db = 10 * log10(max(sum / Float(n), 1e-10))+ out(Data(bytes: samples, count: n * 2), min(1, max(0, (db + 50) / 50)))+ }+ }++ /// 16 kHz mono PCM16 wrapped in a WAV header.+ static func wav(_ pcm: Data) -> Data {+ var out = Data()+ func le<T: FixedWidthInteger>(_ v: T) { withUnsafeBytes(of: v.littleEndian) { out.append(contentsOf: $0) } }+ out.append(contentsOf: Array("RIFF".utf8)); le(UInt32(36 + pcm.count))+ out.append(contentsOf: Array("WAVEfmt ".utf8)); le(UInt32(16)); le(UInt16(1)); le(UInt16(1))+ le(UInt32(16000)); le(UInt32(32000)); le(UInt16(2)); le(UInt16(16))+ out.append(contentsOf: Array("data".utf8)); le(UInt32(pcm.count))+ return out + pcm+ }+}diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swiftindex 3180e277..8b1f5836 100644--- a/kit/Sources/CodyncUI/Store/BotStore.swift+++ b/kit/Sources/CodyncUI/Store/BotStore.swift@@ -108,6 +108,8 @@ public final class BotStore {let botId: Stringlet startRev: Int64let speak: @MainActor (String) -> Void+ /// A notice from the computer (approval needed), as opposed to the bot's reply.+ let announce: @MainActor (String) -> Voidlet end: @MainActor () -> Void}@ObservationIgnored private var voiceCalls: [UUID: VoiceCall] = [:]@@ -279,9 +281,9 @@ public final class BotStore {/// Audio owns this subscription, so background calls don't depend on SwiftUI updates.func beginVoiceCall(_ id: UUID, botId: String, speak: @escaping @MainActor (String) -> Void,- end: @escaping @MainActor () -> Void) {+ announce: (@MainActor (String) -> Void)? = nil, end: @escaping @MainActor () -> Void) {guard !retired, voiceCalls[id] == nil else { return }- voiceCalls[id] = VoiceCall(botId: botId, startRev: rev, speak: speak, end: end)+ voiceCalls[id] = VoiceCall(botId: botId, startRev: rev, speak: speak, announce: announce ?? speak, end: end)if streamTask == nil { restartStream() }}@@ -541,7 +543,7 @@ public final class BotStore {if bot.unread > 0 { acknowledgeVisibleConversations(bot.id) }if bot.needsInput && !neededInput {for call in Array(voiceCalls.values) where call.botId == bot.id {- call.speak("\(bot.name) needs your approval in the chat.")+ call.announce("\(bot.name) needs your approval in the chat.")}}case let .botDeleted(id, r):diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swiftindex 6042fcf3..f4aa2cfb 100644--- a/kit/Sources/CodyncUI/Thread/Composer.swift+++ b/kit/Sources/CodyncUI/Thread/Composer.swift@@ -159,6 +159,62 @@ struct Composer: View {#endif}+ private enum Trailing: Equatable {+ case interrupt, stop, call, send+ }++ private var trailing: Trailing {+ if onInterrupt != nil, draft.isEmpty, files.isEmpty { return .interrupt }+ if working, draft.isEmpty { return .stop }+ if onCall != nil, draft.isEmpty, files.isEmpty { return .call }+ return .send+ }++ /// One button that morphs between call, send, stop and interrupt: its symbol replaces itself,+ /// its fill crossfades and the capsule narrows to a circle, so switching never pops.+ private var trailingButton: some View {+ let state = trailing+ let enabled = state != .send || canSend+ let (symbol, label, size): (String, String, CGFloat) = switch state {+ case .interrupt: ("stop.fill", "Interrupt", 12)+ case .stop: ("stop.fill", "Stop", 12)+ case .call: ("waveform", "Call", 15)+ case .send: ("arrow.up", "Send", 14)+ }+ let fill: Color = switch state {+ case .interrupt: Palette.danger+ case .send: canSend ? Palette.accentFill : Palette.accentDim+ case .stop, .call: Palette.accentFill+ }+ let ink: Color = switch state {+ case .interrupt: .white+ case .send: canSend ? Palette.onAccent : Palette.tertiary+ case .stop, .call: Palette.onAccent+ }+ return Button {+ switch state {+ case .interrupt: onInterrupt?()+ case .stop: model.stop(botId)+ case .call: onCall?()+ case .send: submit()+ }+ } label: {+ Image(systemName: symbol)+ .appFont(.system(size: size, weight: .bold))+ .contentTransition(.symbolEffect(.replace))+ .foregroundStyle(ink)+ .frame(width: state == .call ? buttonSize * 1.35 : buttonSize, height: buttonSize)+ .background(fill, in: Capsule())+ .contentShape(Capsule())+ }+ .buttonStyle(PressScale())+ .disabled(!enabled)+ .accessibilityLabel(label)+ .help(label)+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: state)+ .animation(Motion.reduced(Motion.morph, reduceMotion), value: canSend)+ }+private var box: some View {HStack(alignment: .bottom, spacing: 8) {TextField(placeholder, text: $draft, axis: .vertical)@@ -168,61 +224,9 @@ struct Composer: View {.focused($focused).padding(.vertical, fieldPadding).sendOnReturn(submit)- Group {- if let onInterrupt, draft.isEmpty, files.isEmpty {- Button(action: onInterrupt) {- Image(systemName: "stop.fill")- .appFont(.system(size: 12, weight: .bold))- .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))- .background(Palette.danger, in: Circle())- .foregroundStyle(.white)- .contentTransition(.symbolEffect(.replace))- }- .buttonStyle(.plain)- .accessibilityLabel("Interrupt")- .help("Interrupt")- } else if working && draft.isEmpty {- Button {- model.stop(botId)- } label: {- Image(systemName: "stop.fill")- .appFont(.system(size: 12, weight: .bold))- .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))- .background(Palette.accentFill, in: Circle())- .foregroundStyle(Palette.onAccent)- }- .buttonStyle(.plain)- .accessibilityLabel("Stop")- .help("Stop")- } else if let onCall, draft.isEmpty, files.isEmpty {- Button(action: onCall) {- Image(systemName: "waveform")- .appFont(.system(size: 15, weight: .bold))- .frame(width: buttonSize * 1.35, height: buttonSize)- .background(Palette.accentFill, in: Capsule())- .foregroundStyle(Palette.onAccent)- }- .buttonStyle(.plain)- .transition(.opacity)- .accessibilityLabel("Call")- .help("Call")- } else {- Button(action: submit) {- Image(systemName: "arrow.up")- .appFont(.system(size: 14, weight: .bold))- .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))- .background(canSend ? Palette.accentFill : Palette.accentDim, in: Circle())- .foregroundStyle(canSend ? Palette.onAccent : Palette.tertiary)- }- .buttonStyle(.plain)- .disabled(!canSend)- .accessibilityLabel("Send")- .help("Send")- }- }- .animation(Motion.layout, value: onInterrupt != nil)- .padding(.bottom, max(0, (textLineHeight + 2 * fieldPadding - buttonSize) / 2))- .animation(Motion.layout, value: isEmpty)+ trailingButton+ .padding(.bottom, max(0, (textLineHeight + 2 * fieldPadding - buttonSize) / 2))+ .animation(Motion.layout, value: isEmpty)}.padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18)).padding(.trailing, 6)diff --git a/kit/Tests/CodyncUITests/SpeechClipTests.swift b/kit/Tests/CodyncUITests/SpeechClipTests.swiftnew file mode 100644index 00000000..b3d26b98--- /dev/null+++ b/kit/Tests/CodyncUITests/SpeechClipTests.swift@@ -0,0 +1,12 @@+@testable import CodyncUI+import Testing++/// Replies are read aloud in clips that each fit one channel message.+@MainActor @Test func speechClipsKeepSentencesUnderTheLimit() {+ let clips = CloudSpeechEngine.clips("第一句。第二句很長很長。Third one! " + String(repeating: "x", count: 25), limit: 10)+ #expect(clips.allSatisfy { $0.count <= 10 })+ #expect(clips.first == "第一句。")+ #expect(clips.joined().replacingOccurrences(of: " ", with: "") ==+ ("第一句。第二句很長很長。Third one! " + String(repeating: "x", count: 25)).replacingOccurrences(of: " ", with: ""))+ #expect(CloudSpeechEngine.clips("", limit: 10).isEmpty)+}diff --git a/web/app/privacy/page.tsx b/web/app/privacy/page.tsxindex bc23de90..c1b0f717 100644--- a/web/app/privacy/page.tsx+++ b/web/app/privacy/page.tsx@@ -5,7 +5,7 @@ export default function Privacy() {<main className="flex-1 flex flex-col items-center px-6 py-16"><article className="max-w-2xl w-full space-y-6"><h1 className="text-3xl font-bold text-white">Privacy Policy</h1>- <p className="text-neutral-400 text-sm">Last updated: September 25, 2026</p>+ <p className="text-neutral-400 text-sm">Last updated: October 4, 2026</p><Section title="Overview">Codync lets you message the coding agents that run on your own computer. It is built so that your code, conversations and credentials stay on your devices.@@ -33,6 +33,7 @@ export default function Privacy() {<li><strong>Apple Push Notification service</strong>: delivers notifications and Live Activity updates.</li><li><strong>Cloudflare Workers</strong>: runs the push relay (nothing stored).</li><li><strong>The coding agents you choose</strong>: they run on your computer under their own terms and privacy policies.</li>+ <li><strong>OpenAI or Google (optional, voice calls)</strong>: only if you add your own OpenAI or Gemini API key in a call's settings. Your voice then goes from your iPhone or Mac directly to that provider, under your account and its privacy policy, together with the bot's name and description and the chat messages it asks for during the call. The key is stored encrypted on your computer, which uses it only to start calls and list models. Without a key, voice calls use Apple speech recognition on your device.</li></ul></Section>