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: voice calls run on the computer
leepokai7a6b5e473275
diff --git a/apps/android/WhatsNew.md b/apps/android/WhatsNew.mdindex fdbdcdd4..64648fca 100644--- a/apps/android/WhatsNew.md+++ b/apps/android/WhatsNew.md@@ -11,6 +11,7 @@ else a generic "Bug fixes and improvements" line. Delete old sections.### zh-Hant- 每台電腦都有一個主助理,固定在列表最上面:它會主動跟進你的事,每天兩次看看有沒有該提醒或能幫忙的,需要時請你授權 Gmail 等服務;打電話給它時由它先開口。+- 語音通話:連線中顯示來回的線,中途換語音不必掛斷,結束只留一行標題,點開看逐字稿。- Bot 可以做 Artifact:報告、追蹤表、儀表板這類要回來看的內容會以卡片出現在聊天裡,點開看完整內容,直接在下方留言請它改,改好就自動更新。- 每個 Bot 的「資料庫」收齊它做的 Artifact,以及聊天裡分享過的檔案和圖片。- 可以建立使用 Hermes Agent 的 Bot。@@ -19,16 +20,11 @@ else a generic "Bug fixes and improvements" line. Delete old sections.- 新增聯結器失敗後再試一次,會使用你改好的金鑰。- 在設定開啟「顯示思考細節」後,點一下工作中 Bot 的狀態膠囊,就能展開這一輪的思考與步驟。- 點對話上方的 Bot 會打開它的詳情、資料庫與設定;「新會話」改到 Bot 列表的長按選單。-- 通話中在設定換了語音,關掉設定後通話就改用新的語音繼續。-- 語音通話連線中,通話列會顯示一條左右來回的線,真正連上後才換回點點。### en-US-- Each computer has a lead bot on top of the list: it follows up on your work, checks in twice a day, asks for access like Gmail when it would help, and speaks first when you call it.-- Bots make artifacts, shown as chat cards; message the bot below one to edit it.-- Each bot's Library holds its artifacts and chat files.-- Create bots that run Hermes Agent.-- Bots hand work to each other without waiting.-- Retrying a failed connector uses the corrected key.+- Each computer has a lead bot on top that follows up, checks in twice a day and speaks first on calls.+- Calls leave one titled line; tap it for the transcript. Change voices mid-call as settings close.+- Bots make artifacts as chat cards you can ask to edit; each bot's Library holds them and its files.+- Create Hermes Agent bots; bots hand off work without waiting.- Settings › Show thinking details unfolds a bot's steps.-- Tap a chat's title for the bot's details; New session moved to the list's touch & hold menu.-- Change the voice mid-call; it takes over when settings close.+- Tap a chat's title for bot details; New session is under touch & hold.diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.ktindex 7913102e..635822a0 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreVoice.kt@@ -10,8 +10,9 @@ import kotlinx.coroutines.flow.*import kotlinx.serialization.json.*import okhttp3.OkHttpClient-// A voice call with one bot: what you say is sent, its replies are read aloud. The engine is the one-// picked in the call settings; a cloud engine that can't start or drops mid-call hands over to on-device voice.+// A voice call with one bot, run by the computer (`HostCallLink`): what you say reaches the bot as the call's+// messages, its replies are read aloud, and the call ends as one titled line. The engine is the one picked in the+// call settings; a cloud engine that can't start or drops mid-call hands over to on-device voice./** The call in progress: its engine (replaced on a fallback), start times and which replies it has read. */internal class VoiceBinding(val id: String, val botId: String, val generation: Int, val startedAt: Long, val replies: VoiceReplyGate) {@@ -26,6 +27,8 @@ internal class VoiceBinding(val id: String, val botId: String, val generation: Ival state = MutableStateFlow(VoiceState())/** `voice_call_started` (and `callStarted`) went out: once per call, with the engine that got it going. */var reported = false+ /** The call on the computer. */+ var link: HostCallLink? = null}private val voiceHttp by lazy { OkHttpClient() }@@ -67,12 +70,7 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {call.choice = choices.engineChoice(provider, callLanguage())// A muted call stays muted on the engine that takes over (what the call last showed).val muted = call.state.value.muted- val operator = CallOperator(call.botId, object : CallTarget {- override val bots get() = state.value.bots- override val entries get() = state.value.entries- override fun send(text: String) = sendFromCall(call, text)- override fun respond(entry: Entry, optionId: String) = [email protected](entry, optionId)- })+ val link = call.link(this)call.recording = { null }val kind = when {provider == null -> VoiceEngineKind.OnDevice@@ -83,14 +81,15 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {val engine: VoiceEngine = if (provider == null) {val audio = LocalVoiceAudio(getApplication(), VoicePreferences.language(getApplication()))call.recording = { audio.recordingSessionId }+ startCallOnHost(call, "device", null)VoiceSession(contextScope, audio, settings) { sendFromCall(call, it) }} else {val voice = choices.voice(provider)val model = choices.model(provider, VoiceChoices.Model.Realtime)- val credential: suspend () -> String = { voiceSession(provider, model, voice) }fun mic() = AndroidMic(getApplication()).also { mic -> call.recording = { mic.recordingSessionId } }when {choices.speechMode(provider) -> {+ startCallOnHost(call, "speech", provider)val transcribe = choices.model(provider, VoiceChoices.Model.Transcribe)val speech = choices.model(provider, VoiceChoices.Model.Speech)CloudSpeechEngine(contextScope, provider, settings, mic(), AndroidClipPlayer, CloudSpeechEngine.Speech(@@ -99,10 +98,11 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {send = { sendFromCall(call, it) }))}// WebRTC records the microphone itself.- provider == VoiceProvider.OpenAI -> OpenAIRealtimeEngine(contextScope, settings, credential, operator, WebRtcPeer(getApplication())) { secret, offer ->+ provider == VoiceProvider.OpenAI -> OpenAIRealtimeEngine(contextScope, settings, model, voice,+ choices.model(provider, VoiceChoices.Model.Transcribe), link, WebRtcPeer(getApplication())) { secret, offer ->OpenAIRealtimeEngine.answer(voiceHttp, secret, offer)}- else -> GeminiLiveEngine(contextScope, settings, model, voice, credential, operator, mic(), AndroidPcmPlayer(), voiceHttp)+ else -> GeminiLiveEngine(contextScope, settings, model, voice, link, mic(), AndroidPcmPlayer(), voiceHttp)}}call.engine = engine@@ -170,10 +170,10 @@ private fun AppStore.countCloudMinutes(call: VoiceBinding) {voiceChoices().addUsage(provider, (SystemClock.elapsedRealtime() - since) / 1_000)}-/** What you said goes out as an ordinary message, unless the call has moved on. */+/** What you said goes out as the call's message, unless the call has moved on. */private fun AppStore.sendFromCall(call: VoiceBinding, text: String) {if (state.value.generation != call.generation || state.value.voice?.id != call.id || state.value.loading) return- val send = PendingSend(UUID.randomUUID().toString(), call.botId, text, System.currentTimeMillis())+ val send = PendingSend(UUID.randomUUID().toString(), call.botId, text, System.currentTimeMillis(), call = call.id)action("save:" + send.nonce) { savePending(send); deliver(send) }}@@ -201,12 +201,11 @@ internal fun AppStore.finishVoice(id: String, error: String? = null) {contextScope.launch {try {engine?.awaitEnd()- if (call != null && state.value.generation == call.generation && channel?.state?.value is LinkState.Ready) {- val seconds = ((SystemClock.elapsedRealtime() - call.startedAt) / 1_000).coerceAtLeast(0)- withTimeoutOrNull(3_000) { hostQuery("logCall", buildJsonObject { put("botId", call.botId); put("seconds", seconds) }, 3_000, call.generation) }+ if (call != null && state.value.generation == call.generation) {+ call.link?.end(((SystemClock.elapsedRealtime() - call.startedAt) / 1_000).coerceAtLeast(0))}} catch (cancelled: CancellationException) { throw cancelled }- catch (_: Exception) { /* Duration is best effort; an uncertain log is never retried. */ }+ catch (_: Exception) { /* The call's line is best effort once the link is gone. */ }finally { if (!transportRequired) { connectionJob?.cancel(); graceJob?.cancel(); channel?.close() } }}}@@ -251,7 +250,7 @@ internal suspend fun AppStore.voiceStatus(): VoiceStatus = WireJson.decodeFromJsinternal suspend fun AppStore.voiceModels(provider: VoiceProvider): VoiceModels =WireJson.decodeFromJsonElement(hostCall("voiceModels", body("provider" to provider.id), 30_000))-/** A short-lived credential for one call's audio session. */+/** A short-lived credential, which checks a key in the call settings. */internal suspend fun AppStore.voiceSession(provider: VoiceProvider, model: String, voice: String): String =hostCall("voiceSession", body("provider" to provider.id, "model" to model, "voice" to voice), 30_000).jsonObject["credential"]?.jsonPrimitive?.contentOrNull ?: throw IOException("${provider.title} didn't start the call.")diff --git a/apps/android/app/src/main/kotlin/com/codync/android/CallRows.kt b/apps/android/app/src/main/kotlin/com/codync/android/CallRows.ktnew file mode 100644index 00000000..c29b193f--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/CallRows.kt@@ -0,0 +1,90 @@+package com.codync.android++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.itemsIndexed+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.foundation.text.selection.SelectionContainer+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.codync.android.core.CallMessage+import com.codync.android.core.Entry+import com.codync.android.core.callConversation+import com.codync.android.design.*+import com.kyant.shapes.RoundedRectangle+import kotlinx.serialization.json.jsonPrimitive+import kotlinx.serialization.json.longOrNull++/** A voice call's line in the chat (iOS `CallLineRow`): its title, written once the call ends, and length; it opens the call. */+@Composable internal fun CallLineRow(entry: Entry, open: () -> Unit) {+ val title = tr(entry.text.ifEmpty { "Voice chat" })+ val length = entry.data["callSeconds"]?.jsonPrimitive?.longOrNull?.let { " · %02d:%02d".format(it / 60, it % 60) }.orEmpty()+ Row(Modifier.fillMaxWidth().plainButton(action = open).semantics(mergeDescendants = true) { contentDescription = title + length }+ .padding(vertical = 6.dp), verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally)) {+ Symbol("waveform", size = 13.dp, tint = Palette.secondary)+ Text(title, style = Type.footnote, color = Palette.text, maxLines = 1, overflow = TextOverflow.Ellipsis)+ Text(length, style = Type.footnote.monospacedDigit, color = Palette.secondary)+ Symbol("chevron.right", size = 10.dp, tint = Palette.tertiary)+ }+}++/**+ * What a voice call said, oldest first (iOS `CallConversationView`): the user's and the voice's words, and the+ * messages it carried to the bot and back, which the chat itself leaves out.+ */+@Composable internal fun CallConversationView(botId: String, lineId: String, state: AppState) {+ val entries = state.entries.filter { it.botId == botId }+ val line = entries.firstOrNull { it.id == lineId }+ val messages = line?.let { entries.callConversation(it) }.orEmpty()+ val list = rememberLazyListState()+ LaunchedEffect(messages.size) { if (messages.isNotEmpty()) list.scrollToItem(messages.lastIndex) }+ Column(Modifier.fillMaxSize().background(Palette.background)) {+ ModalHeader(tr(line?.text?.ifEmpty { null } ?: "Voice chat"))+ LazyColumn(Modifier.fillMaxSize(), state = list, contentPadding = PaddingValues(start = 16.dp, end = 16.dp, bottom = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)) {+ if (messages.isEmpty()) item("empty") {+ Text(tr("Nothing was said on this call."), Modifier.fillMaxWidth().padding(top = 24.dp), style = Type.footnote,+ color = Palette.tertiary, textAlign = TextAlign.Center)+ }+ itemsIndexed(messages) { _, message -> CallMessageRow(message) }+ }+ }+}++@Composable private fun CallMessageRow(message: CallMessage) {+ when (message.speaker) {+ CallMessage.Speaker.User -> Box(Modifier.fillMaxWidth().padding(start = 40.dp), contentAlignment = Alignment.CenterEnd) {+ SelectionContainer {+ Text(message.text, Modifier.clip(RoundedRectangle(18.dp)).background(Palette.bubbleUser).padding(horizontal = 14.dp, vertical = 9.dp),+ style = Type.body, color = Palette.text)+ }+ }+ CallMessage.Speaker.Voice -> SelectionContainer {+ Text(message.text, Modifier.fillMaxWidth().padding(end = 40.dp), style = Type.body, color = Palette.secondary)+ }+ CallMessage.Speaker.VoiceToBot -> SelectionContainer { Text("↳ " + message.text, style = Type.footnote, color = Palette.secondary) }+ CallMessage.Speaker.Bot -> Box(Modifier.fillMaxWidth().padding(end = 40.dp), contentAlignment = Alignment.CenterStart) {+ Box(Modifier.clip(RoundedRectangle(22.dp)).background(Palette.bubbleAgent).padding(horizontal = 16.dp, vertical = 10.dp)) {+ MarkdownText(message.text)+ }+ }+ }+}diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.ktindex 8c7385e4..a06ba86c 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ChatScreen.kt@@ -79,6 +79,8 @@ import com.kyant.shapes.Capsulevar viewing by remember(bot.id) { mutableStateOf<OpenArtifact?>(null) }// The bot whose conversation with this one is open.var peer by remember(bot.id) { mutableStateOf<String?>(null) }+ /** The voice call whose conversation is open (its line's entry id). */+ var callLine by remember(bot.id) { mutableStateOf<String?>(null) }var micDenied by remember { mutableStateOf(false) }var setupEntry by rememberSaveable { mutableStateOf<String?>(null) }var app by remember { mutableStateOf<ComposioApp?>(null) }@@ -118,7 +120,7 @@ import com.kyant.shapes.Capsule}) {Transcript(bot, chatState, store, connect, PaddingValues(start = 16.dp, end = 16.dp, top = top + 60.dp,bottom = with(density) { composerHeight.toDp() } + 8.dp), indicatorTop = top + 50.dp, openRoutine = openRoutine, reply = reply,- addFallback = { details = DetailsRequest(botId = it.id) }, openArtifact = { viewing = it }) { peer = it }+ addFallback = { details = DetailsRequest(botId = it.id) }, openArtifact = { viewing = it }, openCall = { callLine = it }) { peer = it }}CodyncDialog("Microphone access is off", micDenied, { micDenied = false },message = "Allow the microphone in Android settings to talk to your bot.") {@@ -136,6 +138,7 @@ import com.kyant.shapes.Capsulestate.bots.firstOrNull { it.id == open.botId }?.let { owner -> ArtifactViewer(open, owner, state, store) { viewing = null } }}CodyncSheet(peer, { peer = null }) { BotConversationView(bot, it, state, store) }+ CodyncSheet(callLine, { callLine = null }) { CallConversationView(bot.id, it, state) }CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }}@@ -195,9 +198,11 @@ import com.kyant.shapes.Capsule/** The messages: all this phone has, earlier ones from the computer near the top, following the newest. */@Composable private fun Transcript(bot: Bot, state: AppState, store: AppStore, connect: ConnectionRequestActions, padding: PaddingValues,indicatorTop: Dp, openRoutine: (String) -> Unit, reply: (Entry) -> Unit, addFallback: (Bot) -> Unit, openArtifact: (OpenArtifact) -> Unit,- openPeer: (String) -> Unit) {- val entries = state.entries.filter { it.botId == bot.id && it.isChat }- val pending = state.pending.filter { it.botId == bot.id }+ openCall: (String) -> Unit, openPeer: (String) -> Unit) {+ // What voice calls carried shows in each call's conversation, not in the chat.+ val entries = state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls(setOfNotNull(state.voice?.id))+ // A call's message that failed to send stays here, to be sent again.+ val pending = state.pending.filter { it.botId == bot.id && (it.call == null || it.status == SendStatus.Failed) }val items = chatItems(entries, pending)val working = bot.isWorking(bot.id) && state.connection is LinkState.Readyval more = bot.id !in state.historyComplete@@ -218,6 +223,9 @@ import com.kyant.shapes.Capsuleval routine = item.entry.data.text("routineId").takeIf { item.entry.kind == "notice" }if (routine != null) RoutineNotice(item.entry, retrying = "retry:" + item.entry.id in state.busy,retry = { store.retryRoutineRun(item.entry) }) { openRoutine(routine) }+ else if (item.entry.kind == "notice" && item.entry.call != null) Box(Modifier.padding(top = 6.dp)) {+ CallLineRow(item.entry) { openCall(item.entry.id) }+ }else ChatRow(item.entry, item.groupStart, bot, state, store, openTrace = { store.showTrace(true) },// An update card takes the composer's place, so there's nothing to reply with.reply = if (item.entry.isReplyable && state.mismatch == null) { { reply(item.entry) } } else null, connect = connect,diff --git a/apps/android/app/src/main/kotlin/com/codync/android/HostCallLink.kt b/apps/android/app/src/main/kotlin/com/codync/android/HostCallLink.ktnew file mode 100644index 00000000..c8d6739e--- /dev/null+++ b/apps/android/app/src/main/kotlin/com/codync/android/HostCallLink.kt@@ -0,0 +1,92 @@+package com.codync.android++import com.codync.android.core.*+import kotlinx.coroutines.*+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.serialization.json.*++/** How long a tool call waits for the user's words that are still being written down. */+private const val HEARING_PATIENCE_MS = 2_000L+/** Tries at a call's line while the link comes back. */+private const val END_TRIES = 3++/** The computer keeps a call though it carries no voice model (on-device or speech to text). */+internal fun AppStore.startCallOnHost(call: VoiceBinding, mode: String, provider: VoiceProvider?) {+ contextScope.launch {+ try { hostCall("startCall", buildJsonObject {+ put("botId", call.botId); put("callId", call.id); put("mode", mode); provider?.let { put("provider", it.id) }+ put("language", java.util.Locale.getDefault().toLanguageTag())+ }, 30_000) } catch (cancelled: CancellationException) { throw cancelled } catch (_: Exception) { }+ }+}++/** The call as the computer runs it, made once per call (it outlives an engine switch). */+internal fun VoiceBinding.link(store: AppStore): HostCallLink = link ?: HostCallLink(store, this).also { link = it }++/**+ * [CallLink] over the computer's call methods (`startCall`, `callTool`, `callLines`, `endCall`; iOS `CallLink`). The+ * computer gets what was said, the tool calls and the end one at a time, in order: a hand-off never overtakes the+ * words it hands on, and lines it didn't get go out with the next request.+ */+internal class HostCallLink(private val store: AppStore, private val call: VoiceBinding) : CallLink {+ private val transcript = CallTranscript(script = ::inReadersScript) { flush() }+ private val order = Mutex()+ /** The user's last words are still being written down (OpenAI transcribes them after the turn). */+ private var hearing = false++ override suspend fun start(provider: VoiceProvider, model: String, voice: String): CallSession =+ CallSession.decode(store.hostCall("startCall", buildJsonObject {+ put("botId", call.botId); put("callId", call.id); put("mode", "realtime"); put("provider", provider.id)+ put("model", model); put("voice", voice); put("language", java.util.Locale.getDefault().toLanguageTag())+ }, 30_000).jsonObject)++ override suspend fun tool(name: String, arguments: JsonObject): JsonElement {+ withTimeoutOrNull(HEARING_PATIENCE_MS) { while (hearing) delay(100) }+ return order.withLock {+ val lines = transcript.drain(withOpen = true)+ try {+ store.hostCall("callTool", buildJsonObject {+ put("callId", call.id); put("name", name); put("arguments", arguments); put("lines", WireJson.encodeToJsonElement(lines))+ }, 60_000).jsonObject["result"] ?: JsonObject(emptyMap())+ } catch (cancelled: CancellationException) { transcript.restore(lines); throw cancelled }+ catch (error: Exception) {+ transcript.restore(lines)+ buildJsonObject { put("error", error.message ?: "The computer didn't answer.") }+ }+ }+ }++ override fun add(from: String, piece: String) {+ if (from == "user") hearing = false+ transcript.add(from, piece)+ }+ override fun transcribing(on: Boolean) { hearing = on }+ override fun endTurn() = transcript.endTurn()+ override fun reply(text: String): String =+ "[${store.state.value.bots.firstOrNull { it.id == call.botId }?.name ?: "Bot"} replied] ${SpokenText.from(text)}"++ /** The call is over: its line in the chat, with what's left of the transcript (the computer ends a call once). */+ suspend fun end(seconds: Long) = order.withLock {+ val lines = WireJson.encodeToJsonElement(transcript.drain(withOpen = true))+ val body = buildJsonObject { put("botId", call.botId); put("callId", call.id); put("seconds", seconds); put("lines", lines) }+ for (attempt in 1..END_TRIES) {+ try { store.hostQuery("endCall", body, 20_000, call.generation); return@withLock }+ catch (cancelled: CancellationException) { throw cancelled }+ catch (_: Exception) { if (attempt < END_TRIES) delay(2_000) }+ }+ }++ /** The lines finished so far go to the computer. */+ private fun flush() {+ store.contextScope.launch {+ order.withLock {+ val lines = transcript.drain(withOpen = false)+ if (lines.isEmpty()) return@withLock+ try { store.hostCall("callLines", buildJsonObject { put("callId", call.id); put("lines", WireJson.encodeToJsonElement(lines)) }, 30_000) }+ catch (cancelled: CancellationException) { transcript.restore(lines); throw cancelled }+ catch (_: Exception) { transcript.restore(lines) }+ }+ }+ }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CallOperator.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CallOperator.ktdeleted file mode 100644index e0f3c204..00000000--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CallOperator.kt+++ /dev/null@@ -1,142 +0,0 @@-package com.codync.android.core--import kotlinx.serialization.json.*--/** What a call's operator works against: the app's mirror and its send/approval actions. */-interface CallTarget {- val bots: List<Bot>- val entries: List<Entry>- fun send(text: String)- fun respond(entry: Entry, optionId: String)-}--/** One function the realtime model can call, in JSON Schema form (both providers take the same shape). */-data class CallTool(val name: String, val description: String, val parameters: JsonObject) {- fun openAI(): JsonObject = buildJsonObject {- put("type", "function"); put("name", name); put("description", description); put("parameters", parameters)- }- fun gemini(): JsonObject = buildJsonObject {- put("name", name); put("description", description)- if (parameters["properties"]?.jsonObject?.isNotEmpty() == true) put("parameters", geminiSchema(parameters))- }- /** Gemini's schema spells types in capitals (`OBJECT`, `STRING`). */- private fun geminiSchema(schema: JsonObject): JsonObject = JsonObject(schema.mapValues { (key, value) ->- when {- key == "type" && value is JsonPrimitive -> JsonPrimitive(value.content.uppercase())- key == "properties" && value is JsonObject -> JsonObject(value.mapValues { (_, it) -> (it as? JsonObject)?.let(::geminiSchema) ?: JsonObject(emptyMap()) })- else -> value- }- })-}--/**- * A realtime model is an operator in front of the bot, not a replacement for it (iOS `CallOperator`):- * the bot does the work, the operator talks. Its tools run here against the app; only `send_to_bot`- * messages and the bot's replies become chat entries.- */-class CallOperator(private val botId: String, private val target: CallTarget) {- private val bot: Bot? get() = target.bots.firstOrNull { it.id == botId }-- val instructions: String get() {- val bot = bot- val name = bot?.name ?: "the bot"- val about = if (bot == null || bot.description.isEmpty()) "" else " (${bot.description})"- val who = if (bot?.kind == "group") {- val members = target.bots.filter { it.id in bot.members }.joinToString(", ") { it.name }- "the group chat $name$about on the user's computer, where the bots $members answer in turn " +- "(a message that @-mentions one of them asks just that bot). The bots do all the actual work; you relay"- } else "$name$about, a coding agent running on the user's computer. $name does all the actual work; you relay"- return """- You are the voice on a phone call between the user and $who.- - 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.- """.trimIndent()- }-- /** How a reply is handed to the operator. */- fun reply(text: String): String = "[${bot?.name ?: "Bot"} replied] ${SpokenText.from(text)}"- fun notice(text: String): String = "[Notice] $text"-- /** Runs one tool call; the result goes back to the model as JSON. */- fun call(name: String, arguments: JsonObject): JsonObject = when (name) {- "send_to_bot" -> send(arguments.text("text").orEmpty())- "bot_status" -> status()- "recent_messages" -> recent(arguments["count"]?.jsonPrimitive?.let { it.intOrNull ?: it.doubleOrNull?.toInt() } ?: 6)- "answer_approval" -> answer(arguments.text("option").orEmpty())- else -> error("Unknown tool $name.")- }-- private fun send(text: String): JsonObject {- val message = text.trim()- if (message.isEmpty()) return error("Nothing to send.")- target.send(message)- return buildJsonObject { put("sent", true); put("note", "The bot's reply will arrive as a separate message.") }- }-- private fun status(): JsonObject {- val bot = bot ?: return error("The bot isn't available.")- return buildJsonObject {- put("status", bot.status); put("activity", bot.activity)- pendingApproval?.let { card ->- putJsonObject("approval") {- put("request", card.data.text("title") ?: card.data.text("command") ?: "")- put("options", JsonArray(options(card).map { JsonPrimitive(it.second) }))- }- }- }- }-- private fun recent(count: Int): JsonObject {- val name = bot?.name ?: "bot"- val messages = chat.filter(Entry::isChat).takeLast(count.coerceIn(1, 20)).map { entry ->- val from = when (entry.kind) {- "user" -> "user"- "agent" -> entry.data.text("author")?.let { author -> target.bots.firstOrNull { it.id == author }?.name } ?: name- "permission" -> "approval request"- else -> "notice"- }- buildJsonObject { put("from", from); put("text", SpokenText.from(entry.data.text("text") ?: entry.data.text("title") ?: "")) }- }- return buildJsonObject { put("messages", JsonArray(messages)) }- }-- private fun answer(option: String): JsonObject {- val card = pendingApproval ?: return error("Nothing is waiting for approval.")- val options = options(card)- val wanted = option.lowercase()- val pick = options.firstOrNull { it.second.lowercase() == wanted || it.first == option }- ?: options.firstOrNull { it.second.lowercase().contains(wanted) || wanted.contains(it.second.lowercase()) }- ?: return buildJsonObject { put("error", "No such option."); put("options", JsonArray(options.map { JsonPrimitive(it.second) })) }- target.respond(card, pick.first)- return buildJsonObject { put("answered", pick.second) }- }-- private val chat: List<Entry> get() = target.entries.filter { it.botId == botId }.sortedBy(Entry::seq)- private val pendingApproval: Entry? get() = chat.lastOrNull { it.kind == "permission" && it.status == "pending" }-- /** A permission card's options: id → name. */- private fun options(card: Entry): List<Pair<String, String>> = (card.data["options"] as? JsonArray).orEmpty().mapNotNull { option ->- val fields = option as? JsonObject ?: return@mapNotNull null- val id = fields.text("optionId") ?: return@mapNotNull null- id to (fields.text("name") ?: id)- }-- private fun error(message: String) = buildJsonObject { put("error", message) }-- companion object {- val tools = listOf(- CallTool("send_to_bot", "Send a message to the bot on the computer, exactly as if the user typed it. Its reply arrives later.",- schema { putJsonObject("text") { put("type", "string"); put("description", "The message") } }.withRequired("text")),- CallTool("bot_status", "Whether the bot is idle or working, what it is doing, and any approval it is waiting for.", schema { }),- CallTool("recent_messages", "The latest messages in the chat with the bot, oldest first.",- schema { putJsonObject("count") { put("type", "integer"); put("description", "How many, 1–20") } }),- CallTool("answer_approval", "Answer the bot's pending approval request with one of its options.",- schema { putJsonObject("option") { put("type", "string"); put("description", "The option's name") } }.withRequired("option")),- )- private fun schema(properties: JsonObjectBuilder.() -> Unit) = buildJsonObject { put("type", "object"); putJsonObject("properties", properties) }- private fun JsonObject.withRequired(name: String) = JsonObject(this + ("required" to JsonArray(listOf(JsonPrimitive(name)))))- }-}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Calls.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Calls.ktnew file mode 100644index 00000000..5679c0cd--- /dev/null+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Calls.kt@@ -0,0 +1,128 @@+package com.codync.android.core++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.*++// Voice calls, run by the computer (host/src/chat/calls, iOS `CallLink`): the voice's instructions, tools and+// transcript live there; the engines only carry audio. What a call sends the bot, and the bot's replies while it+// lasts, carry the call's id; the chat shows them only in the call's conversation, which its line opens.++/** What a client needs to run a call's voice, from the computer (`startCall`). */+data class CallSession(val credential: String?, val instructions: String, val tools: List<CallTool>) {+ companion object {+ fun decode(value: JsonObject) = CallSession(+ credential = value.text("credential"),+ instructions = value.text("instructions") ?: throw IllegalStateException("The computer sent no call instructions."),+ tools = (value["tools"] as? JsonArray).orEmpty().mapNotNull { tool ->+ val fields = tool as? JsonObject ?: return@mapNotNull null+ CallTool(fields.text("name") ?: return@mapNotNull null, fields.text("description").orEmpty(),+ fields["parameters"] as? JsonObject ?: buildJsonObject { put("type", "object"); putJsonObject("properties") { } })+ },+ )+ }+}++/** A call as the computer runs it; one per call, so it outlives an engine switch. */+interface CallLink {+ /** Starts the call on the computer (again, when a provider session is replaced): what the voice needs. */+ suspend fun start(provider: VoiceProvider, model: String, voice: String): CallSession+ /** One of the voice's tool calls, run on the computer. A failure is the answer. */+ suspend fun tool(name: String, arguments: JsonObject): JsonElement+ /** A piece of what `from` (`user` or `voice`) said; the pieces of one turn join into one line. */+ fun add(from: String, piece: String)+ /** The user stopped talking and their words are being written down (`true`), or that failed (`false`): a tool+ * call waits a moment for them. */+ fun transcribing(on: Boolean)+ /** The turn is over: what was said goes to the computer. */+ fun endTurn()+ /** How a final reply of the bot reaches the voice. */+ fun reply(text: String): String+ fun notice(text: String): String = "[Notice] $text"+}++/** One function the voice can call, in JSON Schema form; each provider spells it its own way. */+data class CallTool(val name: String, val description: String, val parameters: JsonObject) {+ fun openAI(): JsonObject = buildJsonObject {+ put("type", "function"); put("name", name); put("description", description); put("parameters", parameters)+ }+ fun gemini(): JsonObject = buildJsonObject {+ put("name", name); put("description", description)+ if (parameters["properties"]?.jsonObject?.isNotEmpty() == true) put("parameters", geminiSchema(parameters))+ }+ /** Gemini's schema spells types in capitals (`OBJECT`, `STRING`). */+ private fun geminiSchema(schema: JsonObject): JsonObject = JsonObject(schema.mapValues { (key, value) ->+ when {+ key == "type" && value is JsonPrimitive -> JsonPrimitive(value.content.uppercase())+ key == "properties" && value is JsonObject -> JsonObject(value.mapValues { (_, it) -> (it as? JsonObject)?.let(::geminiSchema) ?: JsonObject(emptyMap()) })+ else -> value+ }+ })+}++/** One line of a call: what the user said (`user`) or the voice answered (`voice`), with when (ms). */+@Serializable data class CallLine(val from: String, val text: String, val at: Long? = null)++/**+ * What was said on a realtime call, the pieces of a turn joined, until it goes to the computer ([drain]); [turnEnded]+ * says a turn is over.+ */+class CallTranscript(private val clock: () -> Long = System::currentTimeMillis, private val script: (String) -> String = { it },+ private val turnEnded: () -> Unit) {+ private val lines = mutableListOf<CallLine>()+ private var open = false++ fun add(from: String, piece: String) {+ if (piece.isEmpty()) return+ val last = lines.lastOrNull()+ if (open && last?.from == from) lines[lines.lastIndex] = last.copy(text = last.text + piece)+ else { endTurn(); lines += CallLine(from, piece, clock()); open = true }+ }++ fun endTurn() { open = false; turnEnded() }++ /** The lines finished so far ([withOpen]: and the one still being said), out of the buffer: trimmed and through+ * [script] (Chinese in the reader's script). */+ fun drain(withOpen: Boolean): List<CallLine> {+ val count = if (open && !withOpen) lines.size - 1 else lines.size+ if (withOpen) open = false+ val taken = lines.take(count.coerceAtLeast(0))+ repeat(taken.size) { lines.removeAt(0) }+ return taken.mapNotNull { line -> script(line.text.trim()).takeIf { it.isNotEmpty() }?.let { line.copy(text = it) } }+ }++ /** Lines the computer didn't get, for the next request. */+ fun restore(said: List<CallLine>) { lines.addAll(0, said) }+}++/** One message of a call's conversation. */+data class CallMessage(val speaker: Speaker, val text: String) {+ enum class Speaker { User, Voice, VoiceToBot, Bot }+}++/** The voice call it was said in (user), answered during (agent), or that it ends (notice). */+val Entry.call: String? get() = data.text("call")++/** Without what voice calls carried: the messages of a call that has its line, or of a call this phone is on. */+fun List<Entry>.hidingCalls(live: Set<String>): List<Entry> {+ val ended = filter { it.kind == "notice" }.mapNotNull { it.call }.toSet()+ return filter { it.kind == "notice" || it.call?.let { call -> call !in ended && call !in live } ?: true }+}++/** A call's conversation, oldest first: what was said (the voice's transcript) and the messages it carried. */+fun List<Entry>.callConversation(line: Entry): List<CallMessage> {+ val call = line.call ?: return emptyList()+ val said = (line.data["transcript"] as? JsonArray).orEmpty().mapNotNull { element ->+ val fields = element as? JsonObject ?: return@mapNotNull null+ val speaker = if (fields.text("from") == "user") CallMessage.Speaker.User else CallMessage.Speaker.Voice+ ((fields["at"] as? JsonPrimitive)?.longOrNull ?: line.createdAt) to CallMessage(speaker, fields.text("text").orEmpty())+ } + filter { it.call == call && (it.kind == "user" || it.kind == "agent" && it.data["final"]?.jsonPrimitive?.booleanOrNull == true) }.map { e ->+ val speaker = when {+ e.kind == "agent" -> CallMessage.Speaker.Bot+ e.data.text("from") == "voice" -> CallMessage.Speaker.VoiceToBot+ else -> CallMessage.Speaker.User+ }+ e.createdAt to CallMessage(speaker, e.text)+ }+ // Stable: phone and computer clocks are merged as they are.+ return said.sortedBy { it.first }.map { it.second }+}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.ktindex 3cc09770..9c8b1bb9 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Compatibility.kt@@ -12,7 +12,7 @@ sealed interface VersionMismatch {companion object {/** The oldest host this app works with; raise it only when a core flow needs something older hosts lack. */- const val MIN_HOST = "2.20.1"+ const val MIN_HOST = "2.25.0"/** An unknown version is never a reason to lock someone out. */fun check(app: String, hostVersion: String?, minApp: String?, minHost: String = MIN_HOST): VersionMismatch? = when {diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.ktindex b548f24b..03da3db3 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Conversation.kt@@ -128,11 +128,14 @@ data class PendingSend(val files: List<OutgoingFile> = emptyList(),/** The message it quotes (`send`'s `replyTo` is its id), shown on the bubble until the computer has it. */val replyTo: ReplyQuote? = null,+ /** The voice call it was said in (on-device or speech to text). */+ val call: String? = null,) {/** The `send` request for it, with the ids of its uploaded files. */fun body(attachments: List<String> = emptyList()): JsonObject = buildJsonObject {put("botId", botId); put("text", text); put("clientNonce", nonce)replyTo?.let { put("replyTo", it.id) }+ call?.let { put("call", it) }if (attachments.isNotEmpty()) put("attachments", JsonArray(attachments.map(::JsonPrimitive)))}}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/GeminiLiveEngine.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/GeminiLiveEngine.ktindex acbfda95..d956052c 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/GeminiLiveEngine.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/GeminiLiveEngine.kt@@ -3,6 +3,7 @@ package com.codync.android.coreimport java.net.URLEncoderimport java.util.Base64import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.launchimport kotlinx.coroutines.flow.updateimport kotlinx.serialization.json.*import okhttp3.OkHttpClient@@ -14,11 +15,12 @@ import okio.ByteString/*** Gemini Live over a WebSocket, phone ↔ Google directly (iOS `GeminiLiveEngine`): 16 kHz PCM up,- * 24 kHz PCM down, echo-cancelled 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.+ * 24 kHz PCM down, echo-cancelled so you can talk over it. The computer runs the call ([CallLink]): it mints one-use+ * ephemeral tokens on the user's key and writes the voice's instructions and tools, again for each session; a session+ * the server ends (`goAway`) is resumed with a fresh one.*/class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, private val model: String, private val voice: String,- private val credential: suspend () -> String, private val operator: CallOperator,+ private val link: CallLink,private val mic: MicSource, private val player: PcmPlayer, private val http: OkHttpClient,private val endpoint: String = ENDPOINT,) : ProviderEngine(parent, VoiceProvider.Gemini, settings, "Gemini Live") {@@ -36,15 +38,19 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, private/** After a local interrupt, the rest of the turn's audio is dropped. */private var dropping = falseprivate val pending = mutableListOf<String>()+ /** The current provider session's instructions and tools, from the computer. */+ private var session: CallSession? = null+ /** Tool calls still running on the computer: replies wait, so the model gets each answer first. */+ private var toolsRunning = 0init { hop { connect() } }override fun speak(markdown: String): Boolean {if (ended) return false- hop { pending += operator.reply(markdown); flush() }+ hop { pending += link.reply(markdown); flush() }return true}- override fun announce(notice: String) = hop { pending += operator.notice(notice); flush() }+ override fun announce(notice: String) = hop { pending += link.notice(notice); flush() }override fun mute(value: Boolean) = hop {if (value == muted) return@hopmutable.update { it.copy(muted = value, level = 0f) }@@ -62,8 +68,10 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, private}private suspend fun connect() {- val token = credential()+ val session = link.start(VoiceProvider.Gemini, model, voice)if (ended) return+ val token = session.credential ?: throw IllegalStateException("Gemini sent no session credential.")+ this.session = sessionready = falseval url = "$endpoint?access_token=" + URLEncoder.encode(token, "UTF-8")socket = http.newWebSocket(Request.Builder().url(url).build(), Listener())@@ -92,10 +100,13 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, privateputJsonArray("responseModalities") { add("AUDIO") }putJsonObject("speechConfig") { putJsonObject("voiceConfig") { putJsonObject("prebuiltVoiceConfig") { put("voiceName", voice) } } }}- putJsonObject("systemInstruction") { putJsonArray("parts") { addJsonObject { put("text", operator.instructions) } } }- putJsonArray("tools") { addJsonObject { put("functionDeclarations", JsonArray(CallOperator.tools.map(CallTool::gemini))) } }+ putJsonObject("systemInstruction") { putJsonArray("parts") { addJsonObject { put("text", session?.instructions.orEmpty()) } } }+ putJsonArray("tools") { addJsonObject { put("functionDeclarations", JsonArray(session?.tools.orEmpty().map(CallTool::gemini))) } }// Audio sessions are otherwise capped at 15 minutes.putJsonObject("contextWindowCompression") { putJsonObject("slidingWindow") { } }+ // What both sides said, for the call's line in the chat.+ putJsonObject("inputAudioTranscription") { }+ putJsonObject("outputAudioTranscription") { }putJsonObject("sessionResumption") { resumeHandle?.let { put("handle", it) } }}}@@ -113,6 +124,9 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, privateflush()}message.objectAt("serverContent")?.let { content ->+ content.objectAt("inputTranscription")?.text("text")?.let { link.add("user", it) }+ content.objectAt("outputTranscription")?.text("text")?.let { link.add("voice", it) }+ if (content.flag("turnComplete") || content.flag("interrupted")) link.endTurn()if (content.flag("interrupted")) {stopPlayback(); dropping = falseif (phase == VoicePhase.Speaking) phase(VoicePhase.Listening)@@ -128,14 +142,24 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, private}}(message.objectAt("toolCall")?.get("functionCalls") as? JsonArray)?.let { calls ->- val responses = calls.mapNotNull { call ->+ val asked = calls.mapNotNull { call ->val fields = call as? JsonObject ?: return@mapNotNull null- val id = fields.text("id") ?: return@mapNotNull null- val name = fields.text("name") ?: return@mapNotNull null- val result = operator.call(name, fields.objectAt("args") ?: JsonObject(emptyMap()))- buildJsonObject { put("id", id); put("name", name); putJsonObject("response") { put("result", result) } }+ Triple(fields.text("id") ?: return@mapNotNull null, fields.text("name") ?: return@mapNotNull null,+ fields.objectAt("args") ?: JsonObject(emptyMap()))+ }+ // The tools run on the computer, outside the inbox; their answers go back together.+ toolsRunning+++ scope.launch {+ val responses = asked.map { (id, name, args) ->+ val result = link.tool(name, args)+ buildJsonObject { put("id", id); put("name", name); putJsonObject("response") { put("result", result) } }+ }+ hop {+ toolsRunning--+ send(buildJsonObject { putJsonObject("toolResponse") { put("functionResponses", JsonArray(responses)) } })+ flush()+ }}- send(buildJsonObject { putJsonObject("toolResponse") { put("functionResponses", JsonArray(responses)) } })}message.objectAt("sessionResumptionUpdate")?.let { update ->if (update.flag("resumable")) update.text("newHandle")?.let { resumeHandle = it }@@ -151,7 +175,7 @@ class GeminiLiveEngine(parent: CoroutineScope, settings: VoiceSettings, private/** Replies wait for the model to finish talking; `turnComplete` here would cut it off. */private fun flush() {- if (!ready || !turnDone || queued != 0 || pending.isEmpty() || phase == VoicePhase.Interrupted) return+ if (!ready || !turnDone || queued != 0 || toolsRunning > 0 || pending.isEmpty() || phase == VoicePhase.Interrupted) returnval text = pending.joinToString("\n\n"); pending.clear()turnDone = falsesend(buildJsonObject {diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/OpenAIRealtimeEngine.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/OpenAIRealtimeEngine.ktindex 8f62f717..7268ee20 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/OpenAIRealtimeEngine.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/OpenAIRealtimeEngine.kt@@ -26,10 +26,11 @@ interface RealtimePeer {/*** OpenAI Realtime over WebRTC, phone ↔ OpenAI directly (iOS `OpenAIRealtimeEngine`): 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.+ * over `oai-events`. The computer runs the call ([CallLink]): it mints the client secret on the user's key and writes+ * the voice's instructions and tools. `transcribe` is the model that writes down what the user says.*/-class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, private val credential: suspend () -> String,- private val operator: CallOperator, private val peer: RealtimePeer,+class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, private val model: String, private val voice: String,+ private val transcribe: String, private val link: CallLink, private val peer: RealtimePeer,private val exchange: suspend (secret: String, offer: String) -> String,) : ProviderEngine(parent, VoiceProvider.OpenAI, settings, "OpenAI Realtime"), RealtimePeer.Events {/** A response is being generated; new replies wait for it to finish. */@@ -37,11 +38,16 @@ class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, priv/** Replies to hand over, and tool results as empty entries (a response is asked for once free). */private val pending = mutableListOf<String>()private var dropTimer: Job? = null+ private var session: CallSession? = null+ /** Tool calls still running on the computer: replies wait, so the model gets each result first. */+ private var toolsRunning = 0init {hop {- val secret = credential()+ val session = link.start(VoiceProvider.OpenAI, model, voice)if (ended) return@hop+ val secret = session.credential ?: throw IOException("OpenAI sent no session credential.")+ this.session = sessionval offer = peer.offer(this)peer.mic(!muted)val answer = exchange(secret, offer)@@ -53,10 +59,10 @@ class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, privoverride fun speak(markdown: String): Boolean {if (ended) return false- hop { pending += operator.reply(markdown); flush() }+ hop { pending += link.reply(markdown); flush() }return true}- override fun announce(notice: String) = hop { pending += operator.notice(notice); flush() }+ override fun announce(notice: String) = hop { pending += link.notice(notice); flush() }override fun mute(value: Boolean) = hop {mutable.update { it.copy(muted = value, level = if (value) 0f else it.level) }if (phase != VoicePhase.Interrupted) peer.mic(!value)@@ -77,9 +83,13 @@ class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, privput("type", "session.update")putJsonObject("session") {put("type", "realtime")- put("instructions", operator.instructions)- put("tools", JsonArray(CallOperator.tools.map(CallTool::openAI)))- putJsonObject("audio") { putJsonObject("input") { putJsonObject("turn_detection") { put("type", "semantic_vad") } } }+ put("instructions", session?.instructions.orEmpty())+ put("tools", JsonArray(session?.tools.orEmpty().map(CallTool::openAI)))+ // What the user says is transcribed too, for the call's line in the chat.+ putJsonObject("audio") { putJsonObject("input") {+ putJsonObject("turn_detection") { put("type", "semantic_vad") }+ putJsonObject("transcription") { put("model", transcribe) }+ } }}})}@@ -91,21 +101,33 @@ class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, priv"session.updated" -> if (phase == VoicePhase.Starting) { dropTimer?.cancel(); phase(VoicePhase.Listening); flush() }"input_audio_buffer.speech_started" -> level(if (muted) 0f else .7f)"input_audio_buffer.speech_stopped" -> level(0f)+ "input_audio_buffer.committed" -> link.transcribing(true)+ "conversation.item.input_audio_transcription.failed" -> link.transcribing(false)"output_audio_buffer.started" -> if (phase == VoicePhase.Listening) phase(VoicePhase.Speaking)"output_audio_buffer.stopped", "output_audio_buffer.cleared" -> if (phase == VoicePhase.Speaking) phase(VoicePhase.Listening)"response.created" -> responding = true"response.done" -> { responding = false; flush() }+ "conversation.item.input_audio_transcription.completed" -> { link.add("user", message.text("transcript").orEmpty()); link.endTurn() }+ "response.output_audio_transcript.done" -> { link.add("voice", message.text("transcript").orEmpty()); link.endTurn() }"response.function_call_arguments.done" -> {val id = message.text("call_id") ?: return@hopval name = message.text("name") ?: return@hopval arguments = message.text("arguments")?.let { runCatching { WireJson.parseToJsonElement(it).jsonObject }.getOrNull() }- val output = operator.call(name, arguments ?: JsonObject(emptyMap()))- send(buildJsonObject {- put("type", "conversation.item.create")- putJsonObject("item") { put("type", "function_call_output"); put("call_id", id); put("output", output.toString()) }- })- // An empty entry asks for a response once this one is done, so the model speaks the result.- pending += ""+ // The tool runs on the computer, outside the inbox.+ toolsRunning+++ scope.launch {+ val output = link.tool(name, arguments ?: JsonObject(emptyMap()))+ hop {+ toolsRunning--+ send(buildJsonObject {+ put("type", "conversation.item.create")+ putJsonObject("item") { put("type", "function_call_output"); put("call_id", id); put("output", output.toString()) }+ })+ // An empty entry asks for a response once this one is done, so the model speaks the result.+ pending += ""+ flush()+ }+ }}}}@@ -133,7 +155,7 @@ class OpenAIRealtimeEngine(parent: CoroutineScope, settings: VoiceSettings, priv/** Hands waiting replies (and tool results, as empty entries) to the model once it's free. */private fun flush() {- if (responding || !active || !peer.isOpen || pending.isEmpty()) return+ if (responding || toolsRunning > 0 || !active || !peer.isOpen || pending.isEmpty()) returnfor (text in pending) if (text.isNotEmpty()) send(buildJsonObject {put("type", "conversation.item.create")putJsonObject("item") {diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.ktindex 8da2af70..923850c3 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CompatibilityTest.kt@@ -7,8 +7,8 @@ class CompatibilityTest {@Test fun `each side names the oldest version of the other`() {assertNull(VersionMismatch.check("2.17.5-dev", null, "9.0.0"))assertEquals(VersionMismatch.UpdateApp("2.18.0"), VersionMismatch.check("2.17.5-dev", "2.18.0", "2.18.0"))- assertEquals(VersionMismatch.UpdateHost("2.20.0", "2.20.1"), VersionMismatch.check("2.20.1", "2.20.0", "2.3.0"))- assertNull(VersionMismatch.check("2.20.1", "2.20.1", "2.3.0"))+ assertEquals(VersionMismatch.UpdateHost("2.24.0", "2.25.0"), VersionMismatch.check("2.25.0", "2.24.0", "2.3.0"))+ assertNull(VersionMismatch.check("2.25.0", "2.25.0", "2.3.0"))assertTrue(AppVersion.isBelow("2.9.3", "2.14.1"))assertFalse(AppVersion.isBelow("garbled", "2.14.1"))}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceEnginesTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceEnginesTest.ktindex 3525a923..b2d6805b 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceEnginesTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/VoiceEnginesTest.kt@@ -88,47 +88,51 @@ class VoiceEnginesTest {assertEquals(1f, Pcm.level(ShortArray(4) { Short.MAX_VALUE }, 4), .01f); assertEquals(0f, Pcm.level(ShortArray(4), 4))}- private class Desk(override val bots: List<Bot>, override var entries: List<Entry>) : CallTarget {- val sent = mutableListOf<String>(); val answered = mutableListOf<Pair<String, String>>()- override fun send(text: String) { sent += text }- override fun respond(entry: Entry, optionId: String) { answered += entry.id to optionId }+ /** The computer's side of a call, for the engines' tests: one session, tools answered here. */+ private class Link(val credential: String = "ek_secret") : CallLink {+ val tools = mutableListOf<Pair<String, JsonObject>>(); val lines = mutableListOf<Pair<String, String>>(); var turns = 0+ var started: Triple<VoiceProvider, String, String>? = null+ override suspend fun start(provider: VoiceProvider, model: String, voice: String): CallSession {+ started = Triple(provider, model, voice)+ return CallSession.decode(Json.parseToJsonElement("""{"credential":"$credential","instructions":"You are the voice relay for Ada",+ "tools":[{"name":"send_to_bot","description":"Send","parameters":{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}},+ {"name":"bot_status","description":"Status","parameters":{"type":"object","properties":{}}}]}""").jsonObject)+ }+ override suspend fun tool(name: String, arguments: JsonObject): JsonElement {+ tools += name to arguments+ return buildJsonObject { if (name == "bot_status") put("status", "idle") else put("sent", true) }+ }+ override fun add(from: String, piece: String) { lines += from to piece }+ override fun transcribing(on: Boolean) { }+ override fun endTurn() { turns++ }+ override fun reply(text: String) = "[Ada replied] ${SpokenText.from(text)}"}private fun entry(id: String, seq: Long, kind: String, data: JsonObjectBuilder.() -> Unit, bot: String = "ada") =Entry(id, seq, bot, seq, kind, data = buildJsonObject(data))- private val card = entry("card", 4, "permission", {- put("status", "pending"); put("title", "Run npm test")- putJsonArray("options") {- addJsonObject { put("optionId", "allow_once"); put("name", "Allow once"); put("kind", "allow_once") }- addJsonObject { put("optionId", "reject"); put("name", "Deny"); put("kind", "reject_once") }- }- })- @Test fun theOperatorRelaysToTheBotAndAnswersApprovalsByName() {- val desk = Desk(listOf(Bot("ada", "Ada", description = "web app", status = "working", activity = "Running tests")), listOf(- entry("u", 1, "user", { put("text", "Run the tests") }),- entry("a", 2, "agent", { put("text", "**Started** `npm test`"); put("final", true) }), card))- val operator = CallOperator("ada", desk)- assertTrue(operator.instructions.startsWith("You are the voice on a phone call between the user and Ada (web app), a coding agent"))- assertTrue("[Ada replied]" in operator.instructions)- assertEquals("Nothing to send.", operator.call("send_to_bot", buildJsonObject { put("text", " ") })["error"]?.jsonPrimitive?.content)- operator.call("send_to_bot", buildJsonObject { put("text", " Fix the build ") }); assertEquals(listOf("Fix the build"), desk.sent)- val status = operator.call("bot_status", JsonObject(emptyMap()))- assertEquals("Run npm test", status["approval"]!!.jsonObject["request"]!!.jsonPrimitive.content)- val messages = operator.call("recent_messages", buildJsonObject { put("count", 2.0) })["messages"]!!.jsonArray- assertEquals(listOf("ada" to "Started npm test", "approval request" to "Run npm test"),- messages.map { it.jsonObject["from"]!!.jsonPrimitive.content.lowercase() to it.jsonObject["text"]!!.jsonPrimitive.content })- assertEquals("Allow once", operator.call("answer_approval", buildJsonObject { put("option", "allow") })["answered"]?.jsonPrimitive?.content)- assertEquals(listOf("card" to "allow_once"), desk.answered)- assertEquals(2, operator.call("answer_approval", buildJsonObject { put("option", "maybe") })["options"]!!.jsonArray.size)- assertEquals("Unknown tool shell.", operator.call("shell", JsonObject(emptyMap()))["error"]?.jsonPrimitive?.content)- assertEquals("[Ada replied] Done", operator.reply("**Done**")); assertEquals("[Notice] Hi", operator.notice("Hi"))- val group = CallOperator("team", Desk(listOf(Bot("team", "Team", kind = "group", members = listOf("ada", "bo")), Bot("ada", "Ada"), Bot("bo", "Bo")), emptyList()))- assertTrue("the group chat Team on the user's computer, where the bots Ada, Bo answer in turn" in group.instructions)- val declarations = CallOperator.tools.map(CallTool::gemini)+ @Test fun aCallsTranscriptJoinsEachTurnAndItsMessagesHideBehindItsLine() {+ var now = 0L+ val transcript = CallTranscript({ ++now }, { it.uppercase() }) { }+ transcript.add("user", "看一下 "); transcript.add("user", "git"); transcript.add("voice", " Checking.")+ assertEquals("the line being said stays", listOf(CallLine("user", "看一下 GIT", 1)), transcript.drain(withOpen = false))+ transcript.restore(listOf(CallLine("user", "AGAIN", 0)))+ assertEquals(listOf(CallLine("user", "AGAIN", 0), CallLine("voice", "CHECKING.", 2)), transcript.drain(withOpen = true))+ assertTrue(transcript.drain(withOpen = true).isEmpty())++ val line = entry("n1", 9, "notice", { put("text", "Git"); put("callSeconds", 26); put("call", "c")+ putJsonArray("transcript") { addJsonObject { put("from", "user"); put("text", "看一下 git"); put("at", 1) } } })+ val entries = listOf(+ entry("u1", 2, "user", { put("text", "check git"); put("call", "c"); put("from", "voice") }),+ entry("a1", 3, "agent", { put("text", "Clean"); put("final", true); put("call", "c") }),+ entry("u2", 4, "user", { put("text", "on this phone"); put("call", "live") }),+ entry("x1", 5, "user", { put("text", "typed") }), line,+ ).map { it.copy(createdAt = it.seq) }+ assertEquals(listOf("x1", "n1"), entries.hidingCalls(setOf("live")).map(Entry::id))+ assertEquals(listOf("User: 看一下 git", "VoiceToBot: check git", "Bot: Clean"),+ entries.callConversation(line).map { "${it.speaker}: ${it.text}" })+ val declarations = runBlocking { Link().start(VoiceProvider.Gemini, "m", "v") }.tools.map(CallTool::gemini)assertNull(declarations.first { it["name"]!!.jsonPrimitive.content == "bot_status" }["parameters"])- assertEquals("OBJECT", declarations[0]["parameters"]!!.jsonObject["type"]!!.jsonPrimitive.content)assertEquals("STRING", declarations[0]["parameters"]!!.jsonObject["properties"]!!.jsonObject["text"]!!.jsonObject["type"]!!.jsonPrimitive.content)- assertEquals("function", CallOperator.tools[0].openAI()["type"]!!.jsonPrimitive.content)}private class Mic : MicSource {@@ -189,8 +193,8 @@ class VoiceEnginesTest {}@Test fun openAIRealtimeRelaysRepliesOneResponseAtATimeAndRunsTools() = runTest {- val peer = Peer(); val desk = Desk(listOf(Bot("ada", "Ada")), emptyList()); var exchanged: Pair<String, String>? = null- val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), { "ek_secret" }, CallOperator("ada", desk), peer) { secret, offer ->+ val peer = Peer(); val link = Link(); var exchanged: Pair<String, String>? = null+ val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), "gpt-realtime", "marin", "gpt-transcribe", link, peer) { secret, offer ->exchanged = secret to offer; "answer-sdp" }runCurrent()assertEquals("ek_secret" to "offer-sdp", exchanged); assertEquals("answer-sdp", peer.answer); assertEquals(true, peer.micOn)@@ -205,7 +209,7 @@ class VoiceEnginesTest {assertEquals(3, peer.sent.size)peer.events!!.received("""{"type":"response.function_call_arguments.done","call_id":"c1","name":"send_to_bot","arguments":"{\"text\":\"Ship it\"}"}""")peer.events!!.received("""{"type":"response.done"}"""); runCurrent()- assertEquals(listOf("Ship it"), desk.sent)+ assertEquals(listOf("send_to_bot" to "Ship it"), link.tools.map { it.first to it.second["text"]!!.jsonPrimitive.content })assertEquals(listOf("function_call_output", "message"), peer.sent.drop(3).dropLast(1).map { it["item"]!!.jsonObject["type"]!!.jsonPrimitive.content })assertEquals("response.create", peer.types().last())peer.events!!.received("""{"type":"output_audio_buffer.started"}"""); runCurrent()@@ -221,14 +225,14 @@ class VoiceEnginesTest {@Test fun openAIRealtimeGivesUpWhenTheChannelNeverOpens() = runTest {val peer = Peer()- val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), { "ek" }, CallOperator("ada", Desk(emptyList(), emptyList())), peer) { _, _ -> "sdp" }+ val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), "gpt-realtime", "marin", "gpt-transcribe", Link("ek"), peer) { _, _ -> "sdp" }advanceTimeBy(15_001); runCurrent(); engine.awaitEnd()assertEquals(VoicePhase.Failed, engine.state.value.phase); assertEquals("Couldn't reach OpenAI.", engine.state.value.error)}@Test fun openAIRealtimeStartTimerOutlastsIceUntilTheSessionIsSetUp() = runTest {val peer = Peer()- val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), { "ek" }, CallOperator("ada", Desk(emptyList(), emptyList())), peer) { _, _ -> "sdp" }+ val engine = OpenAIRealtimeEngine(backgroundScope, VoiceSettings(), "gpt-realtime", "marin", "gpt-transcribe", Link("ek"), peer) { _, _ -> "sdp" }runCurrent(); peer.isOpen = true; peer.events!!.opened()peer.events!!.ice(RealtimePeer.Ice.Disconnected); advanceTimeBy(5_001); runCurrent()assertEquals(VoicePhase.Starting, engine.state.value.phase) // No 5 s drop timer while starting.@@ -266,9 +270,9 @@ class VoiceEnginesTest {}))val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()val scope = CoroutineScope(SupervisorJob() + dispatcher)- val mic = Mic(); val player = Player(); val desk = Desk(listOf(Bot("ada", "Ada", status = "idle")), emptyList())+ val mic = Mic(); val player = Player(); val link = Link("token/1")val endpoint = mock.url("/live").toString().replace("http://", "ws://")- val engine = GeminiLiveEngine(scope, VoiceSettings(), "gemini-live-test", "Puck", { "token/1" }, CallOperator("ada", desk), mic, player,+ val engine = GeminiLiveEngine(scope, VoiceSettings(), "gemini-live-test", "Puck", link, mic, player,OkHttpClient(), endpoint)fun next() = requireNotNull(inbound.poll(5, TimeUnit.SECONDS)) { "Nothing arrived" }suspend fun until(check: (VoiceState) -> Boolean) = withTimeout(5_000) { engine.state.first(check) }@@ -277,7 +281,9 @@ class VoiceEnginesTest {val setup = next()["setup"]!!.jsonObjectassertEquals("models/gemini-live-test", setup["model"]!!.jsonPrimitive.content)assertEquals("Puck", setup["generationConfig"]!!.jsonObject["speechConfig"]!!.jsonObject["voiceConfig"]!!.jsonObject["prebuiltVoiceConfig"]!!.jsonObject["voiceName"]!!.jsonPrimitive.content)- assertEquals(4, setup["tools"]!!.jsonArray[0].jsonObject["functionDeclarations"]!!.jsonArray.size)+ assertEquals(2, setup["tools"]!!.jsonArray[0].jsonObject["functionDeclarations"]!!.jsonArray.size)+ assertEquals("You are the voice relay for Ada", setup["systemInstruction"]!!.jsonObject["parts"]!!.jsonArray[0].jsonObject["text"]!!.jsonPrimitive.content)+ assertTrue("inputAudioTranscription" in setup && "outputAudioTranscription" in setup)engine.speak("Queued before setup")server!!.send("""{"setupComplete":{}}""")assertEquals("[Ada replied] Queued before setup", next()["clientContent"]!!.jsonObject["turns"]!!.jsonArray[0].jsonObject["parts"]!!.jsonArray[0].jsonObject["text"]!!.jsonPrimitive.content)diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex a2b7152f..4a403e1e 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -172,8 +172,9 @@ export class HostClient {/** `pasted`: what the user pasted rather than typed, which memory never takes as their own words. `replyTo`: the* chat message this one replies to. */- async send(botId: string, text: string, clientNonce: string, attachments: string[] | null, pasted: string[] = [], replyTo: string | null = null) {- return (await this.call<{ entry: Entry }>('send', { botId, text, clientNonce, attachments, ...(pasted.length ? { pasted } : {}), ...(replyTo ? { replyTo } : {}) })).entry+ /** `call`: the voice call it was said in (on-device or speech to text). */+ async send(botId: string, text: string, clientNonce: string, attachments: string[] | null, pasted: string[] = [], replyTo: string | null = null, call: string | null = null) {+ return (await this.call<{ entry: Entry }>('send', { botId, text, clientNonce, attachments, ...(pasted.length ? { pasted } : {}), ...(replyTo ? { replyTo } : {}), ...(call ? { call } : {}) })).entry}/** Bytes per `upload` call: base64 of it stays well under the channel's 1 MiB message. */diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 3b613fd6..3c962aab 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -12,6 +12,7 @@ import {type ScreenState,type Usage,} from '@shared/models'+import type { CallLine } from '@shared/calls'import type { HostClient } from '../client/host-client'import { FileDownloads } from './file-downloads'import { BotSync, sleep } from './bot-sync'@@ -31,6 +32,8 @@ export interface SendOptions {nonce?: stringpasted?: string[]replyTo?: ReplyQuote | null+ /** The voice call it was said in. */+ call?: string | null}/** Anything larger is refused by the computer. */@@ -49,10 +52,11 @@ export class BotStore extends BotSync {private outgoingFiles = new Map<string, OutgoingFile[]>()- send(text: string, botId: string, { files = [], nonce = crypto.randomUUID(), pasted = [], replyTo = null }: SendOptions = {}) {+ send(text: string, botId: string, { files = [], nonce = crypto.randomUUID(), pasted = [], replyTo = null, call = null }: SendOptions = {}) {const trimmed = text.trim()if ((!trimmed && !files.length) || this.retired) returnconst data: Entry['data'] = { text: trimmed, status: 'sending', clientNonce: nonce }+ if (call) data.call = callif (replyTo) data.replyTo = replyToif (files.length) {data.attachments = files.map((f) => ({ id: f.id, name: f.name, size: f.data.length }))@@ -78,7 +82,7 @@ export class BotStore extends BotSync {ids.push(id)}}- return client.send(botId, trimmed, nonce, ids, pasted, replyTo?.id ?? null)+ return client.send(botId, trimmed, nonce, ids, pasted, replyTo?.id ?? null, call)}, true)this.outgoingFiles.delete(nonce)this.upsert(e)@@ -144,8 +148,25 @@ export class BotStore extends BotSync {this.perform((c) => c.call('switchBack', { botId }), true)}- logCall(botId: string, seconds: number) {- this.perform((c) => c.call('logCall', { botId, seconds }))+ /** The calls this window is on: what they carry stays out of the chat until their line arrives (`hidingCalls`). */+ readonly liveCalls = new Set<string>()++ beginCall(call: string) {+ this.liveCalls.add(call)+ this.changed()+ }++ /** A finished call's line, with the rest of its transcript; the chat then shows the call's messages behind it. */+ async endCall(botId: string, call: string, seconds: number, lines: CallLine[]) {+ try {+ // Safe to repeat: the computer ends a call once.+ const { entry } = await this.withLink((c) => c.call<{ entry: Entry | null }>('endCall', { botId, callId: call, seconds, lines }), true)+ if (entry) this.upsert(entry)+ } catch (error) {+ this.lastError = error instanceof Error ? error.message : String(error)+ }+ this.liveCalls.delete(call)+ this.changed()}/** A call's audio is live: the lead speaks first (only a host with leads marks one, so an older host never gets this). */diff --git a/apps/desktop/src/renderer/views/call/CallRows.tsx b/apps/desktop/src/renderer/views/call/CallRows.tsxnew file mode 100644index 00000000..decdced6--- /dev/null+++ b/apps/desktop/src/renderer/views/call/CallRows.tsx@@ -0,0 +1,79 @@+import { callConversation, type CallMessage } from '@shared/calls'+import type { Entry } from '@shared/models'+import { useEffect, useRef } from 'react'+import { Icon } from '../../components/Icon'+import { ModalHeader } from '../../components/Overlay'+import { VStack } from '../../components/Stack'+import { Text } from '../../components/Text'+import { useTr } from '../../lib/use-language'+import { useStore } from '../../store/context'+import { Bubble } from '../thread/ChatRows'+import { MarkdownText } from '../thread/Markdown'+import '../thread/bot-conversation.css'++const length = (seconds?: number) =>+ seconds === undefined ? '' : ` · ${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`++/** A voice call's line in the chat: its title (written once the call ends) and length; it opens the call. */+export function CallLineRow({ entry, open }: { entry: Entry; open: () => void }) {+ const tr = useTr()+ const title = tr(entry.data.text || 'Voice chat')+ return (+ <button className="press call-line-row" onClick={open} title={tr('Open the call')} aria-label={`${title}${length(entry.data.callSeconds)}`}>+ <Icon name="waveform" size={10} color="var(--secondary)" />+ <Text size="footnote" tone="text" truncate>{title}</Text>+ <Text size="footnote" tone="secondary" tabular>{length(entry.data.callSeconds)}</Text>+ <Icon name="chevron.right" size={10} color="var(--tertiary)" />+ </button>+ )+}++/**+ * What a voice call said, oldest first: the user's and the voice's words, and the messages it carried to the bot+ * and back, which the chat itself leaves out.+ */+export function CallConversationView({ botId, lineId }: { botId: string; lineId: string }) {+ const tr = useTr()+ const store = useStore()+ const entries = store.allEntries(botId)+ const line = entries.find((e) => e.id === lineId)+ const messages = line ? callConversation(entries, line) : []+ const scroller = useRef<HTMLDivElement>(null)+ useEffect(() => {+ const el = scroller.current+ if (el) el.scrollTop = el.scrollHeight+ }, [messages.length])+ return (+ <div className="bot-conversation">+ <ModalHeader title={tr(line?.data.text || 'Voice chat')} />+ <div className="bot-conversation-scroll" ref={scroller}>+ <VStack gap={10} className="bot-conversation-rows">+ {messages.length === 0 ? <Text as="div" size="footnote" tone="tertiary" className="bot-conversation-note">{tr('Nothing was said on this call.')}</Text> : null}+ {messages.map((m, i) => <CallMessageRow key={i} message={m} />)}+ </VStack>+ </div>+ </div>+ )+}++function CallMessageRow({ message }: { message: CallMessage }) {+ const copy = () => [{ title: 'Copy', icon: 'square.on.square', action: () => window.codync.app.copy(message.text) }]+ switch (message.speaker) {+ case 'user':+ return (+ <div className="message user">+ <div className="message-body"><Bubble className="bubble user selectable" items={copy}><Text>{message.text}</Text></Bubble></div>+ </div>+ )+ case 'voice':+ return <Text as="div" tone="secondary" className="selectable">{message.text}</Text>+ case 'voiceToBot':+ return <Text as="div" size="footnote" tone="secondary" className="selectable">↳ {message.text}</Text>+ case 'bot':+ return (+ <div className="message agent">+ <div className="message-body"><Bubble className="bubble agent selectable" items={copy}><MarkdownText text={message.text} /></Bubble></div>+ </div>+ )+ }+}diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsxindex 10b62189..20c2daa6 100644--- a/apps/desktop/src/renderer/views/call/CallView.tsx+++ b/apps/desktop/src/renderer/views/call/CallView.tsx@@ -13,7 +13,7 @@ import { useStore } from '../../store/context'import { VoiceChatSettingsView } from '../settings/VoiceChatSettingsView'import { voiceStatus } from '../settings/voice-settings'import { stopDictation } from '../thread/dictation'-import { CallOperator } from './call-operator'+import { CallLink } from './call-link'import { CloudSpeechEngine } from './CloudSpeechEngine'import { GeminiLiveEngine } from './GeminiLiveEngine'import { OnDeviceEngine } from './OnDeviceEngine'@@ -30,8 +30,9 @@ export const OpenVoiceSettings = createContext<(() => void) | null>(null)/*** A voice call with a bot, as Grok Bot does it: a floating bar over the chat, which stays- * readable underneath. What you say goes out as ordinary messages, its final replies are read- * aloud, and the chat gets a "Voice chat · 00:16" line when the call ends.+ * readable underneath. The computer runs the call (`CallLink`): what you say reaches the bot as+ * the call's messages, its final replies are read aloud, and the call ends as one titled line+ * ("Release plan · 00:16") that opens its conversation.*/export function CallView({ botId, onSpeaking, interrupt, onEnd }: {botId: string@@ -59,6 +60,9 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {const counted = useRef(false)const bot = store.bots.get(botId)const color = bot ? avatarColor(bot.avatarColor) : null+ /** The call on the computer, which runs it. */+ const link = useRef<CallLink | null>(null)+ link.current ??= new CallLink(store, botId, crypto.randomUUID())const countCloudMinutes = () => {const provider = engine.current?.provider@@ -67,11 +71,6 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {cloudStartedAt.current = null}- const credential = (provider: VoiceProvider, model: string, voice: string) => async () => {- const client = await store.ready()- return (await client.call<{ credential: string }>('voiceSession', { provider, model, voice }, 30_000)).credential- }-/** Starts the engine: a realtime provider on the key kept by the computer, or on-device speech. */const begin = (provider: VoiceProvider | null) => {if (closed.current) return@@ -79,8 +78,8 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {stopDictation()engineChoice.current = VoiceSettings.engineChoice(provider)if (!provider && !onDeviceAvailable()) return void fallbackFromDevice()- const op = new CallOperator(store, botId)- const send = (text: string) => store.send(text, botId)+ const call = link.current!+ const send = (text: string) => store.send(text, botId, { call: call.call })let next: VoiceEngineif (provider && VoiceSettings.isSpeechMode(provider)) {const transcribe = VoiceSettings.transcribeModel(provider)@@ -95,6 +94,8 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {},send,})+ // The computer keeps the call, though it carries no voice model.+ void call.start('speech', provider).catch(() => {})cloudStartedAt.current = Date.now()engineName.current = 'cloud'} else if (provider) {@@ -102,12 +103,13 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {const voice = VoiceSettings.voice(provider)next =provider === 'openai'- ? new OpenAIRealtimeEngine(credential(provider, model, voice), op)- : new GeminiLiveEngine(model, voice, credential(provider, model, voice), op)+ ? new OpenAIRealtimeEngine(model, voice, call)+ : new GeminiLiveEngine(model, voice, call)cloudStartedAt.current = Date.now()engineName.current = provider} else {next = new OnDeviceEngine(send)+ void call.start('device').catch(() => {})engineName.current = 'on_device'}// Picks up the computer's newest models for the next call; this one starts right away.@@ -170,6 +172,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {useEffect(() => {const startedAt = Date.now()window.codync.speech.setCalling(true)+ store.beginCall(link.current!.call)begin(VoiceSettings.provider())return () => {window.codync.speech.setCalling(false)@@ -178,7 +181,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {countCloudMinutes()onSpeaking(false)interrupt.current = null- store.logCall(botId, Math.floor((Date.now() - startedAt) / 1000))+ link.current?.end(Math.floor((Date.now() - startedAt) / 1000))}}, [])useEffect(() => voiceSettingsClosed.subscribe(switchEngine), [])diff --git a/apps/desktop/src/renderer/views/call/GeminiLiveEngine.ts b/apps/desktop/src/renderer/views/call/GeminiLiveEngine.tsindex b58637ca..ddd14fc1 100644--- a/apps/desktop/src/renderer/views/call/GeminiLiveEngine.ts+++ b/apps/desktop/src/renderer/views/call/GeminiLiveEngine.ts@@ -1,4 +1,4 @@-import { OPERATOR_TOOLS, type CallOperator } from './call-operator'+import type { CallLink, CallSession } from './call-link'import { errorMessage, fromBase64, micPCM16k, toBase64, VoiceEngine } from './voice'const URL_BASE = 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1alpha.GenerativeService.BidiGenerateContentConstrained'@@ -17,8 +17,9 @@ function geminiSchema(schema: Record<string, unknown>): Record<string, unknown>/*** Gemini Live over a WebSocket, this computer ↔ Google directly: 16 kHz PCM up, 24 kHz PCM down,- * echo-cancelled so you can talk over it. The user's key stays with the host, which mints one-use- * ephemeral tokens; a session the server ends (`goAway`) is resumed with a fresh one.+ * echo-cancelled so you can talk over it. The computer runs the call (`CallLink`): it mints one-use ephemeral tokens+ * on the user's key and writes the voice's instructions and tools, again for each session; a session the server ends+ * (`goAway`) is resumed with a fresh one.*/export class GeminiLiveEngine extends VoiceEngine {readonly provider = 'gemini' as const@@ -39,12 +40,15 @@ export class GeminiLiveEngine extends VoiceEngine {/** After a local interrupt, the rest of the turn's audio is dropped. */private dropping = falseprivate pending: string[] = []+ /** The current provider session's instructions and tools, from the computer. */+ private session: CallSession | null = null+ /** Tool calls still running on the computer: replies wait, so the model gets each answer first. */+ private toolsRunning = 0constructor(private model: string,private voice: string,- private credential: () => Promise<string>,- private op: CallOperator,+ private link: CallLink,) {super()}@@ -55,8 +59,11 @@ export class GeminiLiveEngine extends VoiceEngine {private async connect() {try {- const token = await this.credential()+ const session = await this.link.start('realtime', 'gemini', this.model, this.voice)if (this.ended) return+ if (!session.credential) throw new Error('Gemini sent no session credential.')+ this.session = session+ const token = session.credentialconst socket = new WebSocket(`${URL_BASE}?access_token=${encodeURIComponent(token)}`)socket.binaryType = 'arraybuffer'this.socket = socket@@ -73,10 +80,10 @@ export class GeminiLiveEngine extends VoiceEngine {}private sendSetup(socket: WebSocket) {- const tools = OPERATOR_TOOLS.map((t) => ({+ const tools = (this.session?.tools ?? []).map((t) => ({name: t.name,description: t.description,- ...(Object.keys(t.parameters.properties).length ? { parameters: geminiSchema(t.parameters) } : {}),+ ...(Object.keys((t.parameters?.properties as object | undefined) ?? {}).length ? { parameters: geminiSchema(t.parameters!) } : {}),}))const setup = {model: `models/${this.model}`,@@ -84,10 +91,13 @@ export class GeminiLiveEngine extends VoiceEngine {responseModalities: ['AUDIO'],speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: this.voice } } },},- systemInstruction: { parts: [{ text: this.op.instructions }] },+ systemInstruction: { parts: [{ text: this.session?.instructions ?? '' }] },tools: [{ functionDeclarations: tools }],// Audio sessions are otherwise capped at 15 minutes.contextWindowCompression: { slidingWindow: {} },+ // What both sides said, for the call's line in the chat.+ inputAudioTranscription: {},+ outputAudioTranscription: {},sessionResumption: this.resumeHandle ? { handle: this.resumeHandle } : {},}this.send({ setup }, socket)@@ -120,13 +130,13 @@ export class GeminiLiveEngine extends VoiceEngine {speak(reply: string) {if (this.ended || this.phase === 'failed') return- this.pending.push(this.op.reply(reply))+ this.pending.push(this.link.reply(reply))this.flush()}announce(notice: string) {if (this.ended || this.phase === 'failed') return- this.pending.push(this.op.notice(notice))+ this.pending.push(this.link.notice(notice))this.flush()}@@ -160,6 +170,9 @@ export class GeminiLiveEngine extends VoiceEngine {}const content = msg.serverContentif (content) {+ if (typeof content.inputTranscription?.text === 'string') this.link.add('user', content.inputTranscription.text)+ if (typeof content.outputTranscription?.text === 'string') this.link.add('voice', content.outputTranscription.text)+ if (content.turnComplete === true || content.interrupted === true) this.link.endTurn()if (content.interrupted === true) {this.stopPlayback()this.dropping = false@@ -182,13 +195,15 @@ export class GeminiLiveEngine extends VoiceEngine {}const calls = msg.toolCall?.functionCallsif (Array.isArray(calls)) {- const functionResponses = calls- .filter((c) => typeof c?.id === 'string' && typeof c?.name === 'string')- .map((c) => {- const output = this.op.call(c.name, (c.args as Record<string, unknown>) ?? {})- return { id: c.id, name: c.name, response: { result: JSON.parse(output) } }+ // The tools run on the computer; their answers go back together.+ const asked = calls.filter((c) => typeof c?.id === 'string' && typeof c?.name === 'string')+ this.toolsRunning+++ void Promise.all(asked.map(async (c) => ({ id: c.id, name: c.name, response: { result: await this.link.tool(c.name, c.args ?? {}) } })))+ .then((functionResponses) => {+ this.toolsRunning--+ this.send({ toolResponse: { functionResponses } })+ this.flush()})- this.send({ toolResponse: { functionResponses } })}const update = msg.sessionResumptionUpdateif (update?.resumable === true && typeof update.newHandle === 'string') this.resumeHandle = update.newHandle@@ -203,7 +218,7 @@ export class GeminiLiveEngine extends VoiceEngine {/** Replies wait for the model to finish talking; `turnComplete` here would cut it off. */private flush() {- if (!this.ready || !this.turnDone || this.queued !== 0 || !this.pending.length) return+ if (!this.ready || !this.turnDone || this.queued !== 0 || this.toolsRunning > 0 || !this.pending.length) returnconst text = this.pending.join('\n\n')this.pending = []this.turnDone = falsediff --git a/apps/desktop/src/renderer/views/call/OpenAIRealtimeEngine.ts b/apps/desktop/src/renderer/views/call/OpenAIRealtimeEngine.tsindex 6a9509ec..3289b347 100644--- a/apps/desktop/src/renderer/views/call/OpenAIRealtimeEngine.ts+++ b/apps/desktop/src/renderer/views/call/OpenAIRealtimeEngine.ts@@ -1,11 +1,11 @@-import { OPERATOR_TOOLS, type CallOperator } from './call-operator'-import { errorMessage, microphone, VoiceEngine } from './voice'+import type { CallLink, CallSession } from './call-link'+import { errorMessage, microphone, VoiceEngine, VoiceSettings } from './voice'/*** OpenAI Realtime over WebRTC, this computer ↔ 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 with the host, which mints the client secret; the host- * never sees audio.+ * `oai-events`. The computer runs the call (`CallLink`): it mints the client secret on the user's key and writes the+ * voice's instructions and tools; it never sees audio.*/export class OpenAIRealtimeEngine extends VoiceEngine {readonly provider = 'openai' as const@@ -17,10 +17,14 @@ export class OpenAIRealtimeEngine extends VoiceEngine {private responding = falseprivate pending: string[] = []private dropTimer: ReturnType<typeof setTimeout> | null = null+ private session: CallSession | null = null+ /** Tool calls still running on the computer: replies wait, so the model gets each result first. */+ private toolsRunning = 0constructor(- private credential: () => Promise<string>,- private op: CallOperator,+ private model: string,+ private voice: string,+ private link: CallLink,) {super()}@@ -29,9 +33,11 @@ export class OpenAIRealtimeEngine extends VoiceEngine {try {this.stream = await microphone()if (this.ended) return this.release()- const secret = await this.credential()+ const session = await this.link.start('realtime', 'openai', this.model, this.voice)if (this.ended) return- await this.connect(secret)+ if (!session.credential) throw new Error('OpenAI sent no session credential.')+ this.session = session+ await this.connect(session.credential)} catch (e) {if (!this.ended) this.fail(errorMessage(e))}@@ -113,13 +119,13 @@ export class OpenAIRealtimeEngine extends VoiceEngine {speak(reply: string) {if (this.ended || this.phase === 'failed') return- this.pending.push(this.op.reply(reply))+ this.pending.push(this.link.reply(reply))this.flush()}announce(notice: string) {if (this.ended || this.phase === 'failed') return- this.pending.push(this.op.notice(notice))+ this.pending.push(this.link.notice(notice))this.flush()}@@ -131,9 +137,10 @@ export class OpenAIRealtimeEngine extends VoiceEngine {type: 'session.update',session: {type: 'realtime',- instructions: this.op.instructions,- tools: OPERATOR_TOOLS.map((t) => ({ type: 'function', name: t.name, description: t.description, parameters: t.parameters })),- audio: { input: { turn_detection: { type: 'semantic_vad' } } },+ instructions: this.session?.instructions ?? '',+ tools: (this.session?.tools ?? []).map((t) => ({ type: 'function', name: t.name, description: t.description, parameters: t.parameters ?? { type: 'object', properties: {} } })),+ // What the user says is transcribed too, for the call's line in the chat.+ audio: { input: { turn_detection: { type: 'semantic_vad' }, transcription: { model: VoiceSettings.transcribeModel('openai') } } },},})}@@ -160,6 +167,12 @@ export class OpenAIRealtimeEngine extends VoiceEngine {case 'input_audio_buffer.speech_stopped':this.level = 0break+ case 'input_audio_buffer.committed':+ this.link.transcribing(true)+ break+ case 'conversation.item.input_audio_transcription.failed':+ this.link.transcribing(false)+ breakcase 'output_audio_buffer.started':this.setPhase('speaking')break@@ -174,16 +187,31 @@ export class OpenAIRealtimeEngine extends VoiceEngine {this.responding = falsethis.flush()break+ case 'conversation.item.input_audio_transcription.completed':+ this.link.add('user', typeof msg.transcript === 'string' ? msg.transcript : '')+ this.link.endTurn()+ break+ case 'response.output_audio_transcript.done':+ this.link.add('voice', typeof msg.transcript === 'string' ? msg.transcript : '')+ this.link.endTurn()+ breakcase 'response.function_call_arguments.done': {if (typeof msg.call_id !== 'string' || typeof msg.name !== 'string') returnlet args: Record<string, unknown> = {}try {if (typeof msg.arguments === 'string') args = JSON.parse(msg.arguments) as Record<string, unknown>} catch {}- const output = this.op.call(msg.name, args)- this.send({ type: 'conversation.item.create', item: { type: 'function_call_output', call_id: msg.call_id, output } })- // An empty entry asks for a response once this one is done, so the model speaks the result.- this.pending.push('')+ const callId = msg.call_id+ // The tool runs on the computer.+ this.toolsRunning+++ void this.link.tool(msg.name, args).then((result) => {+ this.toolsRunning--+ if (this.ended) return+ this.send({ type: 'conversation.item.create', item: { type: 'function_call_output', call_id: callId, output: JSON.stringify(result) } })+ // An empty entry asks for a response once this one is done, so the model speaks the result.+ this.pending.push('')+ this.flush()+ })break}case 'error':@@ -212,7 +240,7 @@ export class OpenAIRealtimeEngine extends VoiceEngine {/** Hands waiting replies (and tool results, as empty entries) to the model once it's free. */private flush() {- if (this.responding || !this.isActive || this.events?.readyState !== 'open' || !this.pending.length) return+ if (this.responding || this.toolsRunning > 0 || !this.isActive || this.events?.readyState !== 'open' || !this.pending.length) returnfor (const text of this.pending) {if (text) this.send({ type: 'conversation.item.create', item: { type: 'message', role: 'user', content: [{ type: 'input_text', text }] } })}diff --git a/apps/desktop/src/renderer/views/call/call-link.ts b/apps/desktop/src/renderer/views/call/call-link.tsnew file mode 100644index 00000000..1e51235f--- /dev/null+++ b/apps/desktop/src/renderer/views/call/call-link.ts@@ -0,0 +1,129 @@+import type { CallLine } from '@shared/calls'+import { sleep } from '../../store/bot-sync'+import type { BotStore } from '../../store/bot-store'+import { spokenText, type VoiceProvider } from './voice'++/** How long a tool call waits for the user's words that are still being written down. */+const HEARING_PATIENCE_MS = 2_000++/** What a client needs to run a call's voice, from the computer (`startCall`). */+export interface CallSession {+ /** A realtime provider's short-lived credential. */+ credential?: string+ /** The voice's instructions: its role, then the background. */+ instructions: string+ /** The voice's tools in JSON Schema form. */+ tools: { name: string; description: string; parameters?: Record<string, unknown> }[]+}++/**+ * A call as the computer runs it (host/src/chat/calls, kit `CallLink`): the voice's instructions, tools and+ * transcript live there; the engines only carry audio. One per call, so it outlives an engine switch.+ */+export class CallLink {+ private lines: CallLine[] = []+ private open = false+ /** The user's last words are still being written down (OpenAI transcribes them after the turn). */+ private hearing = false+ /** The computer gets what was said, the tool calls and the end one at a time, in order: a hand-off never+ * overtakes the words it hands on. */+ private queue: Promise<unknown> = Promise.resolve()++ constructor(+ private store: BotStore,+ readonly botId: string,+ /** The call's id: what it sends the bot carries it. */+ readonly call: string,+ ) {}++ /** Starts the call on the computer (again, when a provider session is replaced): what the voice needs. */+ async start(mode: 'realtime' | 'speech' | 'device', provider: VoiceProvider | null = null, model?: string, voice?: string) {+ const client = await this.store.ready()+ return client.call<CallSession>('startCall', {+ botId: this.botId, callId: this.call, mode, provider, model, voice, language: navigator.language,+ }, 30_000)+ }++ /** One of the voice's tool calls, run on the computer with what was said that it hasn't got yet. A failure is the+ * answer. */+ async tool(name: string, args: unknown): Promise<unknown> {+ for (let waited = 0; this.hearing && waited < HEARING_PATIENCE_MS; waited += 100) await sleep(100)+ return this.serial(async () => {+ const lines = this.drain(true)+ try {+ const client = await this.store.ready()+ return (await client.call<{ result: unknown }>('callTool', { callId: this.call, name, arguments: args ?? {}, lines }, 60_000)).result+ } catch (e) {+ this.restore(lines)+ return { error: e instanceof Error ? e.message : String(e) }+ }+ })+ }++ /** A piece of what `from` said; the pieces of one turn join into one line. */+ add(from: CallLine['from'], piece: string) {+ if (from === 'user') this.hearing = false+ if (!piece) return+ const last = this.lines.at(-1)+ if (this.open && last?.from === from) {+ last.text += piece+ } else {+ this.endTurn()+ this.lines.push({ from, text: piece, at: Date.now() })+ this.open = true+ }+ }++ /** The user stopped talking and their words are being written down (`true`), or that failed (`false`): a tool+ * call waits a moment for them. */+ transcribing(on: boolean) {+ this.hearing = on+ }++ /** The turn is over: what was said goes to the computer, and the next piece starts a line. */+ endTurn() {+ this.open = false+ void this.serial(async () => {+ const lines = this.drain(false)+ if (!lines.length) return+ try {+ await (await this.store.ready()).call('callLines', { callId: this.call, lines })+ } catch {+ this.restore(lines)+ }+ })+ }++ /** How a final reply of the bot reaches the voice. */+ reply(text: string) {+ return `[${this.store.bots.get(this.botId)?.name ?? 'Bot'} replied] ${spokenText(text)}`+ }++ notice(text: string) {+ return `[Notice] ${text}`+ }++ /** The call is over: its line in the chat, with what's left of the transcript. */+ end(seconds: number) {+ void this.serial(() => this.store.endCall(this.botId, this.call, seconds, this.drain(true)))+ }++ /** The lines finished so far (`withOpen`: and the one still being said), trimmed and out of the buffer. */+ private drain(withOpen: boolean): CallLine[] {+ const count = this.open && !withOpen ? this.lines.length - 1 : this.lines.length+ if (withOpen) this.open = false+ // ponytail: kit turns Simplified Chinese into Traditional here (ICU Hans-Hant); Chromium has no such transform.+ return this.lines.splice(0, count).map((l) => ({ ...l, text: l.text.trim() })).filter((l) => l.text)+ }++ /** Lines the computer didn't get go out with the next request. */+ private restore(lines: CallLine[]) {+ this.lines.unshift(...lines)+ }++ private serial<T>(op: () => Promise<T>): Promise<T> {+ const run = this.queue.then(op)+ this.queue = run.catch(() => {})+ return run+ }+}diff --git a/apps/desktop/src/renderer/views/call/call-operator.ts b/apps/desktop/src/renderer/views/call/call-operator.tsdeleted file mode 100644index 02880818..00000000--- a/apps/desktop/src/renderer/views/call/call-operator.ts+++ /dev/null@@ -1,140 +0,0 @@-import { isChat, isGroup, type Entry } from '@shared/models'-import type { BotStore } from '../../store/bot-store'-import { spokenText } from './voice'--export interface OperatorTool {- name: string- description: string- /** JSON Schema (both providers take the same shape). */- parameters: { type: 'object'; properties: Record<string, { type: string; description: string }>; required?: string[] }-}--export const OPERATOR_TOOLS: OperatorTool[] = [- {- name: 'send_to_bot',- description: 'Send a message to the bot on the computer, exactly as if the user typed it. Its reply arrives later.',- parameters: { type: 'object', properties: { text: { type: 'string', description: 'The message' } }, required: ['text'] },- },- {- name: 'bot_status',- description: 'Whether the bot is idle or working, what it is doing, and any approval it is waiting for.',- parameters: { type: 'object', properties: {} },- },- {- name: 'recent_messages',- description: 'The latest messages in the chat with the bot, oldest first.',- parameters: { type: 'object', properties: { count: { type: 'integer', description: 'How many, 1–20' } } },- },- {- name: 'answer_approval',- description: "Answer the bot's pending approval request with one of its options.",- parameters: { type: 'object', properties: { option: { type: 'string', description: "The option's name" } }, required: ['option'] },- },-]--/**- * 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 the store; only `send_to_bot` messages and- * the bot's replies become chat entries (kit CallOperator).- */-export class CallOperator {- constructor(- private store: BotStore,- private botId: string,- ) {}-- get instructions() {- const bot = this.store.bots.get(this.botId)- const name = bot?.name ?? 'the bot'- const about = bot?.description ? ` (${bot.description})` : ''- const who = bot && isGroup(bot)- ? `the group chat ${name}${about} on the user's computer, where the bots ${this.store.members(bot).map((m) => m.name).join(', ')} answer in turn (a message that @-mentions one of them asks just that bot). The bots do all the actual work; you relay`- : `${name}${about}, a coding agent running on the user's computer. ${name} does all the actual work; you relay`- return [- `You are the voice on a phone call between the user and ${who}.`,- '- 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.',- ].join('\n')- }-- /** Runs one tool call; the result is a JSON string. */- call(name: string, args: Record<string, unknown>): string {- let result: Record<string, unknown>- switch (name) {- case 'send_to_bot':- result = this.send(typeof args.text === 'string' ? args.text : '')- break- case 'bot_status':- result = this.status()- break- case 'recent_messages':- result = this.recent(typeof args.count === 'number' ? Math.trunc(args.count) : 6)- break- case 'answer_approval':- result = this.answer(typeof args.option === 'string' ? args.option : '')- break- default:- result = { error: `Unknown tool ${name}.` }- }- return JSON.stringify(result)- }-- /** How a reply is handed to the operator. */- reply(text: string) {- return `[${this.store.bots.get(this.botId)?.name ?? 'Bot'} replied] ${spokenText(text)}`- }-- notice(text: string) {- return `[Notice] ${text}`- }-- private send(text: string) {- const trimmed = text.trim()- if (!trimmed) return { error: 'Nothing to send.' }- this.store.send(trimmed, this.botId)- return { sent: true, note: "The bot's reply will arrive as a separate message." }- }-- private status() {- const bot = this.store.bots.get(this.botId)- if (!bot) return { error: "The bot isn't available." }- const out: Record<string, unknown> = { status: bot.status, activity: bot.activity }- const card = this.pendingApproval- if (card) out.approval = { request: card.data.title ?? card.data.command ?? '', options: (card.data.options ?? []).map((o) => o.name) }- return out- }-- private recent(count: number) {- const name = this.store.bots.get(this.botId)?.name ?? 'bot'- const n = Math.min(Math.max(count, 1), 20)- const messages = this.store- .allEntries(this.botId)- .filter(isChat)- .slice(-n)- .map((e) => ({- from: e.kind === 'user' ? 'user' : e.kind === 'agent' ? (e.data.author && this.store.bots.get(e.data.author)?.name) || name : e.kind === 'permission' ? 'approval request' : 'notice',- text: spokenText(e.data.text ?? e.data.title ?? ''),- }))- return { messages }- }-- private answer(option: string) {- const card = this.pendingApproval- if (!card) return { error: 'Nothing is waiting for approval.' }- const options = card.data.options ?? []- const wanted = option.toLowerCase()- const pick =- options.find((o) => o.name.toLowerCase() === wanted || o.optionId === option) ??- options.find((o) => o.name.toLowerCase().includes(wanted) || wanted.includes(o.name.toLowerCase()))- if (!pick) return { error: 'No such option.', options: options.map((o) => o.name) }- this.store.respond(card, pick.optionId)- return { answered: pick.name }- }-- private get pendingApproval(): Entry | undefined {- return this.store.allEntries(this.botId).findLast((e) => e.kind === 'permission' && e.data.status === 'pending')- }-}diff --git a/apps/desktop/src/renderer/views/call/call.css b/apps/desktop/src/renderer/views/call/call.cssindex 920c47ae..ca47d8ba 100644--- a/apps/desktop/src/renderer/views/call/call.css+++ b/apps/desktop/src/renderer/views/call/call.css@@ -82,3 +82,13 @@animation: none;}}++/* A voice call's line in the chat: centered like a bot message line, it opens the call. */+.call-line-row {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0 auto;+ padding: 6px 0;+ max-width: 100%;+}diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex fe1538fd..d29e877f 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -13,6 +13,8 @@ import { useStore } from '../../store/context'import { UpdateNeededCard } from '../UpdateNeededCard'import { buildChat, rowIn, useArrivals, type ChatItem } from './chat-items'import { BotConversationView, BotMessageRow } from './BotConversation'+import { CallConversationView, CallLineRow } from '../call/CallRows'+import { hidingCalls } from '@shared/calls'import { ChatRow, TimeSeparator } from './ChatRows'import { WorkingTransition } from './WorkingTransition'import { RoutineNotice } from './RoutineNotice'@@ -46,6 +48,8 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })const [replyTo, setReplyTo] = useState<Entry | null>(null)const cancelReply = useCallback(() => setReplyTo(null), [])const [botChat, setBotChat] = useState<string | null>(null)+ /** The voice call whose conversation is open (its line's entry id). */+ const [callLine, setCallLine] = useState<string | null>(null)const [editingGroup, setEditingGroup] = useState(false)const [templateDraft, setTemplateDraft] = useState<BotDraft | null>(null)const [showSettings, setShowSettings] = useState(false)@@ -176,7 +180,7 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })</button></div>{/* An update card takes the composer's place, so there's nothing to reply with. */}- <Transcript botId={botId} openTrace={openTrace} onReply={store.mismatch ? undefined : setReplyTo} openRoutine={presentRoutine} openAgent={presentAgent} openBotChat={setBotChat} openArtifact={openArtifact} />+ <Transcript botId={botId} openTrace={openTrace} onReply={store.mismatch ? undefined : setReplyTo} openRoutine={presentRoutine} openAgent={presentAgent} openBotChat={setBotChat} openArtifact={openArtifact} openCall={setCallLine} /><div className="composer-dock" ref={dock}><div className="composer-fade" />{store.mismatch ? (@@ -217,6 +221,9 @@ export const ThreadView = memo(function ThreadView({ botId }: { botId: string })<Sheet open={botChat !== null} onClose={() => setBotChat(null)} width={620} height={560}>{botChat ? <BotConversationView botId={botId} peerId={botChat} /> : null}</Sheet>+ <Sheet open={callLine !== null} onClose={() => setCallLine(null)} width={620} height={560}>+ {callLine ? <CallConversationView botId={botId} lineId={callLine} /> : null}+ </Sheet><Sheet open={showTrace} onClose={() => setShowTrace(false)} width={620} height={560}><TraceView botId={botId} /></Sheet>@@ -268,14 +275,16 @@ function ConnectionSubtitle() {/** The messages: every loaded message, brought to the newest as it changes while the reader is at the bottom. */const PAGE = 40-const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact }: { botId: string; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void }) {+const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact, openCall }: { botId: string; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void; openCall: (lineId: string) => void }) {const store = useStore()const tr = useTr()const bot = store.bots.get(botId) ?? nullconst live = !!bot && isWorkingIn(bot, botId) && !store.isOffline// Rebuilt only when this chat changes: the store replaces a chat's list on every change.const entries = store.allEntries(botId)- const all = useMemo(() => buildChat(entries), [entries])+ // What voice calls carried shows in each call's conversation, not in the chat.+ const liveCalls = [...store.liveCalls].join()+ const all = useMemo(() => buildChat(hidingCalls(entries, store.liveCalls)), [entries, liveCalls])const steps = useMemo(() => workingSteps(entries), [entries])// The newest 40 items first; older pages come in near the top.const [firstShown, setFirstShown] = useState<string | null>(null)@@ -315,7 +324,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRouif (at === 0) {const anchor = list[0]?.idawait store.loadOlder(botId)- list = buildChat(store.allEntries(botId))+ list = buildChat(hidingCalls(store.allEntries(botId), store.liveCalls))at = anchor ? Math.max(0, list.findIndex((i) => i.id === anchor)) : 0}if (at > 0) setFirstShown(list[Math.max(0, at - PAGE)]!.id)@@ -375,7 +384,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRou{items.length === 0 && bot ? <div className="transcript-intro">{isGroup(bot) ? <GroupIntroCard group={bot} /> : <IntroCard bot={bot} />}</div> : null}{items.map((item) => (<div key={item.id} className={arrivals.has(item.id) ? rowIn(item) : undefined}>- <Row item={item} chat={bot} openTrace={openTrace} onReply={onReply} openRoutine={openRoutine} openAgent={openAgent} openBotChat={openBotChat} openArtifact={openArtifact} />+ <Row item={item} chat={bot} openTrace={openTrace} onReply={onReply} openRoutine={openRoutine} openAgent={openAgent} openBotChat={openBotChat} openArtifact={openArtifact} openCall={openCall} /></div>))}{bot ? <WorkingTransition bot={bot} visible={live} steps={steps} /> : null}@@ -399,13 +408,14 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRou)})-function Row({ item, chat, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact }: { item: ChatItem; chat: Bot | null; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void }) {+function Row({ item, chat, openTrace, onReply, openRoutine, openAgent, openBotChat, openArtifact, openCall }: { item: ChatItem; chat: Bot | null; openTrace: () => void; onReply?: (e: Entry) => void; openRoutine: (id: string | null) => void; openAgent: (botId: string) => void; openBotChat: (peerId: string) => void; openArtifact: (artifactId: string) => void; openCall: (lineId: string) => void }) {if (item.kind === 'separator') {return <TimeSeparator date={item.date} />}if (item.kind === 'exchanges') return <BotMessageRow exchanges={item.exchanges} open={openBotChat} />const e = item.entryif (e.kind === 'notice' && e.data.routineId) return <RoutineNotice entry={e} open={() => openRoutine(e.data.routineId!)} />+ if (e.kind === 'notice' && e.data.call) return <div className="chat-row notice"><CallLineRow entry={e} open={() => openCall(e.id)} /></div>return <ChatRow entry={e} groupStart={item.groupStart} chat={chat} openTrace={openTrace} onReply={onReply} openAgent={openAgent} openArtifact={openArtifact} />}diff --git a/apps/desktop/src/shared/calls.test.ts b/apps/desktop/src/shared/calls.test.tsnew file mode 100644index 00000000..3432c508--- /dev/null+++ b/apps/desktop/src/shared/calls.test.ts@@ -0,0 +1,34 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { callConversation, hidingCalls } from './calls.ts'+import type { Entry } from './models.ts'++const entry = (id: string, kind: string, at: number, data: Entry['data']): Entry => ({+ id, seq: at, botId: 'b', rev: 1, kind, turn: 1, data, createdAt: at, updatedAt: at,+})++test("finished and live calls hide what they carried", () => {+ const entries = [+ entry('u1', 'user', 1, { text: 'spoken', call: 'c' }),+ entry('a1', 'agent', 2, { text: 'reply', final: true, call: 'c' }),+ entry('u2', 'user', 3, { text: 'no line yet', call: 'lost' }),+ entry('u3', 'user', 4, { text: 'on this window', call: 'live' }),+ entry('local-n', 'user', 5, { text: "didn't go out", call: 'live', status: 'failed' }),+ entry('n1', 'notice', 6, { text: 'Release plan', callSeconds: 26, call: 'c' }),+ ]+ assert.deepEqual(hidingCalls(entries, new Set(['live'])).map((e) => e.id), ['u2', 'local-n', 'n1'])+})++test("a call's conversation merges its transcript with what it carried", () => {+ const line = entry('n1', 'notice', 10, { text: 'Git', call: 'c', transcript: [{ from: 'user', text: '看一下 git', at: 1 }, { from: 'voice', text: 'Clean.', at: 9 }] })+ const entries = [+ entry('u1', 'user', 2, { text: 'check git', call: 'c', from: 'voice' }),+ entry('a1', 'agent', 3, { text: 'Working tree clean', final: true, call: 'c' }),+ entry('t1', 'agent', 4, { text: 'narration', call: 'c' }),+ entry('x1', 'user', 5, { text: 'typed' }),+ line,+ ]+ assert.deepEqual(callConversation(entries, line).map((m) => `${m.speaker}: ${m.text}`), [+ 'user: 看一下 git', 'voiceToBot: check git', 'bot: Working tree clean', 'voice: Clean.',+ ])+})diff --git a/apps/desktop/src/shared/calls.ts b/apps/desktop/src/shared/calls.tsnew file mode 100644index 00000000..26114b8d--- /dev/null+++ b/apps/desktop/src/shared/calls.ts@@ -0,0 +1,42 @@+// Voice calls in a chat (host/src/chat/calls): what a call sends the bot, and the bot's replies while it lasts,+// carry its id; the chat shows them only in the call's conversation, which its line opens.++import type { Entry } from './models'++/** One line of a voice call: what the user said (`user`) or the voice answered (`voice`), with when (ms). */+export interface CallLine {+ from: 'user' | 'voice'+ text: string+ at?: number+}++/** One message of a call's conversation. */+export interface CallMessage {+ speaker: 'user' | 'voice' | 'voiceToBot' | 'bot'+ text: string+}++/** Without what voice calls carried: the messages of a call that has its line, or of a call this window is on. One+ * that failed to send stays, to be sent again. */+export function hidingCalls(entries: Entry[], live: ReadonlySet<string>): Entry[] {+ const ended = new Set(entries.flatMap((e) => (e.kind === 'notice' && e.data.call ? [e.data.call] : [])))+ const shown = (e: Entry) => e.kind === 'notice' || !e.data.call || e.data.status === 'failed'+ return entries.filter((e) => shown(e) || (!ended.has(e.data.call!) && !live.has(e.data.call!)))+}++/** A call's conversation, oldest first: what was said (the voice's transcript) and the messages it carried. */+export function callConversation(entries: Entry[], line: Entry): CallMessage[] {+ const call = line.data.call+ if (!call) return []+ const said: { at: number; message: CallMessage }[] = (line.data.transcript ?? []).map((l) => ({+ at: l.at ?? line.createdAt,+ message: { speaker: l.from === 'user' ? 'user' : 'voice', text: l.text },+ }))+ for (const e of entries) {+ if (e.data.call !== call || !(e.kind === 'user' || (e.kind === 'agent' && e.data.final))) continue+ const speaker = e.kind === 'agent' ? 'bot' : e.data.from === 'voice' ? 'voiceToBot' : 'user'+ said.push({ at: e.createdAt, message: { speaker, text: e.data.text ?? '' } })+ }+ // Stable: phone and computer clocks are merged as they are.+ return said.map((s, i) => ({ ...s, i })).sort((a, b) => a.at - b.at || a.i - b.i).map((s) => s.message)+}diff --git a/apps/desktop/src/shared/compat.test.ts b/apps/desktop/src/shared/compat.test.tsindex 81b3010b..e5b89b45 100644--- a/apps/desktop/src/shared/compat.test.ts+++ b/apps/desktop/src/shared/compat.test.ts@@ -13,6 +13,6 @@ test('versions parse like the host and the iPhone app', () => {test('the side that must update', () => {assert.deepEqual(checkVersions('2.6.0', '2.7.0', '2.7.0'), { kind: 'updateApp', minimum: '2.7.0' })- assert.deepEqual(checkVersions('2.20.1', '2.20.0', null), { kind: 'updateHost', version: '2.20.0', minimum: '2.20.1' })- assert.equal(checkVersions('2.20.1', '2.20.1', '2.3.0'), null)+ assert.deepEqual(checkVersions('2.25.0', '2.24.9', null), { kind: 'updateHost', version: '2.24.9', minimum: '2.25.0' })+ assert.equal(checkVersions('2.25.0', '2.25.0', '2.3.0'), null)})diff --git a/apps/desktop/src/shared/compat.ts b/apps/desktop/src/shared/compat.tsindex baab9d7d..f06580f3 100644--- a/apps/desktop/src/shared/compat.ts+++ b/apps/desktop/src/shared/compat.ts@@ -6,7 +6,7 @@ export type VersionMismatch =| { kind: 'updateHost'; version: string; minimum: string }/** The oldest host this app works with. */-export const MIN_HOST = '2.20.1'+export const MIN_HOST = '2.25.0'/** `major.minor.patch`, ignoring a leading `v` and any pre-release or build suffix. */export function parseVersion(version: string): number[] | null {diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex a5ed8dd6..b584cda7 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -1,4 +1,5 @@import type { ArtifactCard } from './artifacts'+import type { CallLine } from './calls'// Wire types for codync-host (see host/src/api/). Field names match the// host's camelCase JSON. Timestamps are epoch milliseconds.@@ -315,6 +316,13 @@ export interface EntryData {/** agent: an artifact the bot published (or updated) in this turn. */artifact?: ArtifactCardcallSeconds?: number+ /** The voice call it was said in (user), answered during (agent), or that it ends (notice): the chat shows those+ * messages only in the call's conversation. */+ call?: string+ /** user: `voice` when a call's voice wrote it for the user (`send_to_bot`). */+ from?: string+ /** notice: what was said on a realtime call, oldest first. */+ transcript?: CallLine[]}export interface Entry {diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 38a59b08..d63154f8 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -195,16 +195,17 @@ public extension HostClient {/// `replyTo`: the chat message this one quotes./// `pasted`: what the user pasted rather than typed, which memory never takes as their own words.+ /// `call`: the voice call it was said in (on-device or speech to text).func send(botId: String, text: String, clientNonce: String, replyTo: String? = nil, attachments: [String]? = nil,- pasted: [String]? = nil) async throws -> Entry {+ pasted: [String]? = nil, call: String? = nil) async throws -> Entry {struct Body: Encodable {var botId: String; var text: String; var clientNonce: String; var replyTo: String?; var attachments: [String]?- var pasted: [String]?+ var pasted: [String]?; var call: String?}struct Res: Decodable { var entry: Entry }let body = Body(botId: botId, text: text, clientNonce: clientNonce, replyTo: replyTo, attachments: attachments,- pasted: pasted?.isEmpty == false ? pasted : nil)- let res: Res = try await call("send", body)+ pasted: pasted?.isEmpty == false ? pasted : nil, call: call)+ let res: Res = try await self.call("send", body)return res.entry}@@ -241,9 +242,45 @@ public extension HostClient {let _: Empty = try await call("callStarted", ["botId": botId])}- func logCall(_ botId: String, seconds: Int) async throws {- struct Body: Encodable { var botId: String; var seconds: Int }- let _: Empty = try await call("logCall", Body(botId: botId, seconds: seconds))+ // MARK: voice calls (host/src/chat/calls)++ /// The call is on (again, for a provider session that was replaced): the voice's instructions and tools, and a+ /// realtime provider's credential. `mode`: `realtime`, `speech` or `device`.+ func startCall(botId: String, call: String, mode: String, provider: VoiceProvider? = nil, model: String? = nil,+ voice: String? = nil, language: String?) async throws -> CallSession {+ struct Body: Encodable {+ var botId, callId, mode: String; var provider, model, voice, language: String?+ }+ let body = Body(botId: botId, callId: call, mode: mode, provider: provider?.rawValue, model: model, voice: voice,+ language: language)+ let data = try await transport.call("startCall", body: try Self.encoder.encode(body), timeout: 30)+ return try CallSession(json: data)+ }++ /// Runs one of the voice's tool calls on the computer, with what was said that it hasn't got yet (`lines`);+ /// `arguments` and the answer are JSON.+ func callTool(call: String, name: String, arguments: Data, lines: [CallLine]) async throws -> Data {+ let args = (try? JSONSerialization.jsonObject(with: arguments)) ?? [String: Any]()+ let said = try JSONSerialization.jsonObject(with: Self.encoder.encode(lines))+ let body = try JSONSerialization.data(withJSONObject: ["callId": call, "name": name, "arguments": args, "lines": said])+ let data = try await transport.call("callTool", body: body, timeout: 60)+ let result = ((try? JSONSerialization.jsonObject(with: data)) as? [String: Any])?["result"] ?? [String: Any]()+ return try JSONSerialization.data(withJSONObject: result)+ }++ /// What was just said on the call, kept on the computer.+ func callLines(call: String, lines: [CallLine]) async throws {+ struct Body: Encodable { var callId: String; var lines: [CallLine] }+ let _: Empty = try await self.call("callLines", Body(callId: call, lines: lines))+ }++ /// The call is over: its line in the chat, with the rest of the transcript (`lines`), which the computer titles.+ /// Safe to repeat: the computer ends a call once.+ func endCall(botId: String, call: String, seconds: Int, lines: [CallLine]) async throws -> Entry? {+ struct Body: Encodable { var botId, callId: String; var seconds: Int; var lines: [CallLine] }+ struct Res: Decodable { var entry: Entry? }+ let res: Res = try await self.call("endCall", Body(botId: botId, callId: call, seconds: seconds, lines: lines))+ return res.entry}func stop(_ botId: String) async throws {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swiftnew file mode 100644index 00000000..84354405--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swift@@ -0,0 +1,57 @@+import Foundation++// Voice calls in a chat (host/src/chat/calls): what a call sends the bot, and the bot's replies while it lasts,+// carry its id; the chat shows them only in the call's conversation, which its line opens.++/// What a client needs to run a call's voice, from the computer (`startCall`).+public struct CallSession: Sendable {+ /// A realtime provider's short-lived credential.+ public var credential: String?+ /// The voice's instructions: its role, then the background.+ public var instructions: String+ /// The voice's tools, a JSON array of `{name, description, parameters}` (JSON Schema).+ public var tools: Data++ init(json data: Data) throws {+ guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let instructions = object["instructions"] as? String else {+ throw HostError.http(0, "The computer sent no call instructions.")+ }+ credential = object["credential"] as? String+ self.instructions = instructions+ tools = try JSONSerialization.data(withJSONObject: object["tools"] as? [Any] ?? [])+ }+}++/// One message of a call's conversation.+public struct CallMessage: Hashable, Sendable {+ public enum Speaker: Sendable { case user, voice, voiceToBot, bot }+ public var speaker: Speaker+ public var text: String+}++public extension Array where Element == Entry {+ /// Without what voice calls carried: the messages of a call that has its line, or of a call this device is on.+ /// One that failed to send stays, to be sent again.+ func hidingCalls(live: Set<String>) -> [Entry] {+ let ended = Set(compactMap { $0.kind == "notice" ? $0.data.call : nil })+ return filter { e in+ guard e.kind != "notice", e.data.status != "failed", let call = e.data.call else { return true }+ return !ended.contains(call) && !live.contains(call)+ }+ }++ /// A call's conversation, oldest first: what was said (the voice's transcript) and the messages it carried.+ /// Phone and computer clocks are merged as they are.+ func callConversation(_ line: Entry) -> [CallMessage] {+ guard let call = line.data.call else { return [] }+ var said: [(at: Int64, message: CallMessage)] = (line.data.transcript ?? []).map {+ ($0.at ?? line.createdAt, CallMessage(speaker: $0.from == "user" ? .user : .voice, text: $0.text))+ }+ for e in self where e.data.call == call && (e.kind == "user" || (e.kind == "agent" && e.data.final == true)) {+ let speaker: CallMessage.Speaker = e.kind == "agent" ? .bot : e.data.from == "voice" ? .voiceToBot : .user+ said.append((e.createdAt, CallMessage(speaker: speaker, text: e.data.text ?? "")))+ }+ return said.enumerated().sorted { ($0.element.at, $0.offset) < ($1.element.at, $1.offset) }.map(\.element.message)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swiftindex b572c231..6d5d6a10 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Compatibility.swift@@ -11,7 +11,7 @@ public enum VersionMismatch: Equatable, Sendable {/// The oldest host this app works with. Raise it only when the app starts depending on/// something older hosts don't have (an optional feature hides its control instead).- public static let minHost = "2.20.1"+ public static let minHost = "2.25.0"/// Checks this app (`app`) against a host's version and `minApp` (nil from hosts that predate it).public static func check(app: String, minHost: String = minHost, hostVersion: String, minApp: String?) -> VersionMismatch? {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex 2fa90276..23918d39 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -58,6 +58,13 @@ public struct EntryData: Codable, Hashable, Sendable {public var files: [SharedFile]?/// notice: a finished voice call's length.public var callSeconds: Int?+ /// The voice call it was said in (user), answered during (agent), or that it ends (notice); the chat shows those+ /// messages only in the call's conversation.+ public var call: String?+ /// user: `voice` when a call's voice model wrote it for the user (`send_to_bot`).+ public var from: String?+ /// notice: what was said on a realtime call, oldest first.+ public var transcript: [CallLine]?/// agent: an artifact card, the bot's artifact as published then (the newest version shows).public var artifact: ArtifactRef?@@ -68,6 +75,19 @@ public struct EntryData: Codable, Hashable, Sendable {}}+/// One line of a voice call: what the user said (`from: user`) or the voice answered (`voice`), with when (ms).+public struct CallLine: Codable, Hashable, Sendable {+ public var from: String+ public var text: String+ public var at: Int64?++ public init(from: String, text: String, at: Int64?) {+ self.from = from+ self.text = text+ self.at = at+ }+}+/// The message a reply quotes: its entry, who wrote it (`user` or a bot id) and its text (at most 500/// characters, or its file names), and the artifact when it is an artifact card. A partial quote still decodes, so the/// message itself always shows.diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex b7ea6bd4..2f694d0d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1205,5 +1205,8 @@"In your SSH config": "In deiner SSH-Konfiguration","Allow": "Erlauben","Extensions moved to each computer": "Erweiterungen gibt es jetzt pro Computer",- "Each computer has its own. Open them with the button on the computer's heading.": "Jeder Computer hat seine eigenen. Öffne sie mit der Taste in der Überschrift des Computers."+ "Each computer has its own. Open them with the button on the computer's heading.": "Jeder Computer hat seine eigenen. Öffne sie mit der Taste in der Überschrift des Computers.",+ "Nothing was said on this call.": "In diesem Anruf wurde nichts gesagt.",+ "Open the call": "Anruf öffnen",+ "Opens the call": "Öffnet den Anruf"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 31ab1918..861e0501 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1205,5 +1205,8 @@"In your SSH config": "En tu configuración SSH","Allow": "Permitir","Extensions moved to each computer": "Las extensiones ahora están en cada computadora",- "Each computer has its own. Open them with the button on the computer's heading.": "Cada computadora tiene las suyas. Ábrelas con el botón del encabezado de la computadora."+ "Each computer has its own. Open them with the button on the computer's heading.": "Cada computadora tiene las suyas. Ábrelas con el botón del encabezado de la computadora.",+ "Nothing was said on this call.": "No se dijo nada en esta llamada.",+ "Open the call": "Abrir la llamada",+ "Opens the call": "Abre la llamada"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 2879f7c5..3efd6fb4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1205,5 +1205,8 @@"In your SSH config": "Dans votre configuration SSH","Allow": "Autoriser","Extensions moved to each computer": "Les extensions sont maintenant sur chaque ordinateur",- "Each computer has its own. Open them with the button on the computer's heading.": "Chaque ordinateur a les siennes. Ouvrez-les avec le bouton sur l’en-tête de l’ordinateur."+ "Each computer has its own. Open them with the button on the computer's heading.": "Chaque ordinateur a les siennes. Ouvrez-les avec le bouton sur l’en-tête de l’ordinateur.",+ "Nothing was said on this call.": "Rien n'a été dit pendant cet appel.",+ "Open the call": "Ouvrir l'appel",+ "Opens the call": "Ouvre l'appel"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex da6433fb..2c0d5d92 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1205,5 +1205,8 @@"In your SSH config": "SSH 設定にあります","Allow": "許可","Extensions moved to each computer": "拡張機能はコンピューターごとになりました",- "Each computer has its own. Open them with the button on the computer's heading.": "コンピューターごとに別々です。コンピューターの見出しにあるボタンから開きます。"+ "Each computer has its own. Open them with the button on the computer's heading.": "コンピューターごとに別々です。コンピューターの見出しにあるボタンから開きます。",+ "Nothing was said on this call.": "この通話では何も話されませんでした。",+ "Open the call": "通話を開く",+ "Opens the call": "通話を開きます"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 86d4e8ae..57067e42 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1205,5 +1205,8 @@"In your SSH config": "SSH 설정에 있음","Allow": "허용","Extensions moved to each computer": "확장이 컴퓨터별로 옮겨졌습니다",- "Each computer has its own. Open them with the button on the computer's heading.": "컴퓨터마다 따로 있습니다. 컴퓨터 제목의 버튼으로 여세요."+ "Each computer has its own. Open them with the button on the computer's heading.": "컴퓨터마다 따로 있습니다. 컴퓨터 제목의 버튼으로 여세요.",+ "Nothing was said on this call.": "이 통화에서는 아무 말도 하지 않았습니다.",+ "Open the call": "통화 열기",+ "Opens the call": "통화를 엽니다"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 0f257071..c79083dd 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1205,5 +1205,8 @@"In your SSH config": "在你的 SSH 配置文件中","Allow": "允许","Extensions moved to each computer": "扩展移到各台电脑了",- "Each computer has its own. Open them with the button on the computer's heading.": "每台电脑都有自己的一份,用电脑标题栏上的按钮打开。"+ "Each computer has its own. Open them with the button on the computer's heading.": "每台电脑都有自己的一份,用电脑标题栏上的按钮打开。",+ "Nothing was said on this call.": "这通电话没有说话。",+ "Open the call": "打开这通电话",+ "Opens the call": "打开这通电话"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex a027aae9..8b0f0caa 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1205,5 +1205,8 @@"In your SSH config": "在你的 SSH 設定檔中","Allow": "允許","Extensions moved to each computer": "擴充套件移到各台電腦了",- "Each computer has its own. Open them with the button on the computer's heading.": "每台電腦都有自己的一份,用電腦標題列上的按鈕打開。"+ "Each computer has its own. Open them with the button on the computer's heading.": "每台電腦都有自己的一份,用電腦標題列上的按鈕打開。",+ "Nothing was said on this call.": "這通電話沒有說話。",+ "Open the call": "打開這通電話",+ "Opens the call": "打開這通電話"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swiftnew file mode 100644index 00000000..2e34b14d--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swift@@ -0,0 +1,131 @@+import CodyncKit+import Foundation+import os++private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")++/// How long a tool call waits for the user's words that are still being written down.+private let hearingPatience: Duration = .seconds(2)++/// A call as the computer runs it (host/src/chat/calls): the voice's instructions, tools and transcript live there;+/// the engines only carry audio. One per call, so it outlives an engine switch.+@MainActor+final class CallLink {+ let model: BotStore+ let botId: String+ /// The call's id: what it sends the bot carries it.+ let call: String+ private var lines: [CallLine] = []+ private var open = false+ /// The user's last words are still being written down (OpenAI transcribes them after the turn).+ private var hearing = false+ /// The computer gets what was said, the tool calls and the end one at a time, in order: a hand-off never+ /// overtakes the words it hands on.+ private var queue: Task<Void, Never>?++ init(model: BotStore, botId: String, call: String) {+ self.model = model+ self.botId = botId+ self.call = call+ }++ private func client() throws -> HostClient {+ guard let client = model.client else { throw VoiceError("Not connected to \(model.hostName).") }+ return client+ }++ /// Starts the call on the computer (again, when a provider session is replaced): what the voice needs.+ func start(_ mode: String, provider: VoiceProvider? = nil, model chosen: String? = nil, voice: String? = nil) async throws -> CallSession {+ try await client().startCall(botId: botId, call: call, mode: mode, provider: provider, model: chosen, voice: voice,+ language: Locale.preferredLanguages.first)+ }++ /// One of the voice's tool calls, run on the computer with what was said that it hasn't got yet; its answer is+ /// JSON. A failure is the answer.+ func tool(_ name: String, arguments: Data) async -> Data {+ let deadline = ContinuousClock.now + hearingPatience+ while hearing, ContinuousClock.now < deadline { try? await Task.sleep(for: .milliseconds(100)) }+ return await serial { [self] in+ let said = drain(withOpen: true)+ do {+ return try await client().callTool(call: call, name: name, arguments: arguments, lines: said)+ } catch {+ restore(said)+ return (try? JSONSerialization.data(withJSONObject: ["error": error.localizedDescription])) ?? Data("{}".utf8)+ }+ }.value+ }++ /// A piece of what `from` (`user` or `voice`) said; the pieces of one turn join into one line.+ func add(_ from: String, _ piece: String) {+ if from == "user" { hearing = false }+ guard !piece.isEmpty else { return }+ if open, let last = lines.indices.last, lines[last].from == from {+ lines[last].text += piece+ } else {+ endTurn()+ lines.append(CallLine(from: from, text: piece, at: Int64(Date.now.timeIntervalSince1970 * 1000)))+ open = true+ }+ }++ /// The user stopped talking and their words are being written down (`true`), or that failed (`false`): a tool+ /// call waits a moment for them.+ func transcribing(_ on: Bool) {+ hearing = on+ }++ /// The turn is over: what was said goes to the computer, and the next piece starts a line.+ func endTurn() {+ open = false+ serial { [self] in+ let said = drain(withOpen: false)+ guard !said.isEmpty else { return }+ do { try await client().callLines(call: call, lines: said) } catch {+ restore(said)+ log.error("call lines: \(error.localizedDescription, privacy: .public)")+ }+ }+ }++ /// How a final reply of the bot reaches the voice.+ func reply(_ text: String) -> String {+ "[\(model.bots[botId]?.name ?? "Bot") replied] \(SpokenText.from(text))"+ }++ func notice(_ text: String) -> String { "[Notice] \(text)" }++ /// The call is over: its line in the chat, with what's left of the transcript.+ func end(seconds: Int) {+ serial { [self] in await model.endCall(botId, seconds: seconds, call: call, lines: drain(withOpen: true)) }+ }++ /// The lines finished so far (`withOpen`: and the one still being said), out of the buffer: trimmed, Chinese in+ /// the reader's script.+ private func drain(withOpen: Bool) -> [CallLine] {+ let count = open && !withOpen ? lines.count - 1 : lines.count+ if withOpen { open = false }+ let taken = lines.prefix(max(count, 0))+ lines.removeFirst(taken.count)+ return taken.compactMap { line in+ let text = VoiceSettings.inReadersScript(line.text.trimmingCharacters(in: .whitespacesAndNewlines))+ return text.isEmpty ? nil : CallLine(from: line.from, text: text, at: line.at)+ }+ }++ /// Lines the computer didn't get go out with the next request.+ private func restore(_ said: [CallLine]) {+ lines.insert(contentsOf: said, at: 0)+ }++ @discardableResult+ private func serial<T: Sendable>(_ op: @escaping @MainActor () async -> T) -> Task<T, Never> {+ let previous = queue+ let task = Task { @MainActor in+ await previous?.value+ return await op()+ }+ queue = Task { _ = await task.value }+ return task+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallOperator.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallOperator.swiftdeleted file mode 100644index aacd3e97..00000000--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallOperator.swift+++ /dev/null@@ -1,118 +0,0 @@-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))" } ?? ""- let who = if let bot, bot.isGroup {- "the group chat \(name)\(about) on the user's computer, where the bots "- + model.members(of: bot).map(\.name).joined(separator: ", ")- + " answer in turn (a message that @-mentions one of them asks just that bot). "- + "The bots do all the actual work; you relay"- } else {- "\(name)\(about), a coding agent running on the user's computer. \(name) does all the actual work; you relay"- }- return """- You are the voice on a phone call between the user and \(who).- - 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": e.data.author.flatMap { model.bots[$0]?.name } ?? 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/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swiftnew file mode 100644index 00000000..c95fcca6--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swift@@ -0,0 +1,85 @@+import CodyncKit+import SwiftUI++/// A voice call's line in the chat: its title (written once the call ends) and length; tapping it opens the call.+struct CallLineRow: View {+ let entry: Entry+ let open: () -> Void++ var body: some View {+ let title = L10n.tr(entry.data.text ?? "Voice chat")+ let length = entry.data.callSeconds.map { String(format: " · %02d:%02d", $0 / 60, $0 % 60) } ?? ""+ Button(action: open) {+ HStack(spacing: 6) {+ Image(systemName: "waveform").foregroundStyle(Palette.secondary)+ Text(title).foregroundStyle(Palette.text)+ Text(length).monospacedDigit().foregroundStyle(Palette.secondary)+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)+ }+ .font(.footnote)+ .lineLimit(1)+ .padding(.vertical, 6)+ .frame(maxWidth: .infinity)+ .contentShape(Rectangle())+ }+ .buttonStyle(PressScale())+ .accessibilityLabel("\(title)\(length)")+ .accessibilityHint("Opens the call")+ }+}++/// What a voice call said, oldest first: the user's and the voice's words, and the messages it carried to the bot+/// and back, which the chat itself leaves out.+struct CallConversationView: View {+ let line: Entry+ @Environment(BotStore.self) private var model++ var body: some View {+ let entry = model.chat(line.botId).first { $0.id == line.id } ?? line+ let messages = model.chat(line.botId).callConversation(entry)+ VStack(spacing: 0) {+ ModalHeader(entry.data.text ?? "Voice chat")+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 10) {+ if messages.isEmpty {+ Text(L10n.tr("Nothing was said on this call.")).font(.footnote).foregroundStyle(Palette.tertiary)+ .frame(maxWidth: .infinity).padding(.top, 24)+ }+ ForEach(Array(messages.enumerated()), id: \.offset) { _, message in row(message) }+ }+ .padding(.horizontal, 16)+ .padding(.bottom, 12)+ }+ .defaultScrollAnchor(.bottom)+ }+ .background(Palette.background)+ }++ @ViewBuilder private func row(_ message: CallMessage) -> some View {+ switch message.speaker {+ case .user:+ Text(message.text)+ .padding(.horizontal, 14).padding(.vertical, 9)+ .background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 18, style: .continuous))+ .frame(maxWidth: .infinity, alignment: .trailing)+ .padding(.leading, 40)+ case .voice:+ Text(message.text)+ .foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.trailing, 40)+ case .voiceToBot:+ Label(message.text, systemImage: "arrow.turn.down.right")+ .font(.footnote)+ .foregroundStyle(Palette.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ case .bot:+ MarkdownText(message.text)+ .equatable()+ .padding(.horizontal, 16).padding(.vertical, 10)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.trailing, 40)+ }+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swiftindex 29e5a154..c98b0758 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift@@ -3,8 +3,8 @@ import CodyncKitimport SwiftUI/// A voice call with a bot, as Grok Bot does it: a floating bar over the chat, which stays-/// readable underneath. What you say goes out as ordinary messages, its final replies are-/// read aloud, and the chat gets a "Voice chat · 00:16" line when the call ends.+/// readable underneath. What you say goes out as messages of the call, its final replies are+/// read aloud, and the call ends as one titled line ("Release plan · 00:16") that opens its conversation.struct CallView: View {let botId: String@Binding var isSpeaking: Bool@@ -14,6 +14,8 @@ struct CallView: View {@Environment(\.accessibilityReduceMotion) private var reduceMotion@State private var session: (any VoiceEngine)?@State private var callID = UUID()+ /// The call on the computer, which runs it; set as the call appears.+ @State private var link: CallLink?@State private var startedAt = Date.now/// When the current cloud engine started, for this month's minutes.@State private var cloudStartedAt: Date?@@ -26,6 +28,7 @@ struct CallView: View {@State private var reported = falseprivate var bot: Bot? { model.bots[botId] }+ private var call: String { callID.uuidString }private var color: Color { bot.map { AvatarPalette.color($0.avatarColor) } ?? Palette.accent }var body: some View {@@ -42,6 +45,8 @@ struct CallView: View {.animation(Motion.reduced(Motion.fade, reduceMotion), value: notice).onAppear {startedAt = .now+ model.beginCall(call)+ link = CallLink(model: model, botId: botId, call: call)begin(cloud: VoiceSettings.provider)}.onDisappear {@@ -50,7 +55,7 @@ struct CallView: View {isSpeaking = falseinterrupt = nilmodel.endVoiceCall(callID)- model.logCall(botId, seconds: Int(Date.now.timeIntervalSince(startedAt)))+ link?.end(seconds: Int(Date.now.timeIntervalSince(startedAt)))}.onChange(of: session?.phase) { _, phase inisSpeaking = phase == .speaking@@ -79,7 +84,7 @@ struct CallView: View {Task { if let status = try? await client.voiceStatus() { VoiceSettings.remember(status) } }}engineChoice = VoiceSettings.engineChoice(provider)- let op = CallOperator(model: model, botId: botId)+ guard let link else { return }let engine: any VoiceEngineif let provider, VoiceSettings.isSpeechMode(provider) {let transcribe = VoiceSettings.transcribeModel(provider)@@ -92,23 +97,22 @@ struct CallView: View {engine = CloudSpeechEngine(provider: provider, speech: .init(transcribe: { try await VoiceSettings.inReadersScript(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) }+ send: { [model, botId, call] in model.send($0, to: botId, call: call) }))+ // The computer keeps the call, though it carries no voice model.+ Task { _ = try? await link.start("speech", provider: provider) }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)+ case .openAI: OpenAIRealtimeEngine(model: chosen, voice: voice, link: link)+ case .gemini: GeminiLiveEngine(model: chosen, voice: voice, link: link)}cloudStartedAt = .now} else {- engine = OnDeviceEngine { [model, botId] in model.send($0, to: botId) }+ engine = OnDeviceEngine { [model, botId, call] in model.send($0, to: botId, call: call) }+ Task { _ = try? await link.start("device") }}engine.onActivityChanged = { [weak engine, model, botId, callID] active inif active {diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swiftindex bce54cdf..944419bc 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/GeminiLiveEngine.swift@@ -7,8 +7,9 @@ import osprivate 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.+/// echo-cancelled by the voice-processing input so you can talk over it. The computer runs the call (`CallLink`): it+/// mints one-use ephemeral tokens on the user's key and writes the voice's instructions and tools, again for each+/// session; a session the server ends (`goAway`) is resumed with a fresh one.@MainActor@Observablefinal class GeminiLiveEngine: VoiceEngine {@@ -26,11 +27,13 @@ final class GeminiLiveEngine: VoiceEngine {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 -> Stringprivate let model: Stringprivate let voice: String- private let op: CallOperator+ private let link: CallLink+ /// The current provider session's instructions and tools, from the computer.+ private var session: CallSession?+ /// Tool calls still running on the computer: replies wait, so the model gets each answer first.+ private var toolsRunning = 0private var socket: URLSessionWebSocketTask?/// Setup is done on the current socket.private var ready = false@@ -52,11 +55,10 @@ final class GeminiLiveEngine: VoiceEngine {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+ init(model: String, voice: String, link: CallLink) {self.model = modelself.voice = voice- self.op = op+ self.link = link}func start() async {@@ -68,8 +70,10 @@ final class GeminiLiveEngine: VoiceEngine {private func connect() async {do {- let token = try await credential()+ let session = try await link.start("realtime", provider: .gemini, model: model, voice: voice)guard !ended else { return }+ guard let token = session.credential else { throw VoiceError("Gemini sent no session credential.") }+ self.session = sessionvar 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.") }@@ -87,10 +91,12 @@ final class GeminiLiveEngine: VoiceEngine {}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)+ let declared = session.flatMap { (try? JSONSerialization.jsonObject(with: $0.tools)) as? [[String: Any]] } ?? []+ let tools: [[String: Any]] = declared.map { tool in+ var declaration: [String: Any] = ["name": tool["name"] ?? "", "description": tool["description"] ?? ""]+ if let parameters = tool["parameters"] as? [String: Any], let properties = parameters["properties"] as? [String: Any],+ !properties.isEmpty {+ declaration["parameters"] = Self.geminiSchema(parameters)}return declaration}@@ -100,10 +106,13 @@ final class GeminiLiveEngine: VoiceEngine {"responseModalities": ["AUDIO"],"speechConfig": ["voiceConfig": ["prebuiltVoiceConfig": ["voiceName": voice]]],] as [String: Any],- "systemInstruction": ["parts": [["text": op.instructions]]],+ "systemInstruction": ["parts": [["text": session?.instructions ?? ""]]],"tools": [["functionDeclarations": tools]],// Audio sessions are otherwise capped at 15 minutes."contextWindowCompression": ["slidingWindow": [String: Any]()],+ // What both sides said, for the call's line in the chat.+ "inputAudioTranscription": [String: Any](),+ "outputAudioTranscription": [String: Any](),"sessionResumption": resumeHandle.map { ["handle": $0] } ?? [:],]send(["setup": setup], on: socket)@@ -134,13 +143,13 @@ final class GeminiLiveEngine: VoiceEngine {func speak(reply: String) {guard !ended, !phase.isFailed else { return }- pending.append(op.reply(reply))+ pending.append(link.reply(reply))flush()}func announce(_ notice: String) {guard !ended, !phase.isFailed else { return }- pending.append(op.notice(notice))+ pending.append(link.notice(notice))flush()}@@ -195,6 +204,9 @@ final class GeminiLiveEngine: VoiceEngine {flush()}if let content = msg["serverContent"] as? [String: Any] {+ if let heard = (content["inputTranscription"] as? [String: Any])?["text"] as? String { link.add("user", heard) }+ if let said = (content["outputTranscription"] as? [String: Any])?["text"] as? String { link.add("voice", said) }+ if content["turnComplete"] as? Bool == true || content["interrupted"] as? Bool == true { link.endTurn() }if content["interrupted"] as? Bool == true {stopPlayback()dropping = false@@ -214,13 +226,24 @@ final class GeminiLiveEngine: VoiceEngine {}}if let calls = (msg["toolCall"] as? [String: Any])?["functionCalls"] as? [[String: Any]] {- let responses: [[String: Any]] = calls.compactMap { call in+ let asked: [(id: String, name: String, args: Data)] = calls.compactMap { call inguard 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]]+ let args = (try? JSONSerialization.data(withJSONObject: call["args"] as? [String: Any] ?? [:])) ?? Data("{}".utf8)+ return (id, name, args)+ }+ // The tools run on the computer; their answers go back together.+ toolsRunning += 1+ Task { [weak self, link] in+ var responses: [[String: Any]] = []+ for call in asked {+ let result = (try? JSONSerialization.jsonObject(with: await link.tool(call.name, arguments: call.args))) ?? [:]+ responses.append(["id": call.id, "name": call.name, "response": ["result": result]])+ }+ guard let self else { return }+ self.toolsRunning -= 1+ self.send(["toolResponse": ["functionResponses": responses]])+ self.flush()}- send(["toolResponse": ["functionResponses": responses]])}if let update = msg["sessionResumptionUpdate"] as? [String: Any],update["resumable"] as? Bool == true, let handle = update["newHandle"] as? String {@@ -242,7 +265,7 @@ final class GeminiLiveEngine: VoiceEngine {/// 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 }+ guard ready, turnDone, queued == 0, toolsRunning == 0, !pending.isEmpty else { return }let text = pending.joined(separator: "\n\n")pending.removeAll()turnDone = false@@ -350,13 +373,13 @@ final class GeminiLiveEngine: VoiceEngine {// MARK: helpers/// Gemini's schema spells types in capitals (`OBJECT`, `STRING`).- private static func geminiSchema(_ schema: [String: any Sendable]) -> [String: Any] {+ private static func geminiSchema(_ schema: [String: Any]) -> [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) ?? [:] }+ case let nested as [String: Any] where key == "properties":+ out[key] = nested.mapValues { ($0 as? [String: Any]).map(geminiSchema) ?? [:] }default: out[key] = value}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftindex 01364fcf..adfe60fb 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift@@ -26,9 +26,13 @@ final class OpenAIRealtimeEngine: VoiceEngine {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 let model: String+ private let voice: String+ /// The call on the computer: the client secret, the voice's instructions and tools, the transcript.+ private let link: CallLink+ private var session: CallSession?+ /// Tool calls still running on the computer: replies wait, so the model gets each result first.+ private var toolsRunning = 0private var pc: RTCPeerConnection?private var events: RTCDataChannel?private var mic: RTCAudioTrack?@@ -39,9 +43,10 @@ final class OpenAIRealtimeEngine: VoiceEngine {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+ init(model: String, voice: String, link: CallLink) {+ self.model = model+ self.voice = voice+ self.link = link}func start() async {@@ -49,8 +54,10 @@ final class OpenAIRealtimeEngine: VoiceEngine {return fail("Allow the microphone for Codync in Settings to talk to your bots.")}do {- let secret = try await credential()+ let session = try await link.start("realtime", provider: .openAI, model: model, voice: voice)guard !ended else { return }+ guard let secret = session.credential else { throw VoiceError("OpenAI sent no session credential.") }+ self.session = sessiontry await connect(secret: secret)} catch {guard !ended else { return }@@ -126,13 +133,13 @@ final class OpenAIRealtimeEngine: VoiceEngine {func speak(reply: String) {guard !ended, !phase.isFailed else { return }- pending.append(op.reply(reply))+ pending.append(link.reply(reply))flush()}func announce(_ notice: String) {guard !ended, !phase.isFailed else { return }- pending.append(op.notice(notice))+ pending.append(link.notice(notice))flush()}@@ -140,16 +147,21 @@ final class OpenAIRealtimeEngine: VoiceEngine {fileprivate func opened() {guard !ended else { return }- let tools: [[String: Any]] = CallOperator.tools.map {- ["type": "function", "name": $0.name, "description": $0.description, "parameters": $0.parameters]+ let declared = session.flatMap { (try? JSONSerialization.jsonObject(with: $0.tools)) as? [[String: Any]] } ?? []+ let tools: [[String: Any]] = declared.map {+ ["type": "function", "name": $0["name"] ?? "", "description": $0["description"] ?? "", "parameters": $0["parameters"] ?? [:]]}send(["type": "session.update","session": ["type": "realtime",- "instructions": op.instructions,+ "instructions": session?.instructions ?? "","tools": tools,- "audio": ["input": ["turn_detection": ["type": "semantic_vad"]]],+ // What the user says is transcribed too, for the call's line in the chat.+ "audio": ["input": [+ "turn_detection": ["type": "semantic_vad"],+ "transcription": ["model": VoiceSettings.transcribeModel(.openAI)],+ ]],] as [String: Any],])}@@ -164,19 +176,35 @@ final class OpenAIRealtimeEngine: VoiceEngine {flush()case "input_audio_buffer.speech_started": level = muted ? 0 : 0.7case "input_audio_buffer.speech_stopped": level = 0+ case "input_audio_buffer.committed": link.transcribing(true)+ case "conversation.item.input_audio_transcription.failed": link.transcribing(false)case "output_audio_buffer.started": phase = .speakingcase "output_audio_buffer.stopped", "output_audio_buffer.cleared": if phase == .speaking { phase = .listening }case "response.created": responding = truecase "response.done":responding = falseflush()+ case "conversation.item.input_audio_transcription.completed":+ link.add("user", msg["transcript"] as? String ?? "")+ link.endTurn()+ case "response.output_audio_transcript.done":+ link.add("voice", msg["transcript"] as? String ?? "")+ link.endTurn()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("")+ let args = Data((msg["arguments"] as? String ?? "{}").utf8)+ // The tool runs on the computer.+ toolsRunning += 1+ Task { [weak self, link] in+ let output = String(decoding: await link.tool(name, arguments: args), as: UTF8.self)+ guard let self else { return }+ self.toolsRunning -= 1+ guard !self.ended else { return }+ self.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.+ self.pending.append("")+ self.flush()+ }case "error":let error = msg["error"] as? [String: Any]log.error("realtime: \(error?["message"] as? String ?? "?", privacy: .public)")@@ -203,7 +231,7 @@ final class OpenAIRealtimeEngine: VoiceEngine {/// 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 }+ guard !responding, toolsRunning == 0, 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]],diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex 23bee883..3ff84bd5 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -73,7 +73,6 @@ extension BotStore {guard bots[botId]?.lead == true else { return }perform { try await $0.callStarted(botId) }}- public func logCall(_ botId: String, seconds: Int) { perform { try await $0.logCall(botId, seconds: seconds) } }public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }/// The bot's own agent again, off the fallback it runs on.public func switchBack(_ botId: String) { perform(replay: true) { try await $0.switchBack(botId) } }diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swiftnew file mode 100644index 00000000..d44b8475--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swift@@ -0,0 +1,22 @@+import CodyncKit+import Foundation++extension BotStore {+ /// A call starts on this device: what it carries stays out of the chat until its line arrives.+ func beginCall(_ call: String) {+ liveCalls.insert(call)+ }++ /// A finished call's line, with the rest of its transcript; the chat then shows the call's messages behind it.+ func endCall(_ botId: String, seconds: Int, call: String, lines: [CallLine]) async {+ do {+ let line = try await withLink(replay: true) {+ try await $0.endCall(botId: botId, call: call, seconds: seconds, lines: lines)+ }+ if let line { upsert(line) }+ } catch {+ lastError = error.localizedDescription+ }+ liveCalls.remove(call)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swiftindex 951f6b8a..82a185e5 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sending.swift@@ -62,12 +62,18 @@ extension BotStore {send(text, to: botId, replyTo: nil, nonce: UUID().uuidString, files: files)}+ /// Said on voice call `call` (on-device or speech to text): the chat shows it in the call's conversation.+ public func send(_ text: String, to botId: String, call: String) {+ send(text, to: botId, replyTo: nil, nonce: UUID().uuidString, call: call)+ }+@discardableResultfunc send(_ text: String, to botId: String, replyTo: ReplyQuote?, nonce: String, files: [OutgoingFile] = [],- pasted: [String] = []) -> Task<SendProgress, Never>? {+ pasted: [String] = [], call: String? = nil) -> Task<SendProgress, Never>? {let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)guard !trimmed.isEmpty || !files.isEmpty, !retired else { return nil }var data = EntryData(text: trimmed, status: "sending", clientNonce: nonce)+ data.call = call// Shown at once; the computer's own quote replaces it.data.replyTo = replyToif !files.isEmpty {@@ -81,14 +87,15 @@ extension BotStore {upsert(local)storage.lastComputerId = computer.idif let bot = bots[botId] { onSent?(bot, .sending) }- // The relay mailbox holds text only: files wait for the computer.- if canQueue, files.isEmpty, let remote = transport as? any RemoteTransport {+ // The relay mailbox holds text only: files, and the call a message was said in, wait for the computer.+ if canQueue, files.isEmpty, call == nil, let remote = transport as? any RemoteTransport {return enqueue(remote, text: trimmed, botId: botId, replyTo: replyTo?.id, nonce: nonce)}- return deliver(trimmed, botId: botId, replyTo: replyTo?.id, nonce: nonce, pasted: pasted)+ return deliver(trimmed, botId: botId, replyTo: replyTo?.id, nonce: nonce, pasted: pasted, call: call)}- private func deliver(_ text: String, botId: String, replyTo: String?, nonce: String, pasted: [String] = []) -> Task<SendProgress, Never> {+ private func deliver(_ text: String, botId: String, replyTo: String?, nonce: String, pasted: [String] = [],+ call: String? = nil) -> Task<SendProgress, Never> {Task {do {// Safe to repeat: the computer skips a nonce it already has.@@ -106,7 +113,7 @@ extension BotStore {}try Task.checkCancellation()return try await client.send(botId: botId, text: text, clientNonce: nonce, replyTo: replyTo, attachments: ids,- pasted: pasted)+ pasted: pasted, call: call)}outgoingFiles[nonce] = nilupsert(e)diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex f357626b..692cc595 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -118,6 +118,8 @@ public final class BotStore {let end: @MainActor () -> Void}@ObservationIgnored var voiceCalls: [UUID: VoiceCall] = [:]+ /// The calls this device is on: what they carry stays out of the chat (`hidingCalls`).+ public internal(set) var liveCalls: Set<String> = []@ObservationIgnored var shortcutSends = 0var saveTask: Task<Void, Never>?var rewound = falsediff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex e69d71a2..f7c06ee1 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -16,6 +16,8 @@ struct ChatRow: View {var addFallback: (() -> Void)?/// An artifact card's artifact, full size.var openArtifact: ((ArtifactRef) -> Void)?+ /// A voice call's line: the call's conversation.+ var openCall: (() -> Void)?@Environment(BotStore.self) private var model@Environment(\.accessibilityReduceMotion) private var reduceMotion@@ -54,6 +56,8 @@ struct ChatRow: View {HandoffCardRow(entry: entry, card: card).padding(.top, 10)} else if let change = entry.data.agentSwitch {AgentSwitchRow(entry: entry, change: change).padding(.top, 10)+ } else if entry.data.call != nil, let openCall {+ CallLineRow(entry: entry, open: openCall).padding(.top, 6)} else {NoticeRow(entry: entry, addFallback: addFallback).padding(.top, 10)}@@ -224,8 +228,9 @@ struct NoticeRow: View {var body: some View {let text = entry.data.text ?? ""+ // A call an older app logged, with no conversation to open.if let seconds = entry.data.callSeconds {- Label("\(text) · \(String(format: "%02d:%02d", seconds / 60, seconds % 60))", systemImage: "waveform")+ Label("\(L10n.tr(text)) · \(String(format: "%02d:%02d", seconds / 60, seconds % 60))", systemImage: "waveform").font(.footnote.monospacedDigit()).foregroundStyle(Palette.secondary).frame(maxWidth: .infinity)diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex f8552e64..1b45fbed 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -15,6 +15,7 @@ public struct ThreadView: View {@State var replyingTo: Entry?@State var botChat: BotChatTarget?@State var openArtifact: ArtifactTarget?+ @State var openCall: Entry?@State var editingGroup = false@State var details: DetailsRequest?@State var calling = false@@ -74,6 +75,7 @@ public struct ThreadView: View {}.codyncSheet(item: $botChat) { BotConversationView(botId: botId, peerId: $0.id) }.codyncSheet(item: $openArtifact) { ArtifactView(target: $0) }+ .codyncSheet(item: $openCall) { CallConversationView(line: $0) }.codyncSheet(item: $details) { request inBotDetailsView(botId: request.botId ?? botId, request: request) { artifact indetails = nil@@ -113,7 +115,8 @@ public struct ThreadView: View {reply: e.isReplyable && model.mismatch == nil ? { reply(to: e) } : nil,// In a group, the bot whose agent failed.addFallback: { details = DetailsRequest(botId: e.data.author ?? e.botId) },- openArtifact: { openArtifact = ArtifactTarget(botId: e.botId, id: $0.id, title: $0.title) })+ openArtifact: { openArtifact = ArtifactTarget(botId: e.botId, id: $0.id, title: $0.title) },+ openCall: { openCall = e }).equatable()}}@@ -320,7 +323,8 @@ extension ThreadView {/// scrolls up; the chat follows the newest message until they scroll away, and a reply is/// revealed steadily as it's written.var transcript: some View {- let items = ChatItem.build(model.chat(botId))+ // What voice calls carried shows in each call's conversation, not in the chat.+ let items = ChatItem.build(model.chat(botId).hidingCalls(live: model.liveCalls))var rows: [ConversationRow] = []if moreOnComputer {rows.append(ConversationRow("earlier") {diff --git a/apps/ios/Kit/Tests/CodyncKitTests/CallTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/CallTests.swiftnew file mode 100644index 00000000..02c98a52--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/CallTests.swift@@ -0,0 +1,35 @@+import Foundation+import Testing+@testable import CodyncKit++private func entry(_ id: String, _ kind: String, at: Int64, _ json: String) throws -> Entry {+ let data = try JSONDecoder().decode(EntryData.self, from: Data(json.utf8))+ return Entry(id: id, seq: at, botId: "b", rev: 1, kind: kind, turn: 1, data: data, createdAt: at, updatedAt: at)+}++@Test func finishedAndLiveCallsHideWhatTheyCarried() throws {+ let entries = [+ try entry("u1", "user", at: 1, #"{"text":"spoken","call":"c"}"#),+ try entry("a1", "agent", at: 2, #"{"text":"reply","final":true,"call":"c"}"#),+ try entry("u2", "user", at: 3, #"{"text":"no line yet","call":"lost"}"#),+ try entry("u3", "user", at: 4, #"{"text":"on this phone","call":"live"}"#),+ try entry("local-n", "user", at: 5, #"{"text":"didn't go out","call":"live","status":"failed"}"#),+ try entry("n1", "notice", at: 6, #"{"text":"Release plan","callSeconds":26,"call":"c"}"#),+ ]+ #expect(entries.hidingCalls(live: ["live"]).map(\.id) == ["u2", "local-n", "n1"])+}++@Test func aCallsConversationMergesItsTranscriptWithWhatItCarried() throws {+ let line = try entry("n1", "notice", at: 10, #"""+ {"text":"Git","call":"c","transcript":[{"from":"user","text":"看一下 git","at":1},{"from":"voice","text":"Clean.","at":9}]}+ """#)+ let entries = [+ try entry("u1", "user", at: 2, #"{"text":"check git","call":"c","from":"voice"}"#),+ try entry("a1", "agent", at: 3, #"{"text":"Working tree clean","final":true,"call":"c"}"#),+ try entry("t1", "agent", at: 4, #"{"text":"narration","call":"c"}"#),+ try entry("x1", "user", at: 5, #"{"text":"typed"}"#),+ line,+ ]+ let said = entries.callConversation(line).map { "\($0.speaker): \($0.text)" }+ #expect(said == ["user: 看一下 git", "voiceToBot: check git", "bot: Working tree clean", "voice: Clean."])+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftindex 99dd0319..d9db3d79 100644--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift@@ -563,44 +563,6 @@ extension FakeRemote {#expect(await fake.calls.filter { $0 == "respondPermission" }.count == 1)}-// MARK: - Voice call operator--/// The realtime voice operator's tools run against the store, the same paths the chat uses.-@MainActor @Test func callOperatorToolsDriveTheBot() async throws {- let (storage, suite) = context()- defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }- let fake = FakeRemote(.ready(.direct))- let store = BotStore(computer: randomComputer("Mac"), storage: storage) { _ in fake }- defer { store.retire() }- store.setActive(true)- #expect(await until { await fake.subscribed })- await fake.emit(#"{"type":"bot","bot":{"id":"b1","name":"Ada","rev":1,"lastAt":1}}"#)- #expect(await until { store.connection == .online })- let op = CallOperator(model: store, botId: "b1")-- func json(_ s: String) -> [String: Any] {- (try? JSONSerialization.jsonObject(with: Data(s.utf8))) as? [String: Any] ?? [:]- }-- #expect(json(op.call("send_to_bot", arguments: ["text": " run the tests "]))["sent"] as? Bool == true)- #expect(await until { await fake.sent == ["run the tests"] })- #expect(json(op.call("send_to_bot", arguments: [:]))["error"] != nil)- #expect(json(op.call("answer_approval", arguments: ["option": "yes"]))["error"] as? String == "Nothing is waiting for approval.")-- await fake.emit(#"{"type":"entry","entry":{"id":"p1","seq":5,"botId":"b1","rev":5,"kind":"permission","turn":1,"data":{"title":"Run npm test","status":"pending","options":[{"optionId":"a","name":"Allow once","kind":"allow_once"},{"optionId":"r","name":"Reject","kind":"reject_once"}]},"createdAt":1,"updatedAt":1}}"#)- #expect(await until { store.chat("b1").contains { $0.id == "p1" } })- let status = json(op.call("bot_status", arguments: [:]))- #expect((status["approval"] as? [String: Any])?["options"] as? [String] == ["Allow once", "Reject"])- #expect(json(op.call("answer_approval", arguments: ["option": "maybe"]))["error"] as? String == "No such option.")- #expect(json(op.call("answer_approval", arguments: ["option": "allow"]))["answered"] as? String == "Allow once")- #expect(store.answering["p1"] == "a")-- let recent = json(op.call("recent_messages", arguments: ["count": 1]))["messages"] as? [[String: String]]- #expect(recent?.count == 1)- #expect(recent?.first?["from"] == "approval request")- #expect(op.reply("**Done**, see `x`").hasPrefix("[Ada replied] "))-}-/// Approvals reach a call as notices, replies as replies (a realtime operator words them differently).@MainActor @Test func voiceCallGetsApprovalsAsNotices() async throws {let (storage, suite) = context()diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.mdindex 0eda8f21..3fb12942 100644--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@ -26,6 +26,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- 通話中在設定換了語音(例如從本機換成 Gemini),關掉設定後通話就改用新的語音繼續,不必掛斷重打。- 語音通話連線中,通話列會顯示一條左右來回的線,真正連上、聽得到你說話後才換回音量點點。- 有多台電腦時,Bot 列表中每台電腦的標題列都有自己的「擴充套件」按鈕,電腦的連線狀態也靠右對齊;擴充套件裡不再能切換電腦。+- 通話內容不再塞滿聊天:結束後只留一行,標題寫著這通電話在談什麼,點開可以看完整逐字稿;Bot 的記憶也會記住你在通話裡說的話。+- Gemini 與 OpenAI 的語音是 Bot 的轉接者:它知道你的記憶、Bot 的設定、專案現況和最近的對話,轉給 Bot 時附上你說的原話,也能停止 Bot、查 Bot 的記憶。### en-US- Every computer has a lead bot, starred on top of the Bots list: it follows up on what you're working on, checks in twice a day for anything worth a reminder or a head start, asks for access to services like Gmail or your calendar when it would help, and speaks first when you call it.@@ -45,6 +47,8 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o- Pick another voice in the call settings mid-call (on-device to Gemini, say) and the call carries on with it once you close them.- While a voice call connects, the call bar shows a line gliding back and forth until the voice can really hear you.- With several computers, each computer's heading in the Bots list has its own Extensions button, with its connection status on the right; Extensions no longer switches computers.+- Calls no longer fill the chat: each one leaves a single line titled with what it was about; tap it for the full transcript. The bot's memory keeps what you said on the call.+- The Gemini and OpenAI voice relays to your bot: it knows your memory, the bot's setup, the project and the recent conversation, passes your own words along, and can stop the bot or look up what it remembers.## 2.24.0diff --git a/docs/architecture/file-structure.md b/docs/architecture/file-structure.mdindex 6be35b9d..c1adbb55 100644--- a/docs/architecture/file-structure.md+++ b/docs/architecture/file-structure.md@@ -91,6 +91,7 @@ Codync/| Agent process, ACP, queue and session lifecycle | `host/src/agent/bot/` (`launch.rs`, `queue.rs`, `session.rs`, `turn.rs`, `updates.rs`), `acp.rs` || Compaction timing and rollover | `host/src/agent/bot/compaction.rs`, the handoff card in `host/src/chat/handoff.rs`; the rules in `codync-mem`'s `compaction.rs` || Group room turns / bot-to-bot requests | `host/src/chat/group.rs` / `team.rs` |+| Voice calls (the call, the voice's instructions and tools, transcripts, call lines) | `host/src/chat/calls/` (`mod.rs`, `context.rs`, `project.rs` the git state, `tools.rs`); the user's messages it relays go through `host/src/chat/messages.rs` like typed ones; clients' `CallLink` (iPhone `CodyncUI/Call/CallLink.swift`, desktop `views/call/call-link.ts`, Android `core/Calls.kt` + `HostCallLink.kt`) and call rows (`CallRows`) || Team management (bots creating and changing bots) | `host/src/chat/manage.rs`, its approval card (`Cmd::Approve`) in `agent/bot/updates.rs` || Prompt snapshots and memory | `host/src/chat/context.rs`, `memory/` (`api.rs` the apps' read-only view, `tools.rs` and `file_tools.rs` the MCP tools, `files.rs` the folders and scan, `turns.rs` which bot's turn a found change is credited to, `file_api.rs`, `dream.rs`, `import.rs`); the rules in `host/crates/memory` (`codync-mem`: files and facts in `files/`, dreaming in `dream/`, tombstones in `store.rs`, the old entries in `legacy.rs`); harnesses' own memory turned off in `host/src/agent/own_memory.rs` || Identity, encryption and direct channel | `host/src/remote/identity.rs`, `crypto.rs`, `channel.rs` |diff --git a/docs/features/context-and-memory.md b/docs/features/context-and-memory.mdindex 7c9c2b2a..34ffe400 100644--- a/docs/features/context-and-memory.md+++ b/docs/features/context-and-memory.md@@ -206,8 +206,10 @@ Claude Code's own memory; the rules live in the `codync-mem` crate, and `chat/meto keep, and re-applies the instructions afterwards; it can't make a harness keep anything.- A session a harness has deleted (for example, one cleaned up after a month) can't be resumed. The botstarts fresh, but its memory remains.-- Memory search is a substring scan, not semantic vectors. Voice transcripts aren't marked yet, so dreaming- treats them like typed text. Group rooms don't feed dreaming.+- Memory search is a substring scan, not semantic vectors. A voice call's transcript feeds dreaming from the call's+ line: what the user said counts as their own words (spoken, not typed), the voice's lines and what it relayed to+ the bot (`from: voice`) are context only ([voice call](voice-call.md#the-call-on-the-host)). Group rooms don't+ feed dreaming.- `search_history` covers the bot's own chat, not group chats it took part in. It finds messages by words, orreads back from a message id (`from`, then each page's `next`); `search_memory` gives each `MEMORY.md` line'ssource message, so a bot can check where a memory came from.diff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex 0b23cdf4..bd80081b 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -2,8 +2,9 @@A hands-free call with one bot or group from the iPhone, Android or desktop chat (the waveform button in an empty composer).On Linux the desktop app offers only the cloud engines (on-device speech is macOS only). The terminal-UI has no calls (no audio stack); it shows 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.+UI has no calls (no audio stack); it shows a call's line like every client and `o` unfolds its conversation.+The bot is the same agent on the computer; the call only changes how you talk to it. The host runs every call+([the call on the host](#the-call-on-the-host)); the clients only carry audio.On iOS, [Open Live Mode in Shortcuts](ios-shortcuts.md) can select a bot and start this call directly (no bot: the lead).Every other bot waits for you to speak; the [lead bot](lead-bot.md) speaks first: once a call's audio is live theapps send `callStarted {botId}` (once per call, only to a lead), and the host has a lead with no turn under way open@@ -12,7 +13,7 @@ with a sentence or two, read aloud like any reply.## On-device voice- `apps/ios/Kit/Sources/CodyncUI/Call/` (iPhone) and `apps/desktop/src/renderer/views/call/` (desktop): `CallView` (the call bar) over a `VoiceEngine`; `OnDeviceEngine` is the default audio loop. On the Mac the desktop app runs speech recognition in `codync-speech` (`apps/desktop/native/speech-macos/`, driven by `apps/desktop/src/main/speech.ts`).-- Android: `CallBar` (`apps/android/app/.../VoiceControls.kt`) over the same `VoiceEngine` set, ported into `apps/android/core` (`VoiceEngine.kt`, `CloudSpeechEngine.kt`, `GeminiLiveEngine.kt`, `OpenAIRealtimeEngine.kt`, `CallOperator.kt`) with the phone's audio in the app (`VoiceAudioPorts.kt`, `WebRtcPeer.kt`). On device is `VoiceSession` (`LocalVoiceAudio.kt`): the call's language (Voice chat settings → Language, the phone's by default) is heard by Android's on-device recognizer on Android 13+, fed the call's own microphone (`PlatformSpeech.kt`; Android asks before downloading a language), with the bundled Vosk model for English where Android has none; each reply is read by an installed offline voice for the language it's written in, and a reply with no installed voice stays in chat with a notice; `VoiceService` (a microphone foreground service) holds audio focus and the Bluetooth/wired route for the call. Settings keys match the iPhone's (`callEngine`, `callMode.<provider>`, …).+- Android: `CallBar` (`apps/android/app/.../VoiceControls.kt`) over the same `VoiceEngine` set, ported into `apps/android/core` (`VoiceEngine.kt`, `CloudSpeechEngine.kt`, `GeminiLiveEngine.kt`, `OpenAIRealtimeEngine.kt`, `Calls.kt`) with the phone's audio in the app (`VoiceAudioPorts.kt`, `WebRtcPeer.kt`). On device is `VoiceSession` (`LocalVoiceAudio.kt`): the call's language (Voice chat settings → Language, the phone's by default) is heard by Android's on-device recognizer on Android 13+, fed the call's own microphone (`PlatformSpeech.kt`; Android asks before downloading a language), with the bundled Vosk model for English where Android has none; each reply is read by an installed offline voice for the language it's written in, and a reply with no installed voice stays in chat with a notice; `VoiceService` (a microphone foreground service) holds audio focus and the Bluetooth/wired route for the call. Settings keys match the iPhone's (`callEngine`, `callMode.<provider>`, …).- 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@@ -29,15 +30,14 @@ with a sentence or two, read aloud like any reply.- Speech → text with `SFSpeechRecognizer` (on-device when the language supports it) in the languagepicked under Voice chat → Language (`callLanguage`; empty follows the system's first language,which is often English on bilingual setups). A pause ends an- utterance and sends it as an ordinary message (`BotStore.send`), so it takes the normal path:- queued while the bot works, folded into its next turn. What you said appears in the chat as your- message; the bot's reply appears as its message.+ utterance and sends it as the call's message (`BotStore.send` with the call's id), so it takes the normal+ path: queued while the bot works, folded into its next turn. It and the bot's replies show in the call's+ conversation, not in the chat (below).- 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: 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`) that- every client shows as "Voice chat · 00:16".+- Ending the call calls `endCall` (older apps `logCall`); the call's line is described below.- The host receives recognized text; the Cloudflare transport sees encrypted channel frames.Codync does not forward microphone audio to the host. Speech recognition may use Apple serviceswhen on-device recognition is unavailable. `UIBackgroundModes: audio` permits@@ -238,16 +238,66 @@ shows the provider's name next to the dots whenever audio leaves the device.- 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 call on the host++Every call, whatever its engine, is run by the host (`host/src/chat/calls/`, stage 1 of+[host-owned voice](../plans/voice-architecture.md)); the clients' `CallLink` (iPhone, desktop, Android) only+carries audio and talks to these methods:++- **`startCall`** `{botId, callId, mode: realtime | speech | device, provider?, model?, voice?, language?}` keeps the+ call (in `kv`, so a host restart loses nothing) and returns `{credential?, instructions, tools}`: a realtime+ provider's short-lived credential, the voice's instructions and its tools. Called again with the same id when a+ provider session is resumed or replaced (Gemini's `goAway`, a new OpenAI session), so the background is fresh;+ the transcript so far stays. On-device and speech-to-text calls start one too (no credential, no voice model).+- **The instructions** (`calls::context`) put the voice's role first: it is the relay for the bot (or group, with+ its members), the switchboard operator, not the bot; it passes the user's requests on with `send_to_bot`, tells+ the user what the bot says and asks for what's missing; it speaks of the bot in the third person and never claims+ it did or saw something; anything about code, files, the computer or the project goes to the bot even when it+ thinks it knows. Then the background, as named sections that say where they came from, each capped (about 16k+ characters in all on Gemini, six tenths of that on OpenAI), empty ones left out: now (the computer's date, time,+ weekday and offset; the phone's language), about the user (the shared `MEMORY.md` and its notes' names and+ descriptions, when the bot uses it), this bot (name, description, harness and model, folder and project,+ permission mode, connectors, skills, computer use, routines; a group's members), what the bot remembers (its+ `MEMORY.md` and notes index), the project now (git branch, changed files, the last three commits; outside a+ repository, or without the command line tools on macOS, nothing), current work (status, activity, a pending+ approval and its options, queued messages, the last failure), the conversation (the last 20 chat messages in+ spoken form and the titles and gist of the last three calls), the other bots on this computer, and files and+ artifacts shared in the chat. **All of it goes to the voice provider, on the user's own key.**+- **`callTool`** `{callId, name, arguments, lines}` → `{result}` runs the voice's tool calls on the host+ (`calls::tools`): `send_to_bot(text)`, `bot_status()` (a group's: its busy member's), `recent_messages(count)`,+ `answer_approval(option)` (only after the user said which; matched by option name or id), `stop_bot()`,+ `search_memory(query)`. A failure is the tool's answer. The engines hold replies while a tool runs, so the model+ gets each result first.+- **The user's own words:** `send_to_bot` attaches what the user said since the bot last heard from the call, word+ for word from the transcript ("[The user's own words on the call: «…»]"), so the bot sees both, and the message+ is marked `from: voice`: the voice may rephrase or translate, so memory never quotes it.+- **`callLines`** `{callId, lines: [{from: user | voice, text, at}]}` appends the transcript as it is spoken, turn+ by turn: Gemini's `inputAudioTranscription` / `outputAudioTranscription`, OpenAI's input transcription and+ `response.output_audio_transcript.done`. The iPhone and Android turn Chinese into the reader's script first+ (Gemini answers in Simplified for a Traditional speaker); the desktop can't (no ICU transform in Chromium).+- **In order** (`CallLink` in each client): `callLines`, `callTool` and `endCall` leave one at a time, and+ `callTool` and `endCall` carry the lines not sent yet (`lines`, a line still being said included), so a hand-off+ always has the words it hands on. Lines a request didn't deliver go with the next one. OpenAI writes the user's+ words down after their turn: a tool call waits up to 2 s for them (`input_audio_buffer.committed` until the+ transcription arrives or fails).+- **Hidden in the chat:** everything a call sends the bot carries the call's id (`data.call`), and so do the bot's+ replies in those turns while the call lasts, a group's members' included (a turn that also answers a typed+ message stays visible, and a reply after the call ends shows). Every client leaves them out of the chat once the+ call's line is there, or while this device is on the call (`hidingCalls`); a message that failed to send stays,+ with Resend. The roster's preview and unread count skip them too. The bot gets them as usual.+- **`endCall`** `{botId, callId, seconds, lines}` adds the last lines and writes the call's line: a notice with+ `call`, `callSeconds` and the `transcript`. A call ends once (`call.ended.<id>` in `kv`), so the apps retry it+ across a reconnect; an ended call can't start again. The call's actors (a group's members) hear `CallEnded`. A one-shot of the bot's harness (`chat::oneshot`) titles it from the conversation, in the user's+ language, into the notice's `text` ("Voice chat" until then, or when there's nothing to sum up); older apps+ show the title too. The line shows a waveform, the title and the length; tapping it opens the conversation+ (iPhone and Android sheets, the desktop `Sheet`, `o` in the terminal): the user's lines, the voice's lines, what+ it relayed and the bot's messages, in order. `logCall` stays for older apps.+- **Memory:** dreaming reads the call's line: the user's spoken lines are their own words, the voice's lines and+ its relayed messages context only, and a call's spoken lines count toward the dream trigger; the call's end+ asks for a run soon.++### How the voice talks-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, reply- in the user's language, keep spoken answers short.-- 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; matched by option name).- Each new final reply is added to the realtime conversation as `[<bot> replied] …` and an approvalas `[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.@@ -262,8 +312,6 @@ The realtime model is an operator in front of the bot, not a replacement for itspeaker again each time: the engine stops itself then, and without both the microphone stays quiet, or theplayer never finishes its buffers so the phase stays "speaking" and the bot's replies are never said.A reply counts as played once its buffers are rendered (`.dataRendered`).-- The chat stays the record: only `send_to_bot` messages and the bot's replies are entries. The- operator's small talk isn't saved; the call still ends with the "Voice chat" notice.### Failure and cost@@ -289,8 +337,10 @@ buffers never finished, so the phase stayed "speaking" and the bot's reply was nanswer returned to listening, and several turns in English and Chinese followed, without Gemini hearing itself.A route change mid-call (AirPods) is not checked yet.-`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. On Android, `VoiceEnginesTest` (core, JVM) drives+Host tests (`chat::calls`) cover a call's flow (start, lines, `send_to_bot` with the user's words, the line at the+end), the voice's instructions (the relay role and the bot's name first, each section present and within its cap,+OpenAI's smaller share), transcript checks and dreaming over a call. `StoreTests` cover approvals reaching a call+as notices; each client tests hiding a call's messages and merging its conversation. On Android, `VoiceEnginesTest` (core, JVM) driveseach engine through fake audio: utterance cutting and clip playback, OpenAI's event sequence and SDPexchange (MockWebServer), and a Gemini Live session over a real WebSocket (setup, audio both ways,a tool call, a close with the provider's reason). Provider audio isn'tdiff --git a/docs/plans/voice-architecture.md b/docs/plans/voice-architecture.mdindex 0a6ee9f3..53aab2f6 100644--- a/docs/plans/voice-architecture.md+++ b/docs/plans/voice-architecture.md@@ -1,7 +1,7 @@# Voice calls owned by the host-Status: in progress (owner's go-ahead, 2026-10-25). Supersedes [voice call transcripts](voice-call-transcripts.md),-which becomes stage 1 of this plan. Current behavior: [voice call](../features/voice-call.md).+Status: stage 1 shipped (2.25.0); stages 2–4 planned. Supersedes [voice call transcripts](voice-call-transcripts.md),+which became stage 1 of this plan. Current behavior: [voice call](../features/voice-call.md#the-call-on-the-host).A realtime voice model (Gemini Live, OpenAI Realtime) stays in front of the bot: coding agents are text-only andslow, so the voice talks and the bot works. What changes is how it hands over. Today each client (iPhone, Android,@@ -18,7 +18,7 @@ phone / desktop (audio only) host (all logic) the botEach stage ships on its own (after-change, merged into `dev`), all clients together.-### 1. The call on the host+### 1. The call on the host (shipped)- **`startCall`** `{botId, callId, provider?, model?, voice?, mode}` creates the call and returns everything aclient needs: the provider credential (realtime and speech modes), the voice's instructions and the tool@@ -80,5 +80,6 @@ Each stage ships on its own (after-change, merged into `dev`), all clients toget## Compatibility-New methods and fields are additive. The phone apps need a host with `startCall`, so they raise `minHost` to the-release that ships stage 1 (the desktop app bundles its host). `logCall` stays until `minApp` passes it.+New methods and fields are additive. The apps need a host with `startCall`, so the iPhone, Android and desktop apps+raise `minHost` to the release that ships stage 1 (a Linux desktop or an SSH computer may run an older host).+`logCall` stays until `minApp` passes it.diff --git a/docs/plans/voice-call-transcripts.md b/docs/plans/voice-call-transcripts.mdindex 330f5622..6bfcdafa 100644--- a/docs/plans/voice-call-transcripts.md+++ b/docs/plans/voice-call-transcripts.md@@ -1,9 +1,9 @@# Voice call transcripts-Status: planned (owner's request, 2026-10-25). Today a realtime call (OpenAI Realtime, Gemini Live) keeps only what-the voice model forwarded with `send_to_bot` and the bot's replies; the rest of the conversation is lost, so the bot-and its memory never see it, and the chat gets a bare "Voice chat · 00:26" line. Current behavior:-[voice call](../features/voice-call.md), [context and memory](../features/context-and-memory.md).+Status: superseded and shipped as stage 1 of [voice calls owned by the host](voice-architecture.md) (2.25.0):+transcripts, the titled call line, hidden call messages and dreaming over calls, with the host running the call.+Current behavior: [voice call](../features/voice-call.md#the-call-on-the-host). The original plan stays below for+the record.## Goaldiff --git a/docs/reference/analytics-events.md b/docs/reference/analytics-events.mdindex 0a5273f6..33a786bc 100644--- a/docs/reference/analytics-events.md+++ b/docs/reference/analytics-events.md@@ -81,7 +81,7 @@ host answers and sends it once the host is up.| `routine_run` | host | `runRoutine` | — || `routine_retried` | host | `retryRoutineRun` (the retry button on a failed run's notice) | — || `voice_call_started` | host `track` (desktop), iOS, Android | A voice call starts, with the engine it really uses after any fallback | `engine` (`on_device`; `openai`/`gemini` realtime; `cloud`: cloud speech to text and back) |-| `voice_call_finished` | host | `logCall` | `seconds` |+| `voice_call_finished` | host | `endCall` (older apps `logCall`) | `seconds` || `remote_screen_opened` | host | `screenPrepare` (each connection, reconnects included) | — || `screen_taken_over` | host | `screenTakeover` (taking control, not handing it back) | — || `connector_installed` | host | `installConnector`; a Composio app once its connection is `active` | `connector` (catalog name, `composio` or `custom`) |diff --git a/docs/reference/compatibility.md b/docs/reference/compatibility.mdindex 598ef543..aa8486c8 100644--- a/docs/reference/compatibility.md+++ b/docs/reference/compatibility.md@@ -141,6 +141,7 @@ Update this table in the release that changes a floor, with the reason.| Release | Host `minApp` | Client `minHost` | Why ||---|---|---|---|+| 2.25.0 | 2.21.0 | 2.25.0 (iPhone, Android, desktop) | Voice calls run on the host: the apps start a call, run the voice's tools and end it through `startCall`, `callTool`, `callLines` and `endCall`, which older hosts lack (a Linux desktop or an SSH computer can run one). `logCall` stays for older apps. || 2.21.0 | 2.21.0 | 2.20.1 | Memory is files the bot keeps, and the apps only read it: the edit methods (`saveMemory`, `pinMemory`, `archiveMemory`, `forgetMemory`, `clearMemory`, `undoDream`, `answerMemory`, `undoMemory`, `saveMemoryFile`, `deleteMemoryFile`, `restoreMemoryFile`) are gone, so older apps' memory buttons would fail. `memory` keeps its shape, so new apps still read an older host's memory. || 2.20.1 | 2.20.1 | 2.20.1 | Reply threads gave way to quote replies: the `thread` method, `send.threadId`, `markRead.threadId`, entry `threadId`, `data.thread` and bot `workingThread` are gone, and old thread replies sit in the main chat. Older apps would open empty threads. The clients no longer leave thread replies out of the chat or read threads, so an older host would show them inline, routine results twice and thread unread counts that never clear. || 2.18.0 | 2.18.0 | 2.12.0 | Memory moved from Engram into the host: the memory methods take and return the new two layers, and the Engram ones (`memoryDetail`, `reviewMemory`, `exportMemory`, `importMemory`) are gone. Clients still talk to older hosts; only their memory screen shows an error there. |diff --git a/host/src/agent/bot/cmd.rs b/host/src/agent/bot/cmd.rsindex 35ed0bbf..df934010 100644--- a/host/src/agent/bot/cmd.rs+++ b/host/src/agent/bot/cmd.rs@@ -65,6 +65,10 @@ pub enum Cmd {Reconfigure(Box<BotConfig>),/// The user wants the bot's own agent again (`switchBack`).SwitchBack,+ /// A voice call ended (`chat::calls`): its replies show in the chat again, and dreaming reads it.+ CallEnded {+ call: String,+ },Shutdown,}diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 8de11e56..ae87bbde 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -102,6 +102,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {dreamer,turn_text: None,turn_entries: Vec::new(),+ turn_call: None,turn_memory_revision: String::new(),announce: None,turn: None,@@ -259,6 +260,8 @@ struct Actor {turn_text: Option<String>,/// The user messages this turn answers (none when it isn't the user's).turn_entries: Vec<String>,+ /// The voice call this turn answers while it lasts: its replies carry it (`chat::calls`).+ turn_call: Option<String>,/// The memory change this turn's notice told the agent about (see `memory::change_notice`).turn_memory_revision: String,/// A profile update this turn carried, recorded once the agent got it.@@ -400,6 +403,9 @@ impl Actor {/// Adds an entry to the current lane, signed by this bot (a group shows who said it).fn add(&self, kind: EntryKind, turn: i64, mut data: Value) -> Option<Entry> {data["author"] = self.cfg.id.clone().into();+ if let (EntryKind::Agent, Some(call)) = (kind, &self.turn_call) {+ data["call"] = call.clone().into();+ }self.hub.add_entry(&self.lane, kind, turn, &data)}diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex 2e60ec6f..d8c71026 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -58,6 +58,12 @@ impl Actor {let _ = self.dreamer.send(memory::DreamEvent::Flush);}Cmd::SwitchBack => self.switch_back().await,+ Cmd::CallEnded { call } => {+ if self.turn_call.as_ref() == Some(&call) {+ self.turn_call = None;+ }+ let _ = self.dreamer.send(memory::DreamEvent::Flush);+ }Cmd::Reconfigure(base) => {let old = std::mem::replace(&mut self.base, *base);// On its own agent the bot takes the new one; on a fallback it keeps that agent (its step may havediff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 64973cdd..b56aeee9 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -104,6 +104,9 @@ impl Actor {let from_user = !hidden && self.source() == TurnSource::User;self.turn_text = from_user.then(|| text.to_owned());self.turn_entries = if from_user { entry_ids.to_vec() } else { Vec::new() };+ // A room turn answers the user's message in the room; another turn, the messages it was given.+ let answered = self.active_group.as_ref().map_or(self.turn_entries.as_slice(), |g| g.answers.as_slice());+ self.turn_call = crate::chat::calls::of_turn(&self.hub.store, answered);self.turn_memory_revision.clear();self.announce = None;self.stop_requested = false;diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex 0f23777d..c1d19dc6 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -87,7 +87,7 @@ fn call_event(method: &str, b: &Value, p: &mut Map<String, Value>) -> Option<Eve"deleteRoutine" => Event::RoutineDeleted,"runRoutine" => Event::RoutineRun,"retryRoutineRun" => Event::RoutineRetried,- "logCall" => {+ "logCall" | "endCall" => {p.insert("seconds".into(), b["seconds"].as_u64().unwrap_or(0).into());Event::VoiceCallFinished}diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex 20be8461..d54c00b9 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -142,7 +142,6 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<ContrSome(id) => Some(crate::chat::replies::quote(&hub.store, bot, id)?),None => None,};- let lane = Lane::main(bot);let mut attachments = Vec::new();if !uploads.is_empty() {let root = crate::chat::uploads::root(&row.config);@@ -150,10 +149,7 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contrattachments.push(crate::chat::uploads::resolve(&root, id)?.1);}}- let turn = hub.store.max_turn(bot) + 1;- // A group has no agent of its own to queue behind: its message is simply sent.- let status = if row.config.is_group() { "sent" } else { "queued" };- let mut data = json!({"text": text, "clientNonce": nonce, "status": status, "attachments": attachments});+ let mut data = json!({"text": text, "clientNonce": nonce, "attachments": attachments});// What the user pasted rather than typed: memory never takes it as the user's own words.let pasted: Vec<&str> = b["pasted"].as_array()@@ -169,37 +165,47 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contrif let Some(reply) = reply {data["replyTo"] = reply;}- let e = hub- .add_entry(&lane, EntryKind::User, turn, &data)- .ok_or_else(|| anyhow!("couldn't save the message"))?;- // Before the turn starts, so its reply lands unread.- if let Err(error) = hub.mark_read(bot) {- tracing::warn!(%error, bot, "couldn't mark bot read after send");+ // Said on a voice call (on-device or speech to text): the apps show it in the call's conversation.+ if let Some(call) = b["call"].as_str() {+ data["call"] = crate::chat::calls::checked(call)?.into();}- if row.config.is_group() {- // Each member reads it in its room prompt (`chat::group`).- crate::chat::group::start(hub, &row.config, lane);- } else {- // `/skill …` reaches the agent as "read this skill first"; the chat keeps what was typed.- let prompt = crate::chat::prompt::of_entry(hub, &row.config, &e.data);- hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: prompt })?;- }- json!({"entry": e})+ json!({"entry": crate::chat::messages::post(hub, &row.config, data)?})}// A voice call is on (its audio flows): the lead speaks first."callStarted" => {crate::chat::lead::call_started(hub, str_arg(&b, "botId")?)?;json!({})}- // A finished voice call, as a line in the chat ("Voice chat · 0:16").+ // A finished voice call from an app older than `endCall`, as a line in the chat ("Voice chat · 0:16")."logCall" => {let bot = str_arg(&b, "botId")?;hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;let seconds = b["seconds"].as_u64().unwrap_or(0);- let data = json!({"text": "Voice chat", "callSeconds": seconds});+ let data = json!({"text": crate::chat::calls::UNTITLED, "callSeconds": seconds});let e = hub.add_entry(&Lane::main(bot), EntryKind::Notice, hub.store.max_turn(bot), &data);json!({"entry": e})}+ // A voice call, owned by the host (`chat::calls`).+ "startCall" => crate::chat::calls::start(hub, &b).await?,+ // `lines`: what was said on the call that the app hadn't sent yet, which the tool may hand on.+ "callTool" => {+ let call = crate::chat::calls::checked(str_arg(&b, "callId")?)?;+ let result = crate::chat::calls::tools::call(hub, call, str_arg(&b, "name")?, &b["arguments"], &b["lines"]);+ json!({"result": result.await})+ }+ "callLines" => {+ crate::chat::calls::add_lines(+ &hub.store,+ crate::chat::calls::checked(str_arg(&b, "callId")?)?,+ &b["lines"],+ )?;+ json!({})+ }+ "endCall" => {+ let call = crate::chat::calls::checked(str_arg(&b, "callId")?)?;+ let seconds = b["seconds"].as_u64().unwrap_or(0);+ json!({"entry": crate::chat::calls::end(hub, str_arg(&b, "botId")?, call, seconds, &b["lines"])?})+ }"stop" => {let bot = str_arg(&b, "botId")?;match hub.store.bot(bot)? {diff --git a/host/src/chat/calls/context.rs b/host/src/chat/calls/context.rsnew file mode 100644index 00000000..1caa9cd2--- /dev/null+++ b/host/src/chat/calls/context.rs@@ -0,0 +1,492 @@+//! What the voice of a call hears before it speaks: its rules, then the background as named sections, each capped,+//! empty ones left out, each saying where it came from. It goes to the voice provider, on the user's own key.++use super::tools::{runtime, waiting};+use crate::hub::{BotStatus, Hub};+use crate::store::{BotConfig, Entry, EntryKind, Lane};+use crate::voice::Provider;+use codync_mem::files::{self as mf, MAIN};+use std::path::Path;+use std::sync::Arc;++/// Each section's cap (characters) and the whole background's: about 16k on Gemini. `OpenAI` Realtime keeps a+/// smaller context, so it gets [`OPENAI_TENTHS`] tenths of each.+const CAPS: Caps = Caps {+ now: 300,+ user: 3_000,+ bot: 2_000,+ remembers: 3_000,+ project: 1_000,+ work: 1_500,+ conversation: 3_500,+ others: 1_000,+ shared: 700,+};+/// Of each cap, in tenths.+const OPENAI_TENTHS: usize = 6;+/// The chat messages the voice reads, and how much of each.+const MESSAGES: i64 = 20;+const MESSAGE_CHARS: usize = 600;+/// Entries looked through for the bot's current work, past calls and shared files.+pub(super) const RECENT: i64 = 300;++struct Caps {+ now: usize,+ user: usize,+ bot: usize,+ remembers: usize,+ project: usize,+ work: usize,+ conversation: usize,+ others: usize,+ shared: usize,+}++/// The voice's role first: a relay between the user and the bot (or group), never the bot itself.+fn rules(hub: &Hub, cfg: &BotConfig) -> String {+ let name = if cfg.name.trim().is_empty() { "the bot" } else { cfg.name.trim() };+ let who = if cfg.is_group() {+ let members: Vec<String> = cfg.members.iter().map(|id| hub.bot_name(id)).collect();+ format!(+ "{name}, a group chat of coding agents on the user's computer ({}), who answer in turn",+ members.join(", ")+ )+ } else {+ format!("{name}, a coding agent on the user's computer")+ };+ format!(+ "You are the voice relay for {name}: the switchboard operator on a phone call between the user and {who}. You \+are not {name}. {name} does all the actual work.+- Your job: pass the user's requests to {name} with send_to_bot, tell the user what {name} says, and ask the user \+for anything missing. Small talk, clarifying questions and reading results aloud are yours.+- When asked who you are, say you're the voice line to {name}. Speak of {name} in the third person (\"I'll ask {name}\", \+\"{name} says …\"); never claim you did, checked or saw something yourself.+- Anything about the user's code, files, computer or project goes to {name} with send_to_bot, even if you think you \+know the answer, in the user's own words (keep names and code terms exactly). The host attaches what the user said \+word for word. Never do the work or invent results.+- bot_status and recent_messages answer \"what is {name} doing?\" or \"what did it say?\"; search_memory finds what \+{name} remembers; stop_bot stops {name} when the user asks.+- 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).+- Speak the user's language. Keep spoken answers short and natural.+- The background below is for context: use it, don't read it out."+ )+}++/// The voice's instructions for a call with `cfg`'s bot.+pub async fn instructions(+ hub: &Arc<Hub>,+ cfg: &BotConfig,+ provider: Option<Provider>,+ language: Option<&str>,+) -> String {+ let tenths = if provider == Some(Provider::OpenAi) { OPENAI_TENTHS } else { 10 };+ let cap = |n: usize| n * tenths / 10;+ let project = super::project::now(&cfg.cwd).await;+ let (h, c, l) = (hub.clone(), cfg.clone(), language.map(str::to_owned));+ let sections = tokio::task::spawn_blocking(move || background(&h, &c, l.as_deref())).await.unwrap_or_default();+ let mut out = vec![rules(hub, cfg)];+ let caps = &CAPS;+ let named = [+ ("Now", "this computer's clock and the user's phone", sections.now, caps.now),+ ("About the user", "the memory the user's bots share", sections.user, caps.user),+ ("This bot", "its settings in Codync", sections.bot, caps.bot),+ ("What the bot remembers", "its own memory", sections.remembers, caps.remembers),+ ("The project now", "git, in the bot's folder", project, caps.project),+ ("Current work", "the bot's status and its chat", sections.work, caps.work),+ ("The conversation", "the bot's chat and earlier calls", sections.conversation, caps.conversation),+ ("Other bots on this computer", "Codync", sections.others, caps.others),+ ("Shared in this chat", "files and artifacts in the bot's chat", sections.shared, caps.shared),+ ];+ for (title, from, body, n) in named {+ let body = body.trim();+ if !body.is_empty() {+ out.push(format!("## {title} (from {from})\n{}", crate::agent::acp::truncate(body, cap(n))));+ }+ }+ out.join("\n\n")+}++#[derive(Default)]+struct Sections {+ now: String,+ user: String,+ bot: String,+ remembers: String,+ work: String,+ conversation: String,+ others: String,+ shared: String,+}++fn background(hub: &Hub, cfg: &BotConfig, language: Option<&str>) -> Sections {+ let recent = hub.store.history(&cfg.id, i64::MAX, RECENT).unwrap_or_default();+ Sections {+ now: now(language),+ user: user(hub, cfg),+ bot: bot(hub, cfg),+ remembers: remembers(hub, cfg),+ work: work(hub, cfg, &recent),+ conversation: conversation(hub, cfg, &recent),+ others: others(hub, cfg),+ shared: shared(&recent),+ }+}++fn now(language: Option<&str>) -> String {+ let now = chrono::Local::now();+ let mut lines = vec![format!("{} (UTC{})", now.format("%A %Y-%m-%d %H:%M"), now.format("%:z"))];+ if let Some(language) = language.filter(|l| !l.trim().is_empty()) {+ lines.push(format!("The user's language: {}", crate::agent::acp::truncate(language.trim(), 40)));+ }+ lines.join("\n")+}++/// A layer's `MEMORY.md` and its notes' names and descriptions (a description the checks refuse stays out).+fn layer(hub: &Hub, bot: Option<&str>, owner: &str, shared: bool) -> String {+ let main = hub.store.memory_read(|c| mf::current(c, bot, MAIN)).ok().flatten().unwrap_or_default();+ let index = hub.store.memory_read(|c| mf::index(c, owner, shared)).ok();+ let notes = index.map(|i| if bot.is_some() { i.bot } else { i.yours.unwrap_or_default() }).unwrap_or_default();+ let mut out = main.trim().to_owned();+ let listed: Vec<String> = notes+ .iter()+ .map(|f| {+ let about = f.description.as_deref().filter(|d| codync_mem::check::content(d).is_ok()).unwrap_or("");+ if about.is_empty() { format!("- {}", f.name) } else { format!("- {}: {about}", f.name) }+ })+ .collect();+ if !listed.is_empty() {+ out = format!("{out}\nNotes (ask the bot to read one):\n{}", listed.join("\n"));+ }+ out+}++fn user(hub: &Hub, cfg: &BotConfig) -> String {+ if cfg.is_group() || !crate::chat::memory::shared(cfg) {+ return String::new();+ }+ layer(hub, None, &cfg.id, true)+}++fn remembers(hub: &Hub, cfg: &BotConfig) -> String {+ if cfg.is_group() {+ return String::new();+ }+ layer(hub, Some(&cfg.id), &cfg.id, false)+}++fn bot(hub: &Hub, cfg: &BotConfig) -> String {+ let mut lines = vec![format!("Name: {}", cfg.name)];+ if !cfg.description.trim().is_empty() {+ lines.push(format!("Description: {}", cfg.description.trim()));+ }+ if cfg.is_group() {+ lines.push("A group chat; its members answer in turn:".into());+ for id in &cfg.members {+ if let Ok(Some(m)) = hub.store.bot(id) {+ lines.push(format!("- {}: {}", m.config.name, m.config.description.trim()));+ }+ }+ return lines.join("\n");+ }+ let model = cfg.model.as_deref().map(|m| format!(", model {m}")).unwrap_or_default();+ lines.push(format!("Runs on: {}{model}", crate::agent::fallback::name(&cfg.backend)));+ let project = Path::new(&cfg.cwd).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();+ lines.push(format!("Folder: {} (project {project})", cfg.cwd));+ lines.push(format!(+ "Permission mode: {}",+ serde_json::to_value(cfg.permission).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default()+ ));+ if !cfg.connectors.is_empty() {+ lines.push(format!("Connectors: {}", cfg.connectors.join(", ")));+ }+ if !cfg.skills.is_empty() {+ lines.push(format!("Skills: {}", cfg.skills.join(", ")));+ }+ lines.push(format!("Computer use: {}", if cfg.computer { "on" } else { "off" }));+ let routines = hub.routines.list(&cfg.id);+ for r in routines["routines"].as_array().into_iter().flatten() {+ let when: Vec<&str> =+ r["triggerDescriptions"].as_array().into_iter().flatten().filter_map(|t| t.as_str()).collect();+ let off = if r["enabled"] == true { "" } else { " (off)" };+ lines.push(format!("Routine: {} — {}{off}", r["name"].as_str().unwrap_or_default(), when.join("; ")));+ }+ lines.join("\n")+}++fn work(hub: &Hub, cfg: &BotConfig, recent: &[Entry]) -> String {+ let rt = runtime(hub, cfg);+ let status = match rt.status {+ BotStatus::Idle => "idle",+ BotStatus::Working => "working",+ BotStatus::NeedsInput => "waiting for the user",+ BotStatus::Error => "stopped on an error",+ };+ let mut lines = vec![format!("Status: {status}")];+ if !rt.activity.trim().is_empty() {+ lines.push(format!("Doing: {}", rt.activity.trim()));+ }+ if let Some(w) = waiting(recent) {+ lines.push(format!("Waiting for approval: {} (options: {})", w.request, w.options.join(", ")));+ }+ let queued = recent.iter().filter(|e| e.kind == EntryKind::User.as_str() && e.data["status"] == "queued").count();+ if queued > 0 {+ lines.push(format!("Messages waiting for it: {queued}"));+ }+ if let Some(failure) =+ recent.iter().rev().find(|e| e.kind == EntryKind::Notice.as_str() && e.data["style"] == "error")+ {+ lines.push(format!("Last failure: {}", spoken(failure.data["text"].as_str().unwrap_or_default(), 300)));+ }+ lines.join("\n")+}++/// The chat's last `count` messages as the voice reads them: who wrote each, and its text shortened for speech.+pub(super) fn said(hub: &Hub, cfg: &BotConfig, count: i64, chars: usize) -> Vec<(String, String)> {+ let messages = hub.store.messages_after(&Lane::main(&cfg.id), 0, count).unwrap_or_default();+ messages+ .iter()+ .map(|e| {+ let who = super::writer(e)+ .map_or_else(|| hub.bot_name(e.data["author"].as_str().unwrap_or(&cfg.id)), str::to_owned);+ (who, spoken(e.data["text"].as_str().unwrap_or_default(), chars))+ })+ .collect()+}++fn conversation(hub: &Hub, cfg: &BotConfig, recent: &[Entry]) -> String {+ let mut lines: Vec<String> =+ said(hub, cfg, MESSAGES, MESSAGE_CHARS).into_iter().map(|(who, text)| format!("{who}: {text}")).collect();+ let calls: Vec<String> = recent+ .iter()+ .rev()+ .filter(|e| e.kind == EntryKind::Notice.as_str() && e.data["callSeconds"].is_number())+ .take(3)+ .map(|e| {+ let gist = e.data["transcript"].as_array().into_iter().flatten().find(|l| l["from"] == "user");+ let gist =+ gist.and_then(|l| l["text"].as_str()).map(|t| format!(": \"{}\"", spoken(t, 120))).unwrap_or_default();+ format!(+ "- {} ({}){gist}",+ e.data["text"].as_str().unwrap_or(super::UNTITLED),+ crate::chat::memory::ymd(e.created_at)+ )+ })+ .collect();+ if !calls.is_empty() {+ lines.push(format!("Earlier calls with this bot:\n{}", calls.join("\n")));+ }+ lines.join("\n")+}++fn others(hub: &Hub, cfg: &BotConfig) -> String {+ let rows = hub.store.bots().unwrap_or_default();+ rows.iter()+ .filter(|r| !r.deleted && r.config.id != cfg.id)+ .map(|r| {+ let about = r.config.description.trim();+ if about.is_empty() { format!("- {}", r.config.name) } else { format!("- {}: {about}", r.config.name) }+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn shared(recent: &[Entry]) -> String {+ let mut titles: Vec<String> = Vec::new();+ for e in recent.iter().rev() {+ if let Some(title) = e.data["artifact"]["title"].as_str() {+ titles.push(format!("- {title} (artifact)"));+ }+ for f in e.data["files"]+ .as_array()+ .into_iter()+ .flatten()+ .chain(e.data["attachments"].as_array().into_iter().flatten())+ {+ if let Some(name) = f["name"].as_str() {+ titles.push(format!("- {name}"));+ }+ }+ if titles.len() >= 10 {+ break;+ }+ }+ titles.join("\n")+}++/// Text as speech can carry it: code blocks and links named, not read, markdown marks dropped, capped.+pub fn spoken(text: &str, max: usize) -> String {+ let mut out = String::new();+ let mut in_code = false;+ for line in text.lines() {+ if line.trim_start().starts_with("```") {+ if !in_code {+ out.push_str(" (code) ");+ }+ in_code = !in_code;+ continue;+ }+ if in_code {+ continue;+ }+ let words: Vec<String> = line+ .split_whitespace()+ .map(|w| {+ if w.starts_with("http://") || w.starts_with("https://") {+ "(link)".to_owned()+ } else {+ w.trim_matches(['*', '`', '#', '>', '_']).to_owned()+ }+ })+ .filter(|w| !w.is_empty())+ .collect();+ out.push_str(&words.join(" "));+ out.push(' ');+ }+ crate::agent::acp::truncate(out.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), max)+}++#[cfg(test)]+pub(super) mod tests {+ use super::*;+ use crate::store::{BotKind, Permission, Store};+ use codync_mem::files::{Author, Cause, Change};+ use serde_json::json;++ pub(in crate::chat::calls) fn hub() -> Arc<Hub> {+ let dir = std::env::temp_dir().join(format!("codync-call-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let store = Store::open(Path::new(":memory:")).unwrap();+ let identity = crate::remote::identity::Identity::load_or_create(&dir).unwrap();+ Hub::new(store, "h".into(), identity, "t".into(), 0)+ }++ pub(in crate::chat::calls) fn bot(id: &str, name: &str, cwd: &str) -> BotConfig {+ BotConfig {+ id: id.into(),+ kind: BotKind::Agent,+ members: vec![],+ name: name.into(),+ description: "Keeps the shop's site running".into(),+ avatar_color: "blue".into(),+ avatar_shape: "blob".into(),+ backend: "claude".into(),+ command: None,+ cwd: cwd.into(),+ permission: Permission::Ask,+ model: Some("opus".into()),+ model_options: std::collections::BTreeMap::new(),+ fast_mode: false,+ fallbacks: vec![],+ self_fallbacks: true,+ pinned: false,+ position: 0,+ hidden: false,+ notify: None,+ connectors: vec!["github".into()],+ skills: vec![],+ computer: false,+ manage_team: false,+ created_by: None,+ shared_memory: Some(true),+ harness_memory: false,+ auto_name: false,+ lead: false,+ created_at: 0,+ }+ }++ /// `MEMORY.md` straight into the store, as a scan would record it.+ fn remember(hub: &Hub, layer: Option<&str>, content: &str) {+ let change = Change {+ bot: layer,+ name: MAIN,+ content: Some(content),+ author: Author::User,+ author_bot: None,+ cause: Cause::Edit,+ message: None,+ mtime: 0,+ size: content.len() as u64,+ };+ hub.store.memory_write(|c, now, rev| mf::record(c, &change, now, rev)).unwrap();+ }++ /// git in `dir` alone: a pre-commit hook running these tests sets `GIT_DIR` and `GIT_INDEX_FILE` for the commit.+ fn git(dir: &Path, args: &[&str]) -> bool {+ let mut cmd = std::process::Command::new("git");+ for (key, _) in std::env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("GIT_")) {+ cmd.env_remove(key);+ }+ cmd.args(args).current_dir(dir).output().is_ok_and(|o| o.status.success())+ }++ #[tokio::test]+ async fn the_voice_hears_its_role_then_the_background_within_caps() {+ let hub = hub();+ let repo = std::env::temp_dir().join(format!("codync-call-repo-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&repo).unwrap();+ std::fs::write(repo.join("cart.ts"), "x").unwrap();+ let repo_ok = git(&repo, &["init", "-q", "-b", "main"])+ && git(&repo, &["add", "cart.ts"])+ && git(&repo, &["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "Add the cart"]);+ // Unstaged, so its porcelain line starts with a space.+ std::fs::write(repo.join("cart.ts"), "y").unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ let cfg = bot(&id, "Mika", &repo.to_string_lossy());+ hub.store.save_bot(&cfg).unwrap();+ hub.store.save_bot(&bot(&uuid::Uuid::new_v4().to_string(), "Owen", "/tmp")).unwrap();+ remember(&hub, Some(&id), "- The shop deploys from main\n");+ remember(&hub, None, "- Lives in Taipei\n");+ let chat = Lane::main(&id);+ for turn in 0..30 {+ let long = format!("message {turn} {}", "x".repeat(2_000));+ hub.store.insert_entry(&chat, EntryKind::User, turn, &json!({"text": long})).unwrap();+ hub.store+ .insert_entry(&chat, EntryKind::Agent, turn, &json!({"text": "Done.", "final": true, "author": id}))+ .unwrap();+ }++ let gemini = instructions(&hub, &cfg, Some(Provider::Gemini), Some("zh-TW")).await;+ assert!(gemini.starts_with("You are the voice relay for Mika"), "the role comes first: {}", &gemini[..80]);+ assert!(gemini.contains("You are not Mika") && gemini.contains("send_to_bot"));+ for heading in [+ "## Now",+ "## About the user",+ "## This bot",+ "## What the bot remembers",+ "## The conversation",+ "## Other bots",+ ] {+ assert!(gemini.contains(heading), "{heading} is there");+ }+ for fact in ["Lives in Taipei", "The shop deploys from main", "zh-TW", "github", "Owen"] {+ assert!(gemini.contains(fact), "{fact} reaches the voice");+ }+ if repo_ok {+ assert!(+ gemini.contains("## The project now")+ && gemini.contains("Branch: main")+ && gemini.contains("Changed files (1): cart.ts")+ );+ assert!(gemini.contains("Add the cart"));+ }+ assert!(!gemini.contains("## Shared in this chat"), "empty sections stay out");+ let conversation = gemini.split("## The conversation").nth(1).unwrap().split("\n## ").next().unwrap();+ assert!(conversation.chars().count() <= CAPS.conversation + 80, "the conversation keeps to its cap");+ let background = gemini.chars().count() - rules(&hub, &cfg).chars().count();+ assert!(background <= 16_000 + 1_000, "the background keeps to about 16k: {background}");+ let openai = instructions(&hub, &cfg, Some(Provider::OpenAi), None).await;+ assert!(openai.chars().count() < gemini.chars().count(), "OpenAI's smaller context gets less");+ }++ #[test]+ fn speech_names_code_and_links() {+ assert_eq!(+ spoken("**Done.** See https://x.dev\n```\nlet a = 1;\n```\n- `cargo test` passed", 200),+ "Done. See (link) (code) - cargo test passed"+ );+ assert!(spoken(&"word ".repeat(500), 50).chars().count() <= 51);+ }+}diff --git a/host/src/chat/calls/mod.rs b/host/src/chat/calls/mod.rsnew file mode 100644index 00000000..ed73f179--- /dev/null+++ b/host/src/chat/calls/mod.rs@@ -0,0 +1,411 @@+//! Voice calls, owned by the host (`docs/plans/voice-architecture.md`, stage 1). A client starts a call+//! (`startCall`): the host hands it the provider's credential, the voice's instructions and its tools, runs the+//! voice's tool calls (`callTool`, [`tools`]), keeps the transcript as it is spoken (`callLines`, and whatever lines+//! the app still holds ride along with `callTool` and `endCall`) and writes the call's line when it ends (`endCall`).+//! What a call sends the bot carries its id (`call`), and so do the bot's replies while it lasts: the apps show those+//! only in the call's conversation, which its line opens.++pub mod context;+mod project;+pub mod tools;++use crate::LockExt;+use crate::agent::bot::Cmd;+use crate::hub::Hub;+use crate::store::{BotConfig, Entry, EntryKind, Lane, Store, now_ms};+use anyhow::{Result, anyhow, bail};+use serde::{Deserialize, Serialize};+use serde_json::{Value, json};+use std::sync::{Arc, Mutex};++const MAX_LINES: usize = 500;+const MAX_LINE_CHARS: usize = 2_000;+/// What the title writer reads of a call, from its end.+const TITLE_SOURCE_CHARS: usize = 8_000;+const MAX_TITLE_CHARS: usize = 60;+/// The call line's text until a title is written.+pub const UNTITLED: &str = "Voice chat";++/// One read-modify-write of a call's state at a time (lines and hand-offs arrive together).+static STATE: Mutex<()> = Mutex::new(());++/// Who said a line of a call: the user, or the voice answering them.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Speaker {+ User,+ Voice,+}++/// One line of what was said on a call, with when (ms, the app's clock).+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+pub struct CallLine {+ pub from: Speaker,+ pub text: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub at: Option<i64>,+}++/// A call in progress, kept in `kv` so a host restart or a dropped client loses nothing: its bot, the transcript+/// so far and how much of it the bot has heard (`handoff`).+#[derive(Serialize, Deserialize)]+struct CallState {+ bot: String,+ lines: Vec<CallLine>,+ handoff: usize,+ started: i64,+}++/// What carries a call's voice: a realtime provider, speech to text and back, or the device's own speech.+#[derive(Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "lowercase")]+enum CallMode {+ Realtime,+ Speech,+ Device,+}++/// A call id from an app: a UUID, or anything as plain.+pub fn checked(id: &str) -> Result<&str> {+ let ok = !id.is_empty() && id.len() <= 64 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-');+ if ok { Ok(id) } else { bail!("`{id}` isn't a call id") }+}++fn ended_key(call: &str) -> String {+ format!("call.ended.{call}")+}++fn state_key(call: &str) -> String {+ format!("call.{call}")+}++fn state(store: &Store, call: &str) -> Option<CallState> {+ store.kv_get(&state_key(call)).and_then(|s| serde_json::from_str(&s).ok())+}++fn save(store: &Store, call: &str, s: &CallState) -> Result<()> {+ store.kv_set(&state_key(call), &serde_json::to_string(s)?)+}++/// The call's bot, if the call is in progress.+fn bot_of(store: &Store, call: &str) -> Option<String> {+ state(store, call).map(|s| s.bot)+}++/// The call a turn answers: the one every message it answers came from, while that call lasts. A typed message+/// in the batch makes its reply visible.+pub fn of_turn(store: &Store, entry_ids: &[String]) -> Option<String> {+ let mut calls = entry_ids.iter().map(|id| store.entry(id).and_then(|e| e.data["call"].as_str().map(str::to_owned)));+ let first = calls.next()??;+ (calls.all(|c| c.as_deref() == Some(first.as_str())) && store.kv_get(&ended_key(&first)).is_none()).then_some(first)+}++/// Who wrote a chat message, as the voice and the title writer name them; `None` for a bot.+fn writer(e: &Entry) -> Option<&'static str> {+ match (e.kind.as_str(), e.data["from"].as_str()) {+ ("user", Some("voice")) => Some("Voice (relayed)"),+ ("user", _) => Some("User"),+ _ => None,+ }+}++/// Lines of what was said, from an app: `from` `user` (what the user said) or `voice`, with `at` (ms).+fn transcript(raw: &Value) -> Vec<CallLine> {+ raw.as_array()+ .into_iter()+ .flatten()+ .filter_map(|line| {+ let line = CallLine::deserialize(line).ok()?;+ let text = line.text.trim();+ (!text.is_empty()).then(|| CallLine {+ from: line.from,+ text: crate::agent::acp::truncate(text, MAX_LINE_CHARS),+ at: line.at,+ })+ })+ .take(MAX_LINES)+ .collect()+}++/// Adds what was just said to the call, keeping its last [`MAX_LINES`].+fn append(s: &mut CallState, lines: Vec<CallLine>) {+ s.lines.extend(lines);+ let over = s.lines.len().saturating_sub(MAX_LINES);+ s.lines.drain(..over);+ // What the bot heard moves with the lines dropped from the front.+ s.handoff = s.handoff.saturating_sub(over);+}++/// `startCall`: the call is on (again, for a session the provider replaced: its transcript stays). Hands back what+/// the client needs: the voice's instructions and tools, and a realtime provider's credential.+pub async fn start(hub: &Arc<Hub>, b: &Value) -> Result<Value> {+ let bot = b["botId"].as_str().ok_or_else(|| anyhow!("`botId` is required"))?;+ let call = checked(b["callId"].as_str().unwrap_or_default())?;+ let mode = if b["mode"].is_null() { CallMode::Realtime } else { CallMode::deserialize(&b["mode"])? };+ let cfg = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?.config;+ {+ let _one = STATE.locked();+ if hub.store.kv_get(&ended_key(call)).is_some() {+ bail!("that call has ended");+ }+ match state(&hub.store, call) {+ Some(s) if s.bot != bot => bail!("that call belongs to another bot"),+ Some(_) => {}+ None => {+ let s = CallState { bot: bot.to_owned(), lines: Vec::new(), handoff: 0, started: now_ms() };+ save(&hub.store, call, &s)?;+ }+ }+ }+ let provider = b["provider"].as_str().map(crate::voice::Provider::parse).transpose()?;+ let mut out = json!({+ "instructions": context::instructions(hub, &cfg, provider, b["language"].as_str()).await,+ "tools": tools::declarations(),+ });+ if let (Some(p), CallMode::Realtime) = (provider, mode) {+ // The provider's key is in the vault.+ crate::market::vault::unlock(hub.clone()).await?;+ let (model, voice) = (b["model"].as_str().unwrap_or_default(), b["voice"].as_str().unwrap_or_default());+ out["credential"] = crate::voice::session(&hub.store, p, model, voice).await?["credential"].clone();+ }+ Ok(out)+}++/// `callLines`: what was just said on the call (`raw`, see [`transcript`]).+pub fn add_lines(store: &Store, call: &str, raw: &Value) -> Result<()> {+ let lines = transcript(raw);+ if lines.is_empty() {+ return Ok(());+ }+ let _one = STATE.locked();+ let mut s = state(store, call).ok_or_else(|| anyhow!("no such call"))?;+ append(&mut s, lines);+ save(store, call, &s)+}++/// What the user said since the bot last heard from the call, word for word; the bot hears it now.+fn take_said(store: &Store, call: &str) -> Result<String> {+ let _one = STATE.locked();+ let mut s = state(store, call).ok_or_else(|| anyhow!("no such call"))?;+ let unheard = s.lines.get(s.handoff..).unwrap_or_default();+ let said =+ unheard.iter().filter(|l| l.from == Speaker::User).map(|l| l.text.as_str()).collect::<Vec<_>>().join(" ");+ s.handoff = s.lines.len();+ save(store, call, &s)?;+ Ok(said)+}++/// `endCall`: the rest of the transcript (`raw`), the call's line in the chat, then a title written for it. A call+/// ends once: an app trying again changes nothing.+pub fn end(hub: &Arc<Hub>, bot: &str, call: &str, seconds: u64, raw: &Value) -> Result<Option<Entry>> {+ let s = {+ let _one = STATE.locked();+ if hub.store.kv_get(&ended_key(call)).is_some() {+ return Ok(None);+ }+ let mut s = state(&hub.store, call);+ if let Some(s) = s.as_mut() {+ append(s, transcript(raw));+ }+ hub.store.kv_set(&ended_key(call), "1")?;+ hub.store.kv_delete(&state_key(call))?;+ s+ };+ let bot = s.as_ref().map_or(bot, |s| s.bot.as_str()).to_owned();+ let cfg = hub.store.bot(&bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?.config;+ let mut data = json!({"text": UNTITLED, "callSeconds": seconds, "call": call});+ if let Some(s) = s.filter(|s| !s.lines.is_empty()) {+ data["transcript"] = serde_json::to_value(&s.lines)?;+ }+ let entry = hub.add_entry(&Lane::main(&bot), EntryKind::Notice, hub.store.max_turn(&bot), &data);+ // Replies from here on show in the chat again, and dreaming reads the call (its line is in the store by now)+ // soon. A group's members answer it.+ let actors = if cfg.is_group() { cfg.members.clone() } else { vec![cfg.id.clone()] };+ for actor in actors {+ if let Err(e) = hub.send_cmd(&actor, Cmd::CallEnded { call: call.to_owned() }) {+ tracing::debug!(bot = actor, error = format!("{e:#}"), "no bot actor to tell the call ended");+ }+ }+ let Some(entry) = entry else { return Ok(None) };+ let (hub, line) = (hub.clone(), entry.clone());+ tokio::spawn(async move {+ if let Err(e) = title(&hub, &cfg, &line).await {+ tracing::info!(bot = %cfg.id, error = format!("{e:#}"), "couldn't title the call");+ }+ });+ Ok(Some(entry))+}++/// The call as a conversation, oldest first: the voice's transcript and the messages the call carried.+fn conversation(store: &Store, bot: &str, line: &Entry) -> Vec<(String, String)> {+ let Some(call) = line.data["call"].as_str() else { return Vec::new() };+ let mut said: Vec<(i64, String, String)> = transcript(&line.data["transcript"])+ .into_iter()+ .map(|l| {+ let who = match l.from {+ Speaker::User => "User",+ Speaker::Voice => "Voice",+ };+ (l.at.unwrap_or(line.created_at), who.to_owned(), l.text)+ })+ .collect();+ for e in store.call_entries(bot, call).unwrap_or_default() {+ let who = writer(&e).unwrap_or("Bot");+ said.push((e.created_at, who.to_owned(), e.data["text"].as_str().unwrap_or_default().to_owned()));+ }+ // ponytail: phone and computer clocks merged as they are; a skewed phone clock reorders a line or two.+ said.sort_by_key(|(at, ..)| *at);+ said.into_iter().map(|(_, who, text)| (who, text)).collect()+}++async fn title(hub: &Arc<Hub>, cfg: &BotConfig, line: &Entry) -> Result<()> {+ let said = conversation(&hub.store, &cfg.id, line);+ if !said.iter().any(|(who, _)| who == "User") {+ return Ok(());+ }+ // The call's end, whole lines, within the budget.+ let mut lines: Vec<String> = said+ .iter()+ .rev()+ .map(|(who, text)| format!("{who}: {}", text.trim()))+ .scan(0, |len, line| {+ *len += line.len() + 1;+ (*len <= TITLE_SOURCE_CHARS).then_some(line)+ })+ .collect();+ lines.reverse();+ let body = lines.join("\n");+ let raw =+ crate::chat::oneshot::one_shot(hub, cfg, TITLE_PROMPT, &format!("The call, oldest first:\n\n{body}")).await?;+ let Some(name) = parse_title(&raw) else { return Ok(()) };+ let Some(mut e) = hub.store.entry(&line.id) else { return Ok(()) };+ e.data["text"] = name.into();+ hub.set_entry(&line.id, &e.data);+ Ok(())+}++const TITLE_PROMPT: &str = "\+You title a voice call between the user and their assistant, for the call's line in the chat.+Output exactly one line:+title: <what the call was about, 2-6 words>+Write it in the language and script the user speaks (Traditional and Simplified Chinese are different). No quotes, no emoji, no trailing punctuation.+Output exactly NONE if the call has nothing to sum up (only greetings or tests).";++fn parse_title(raw: &str) -> Option<String> {+ let title = raw.lines().find_map(|line| {+ let (tag, rest) = line.trim().trim_start_matches(['-', '*', ' ']).split_once(':')?;+ tag.trim().eq_ignore_ascii_case("title").then(|| rest.trim().trim_matches(['"', '“', '”', '「', '」']))+ })?;+ let title = title.trim_end_matches(['.', '。']).trim();+ (!title.is_empty() && !title.eq_ignore_ascii_case("none") && title.chars().count() <= MAX_TITLE_CHARS)+ .then(|| title.to_owned())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn call_ids_are_plain() {+ assert!(checked("6f1c2e0a-1b2c-4d5e-8f90-123456789abc").is_ok());+ assert!(checked("").is_err());+ assert!(checked("a/b").is_err());+ assert!(checked(&"a".repeat(65)).is_err());+ }++ #[test]+ fn transcripts_keep_only_lines_of_the_user_or_the_voice() {+ let raw = json!([+ {"from": "user", "text": " 幫我看 git status ", "at": 5},+ {"from": "voice", "text": "Checking."},+ {"from": "bot", "text": "spoofed"},+ {"from": "user", "text": " "},+ {"text": "no speaker"},+ ]);+ let lines = serde_json::to_value(transcript(&raw)).unwrap();+ assert_eq!(+ lines,+ json!([{"from": "user", "text": "幫我看 git status", "at": 5}, {"from": "voice", "text": "Checking."}])+ );+ let long: Vec<Value> = (0..MAX_LINES + 5).map(|_| json!({"from": "user", "text": "x"})).collect();+ assert_eq!(transcript(&Value::Array(long)).len(), MAX_LINES);+ }++ #[test]+ fn titles_are_parsed() {+ assert_eq!(parse_title("title: 「規劃 2.26 發佈」").as_deref(), Some("規劃 2.26 發佈"));+ assert_eq!(parse_title("Sure.\n- Title: Fix the login bug.").as_deref(), Some("Fix the login bug"));+ assert_eq!(parse_title("NONE"), None);+ assert_eq!(parse_title(&format!("title: {}", "x".repeat(61))), None);+ }++ #[test]+ fn a_call_reads_as_one_conversation_in_order() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ let chat = Lane::main("b");+ store+ .insert_entry(&chat, EntryKind::User, 1, &json!({"text": "check git", "call": "c", "from": "voice"}))+ .unwrap();+ store.insert_entry(&chat, EntryKind::Agent, 1, &json!({"text": "Clean.", "final": true, "call": "c"})).unwrap();+ store.insert_entry(&chat, EntryKind::Agent, 1, &json!({"text": "narration", "call": "c"})).unwrap();+ store.insert_entry(&chat, EntryKind::User, 2, &json!({"text": "typed, not the call's"})).unwrap();+ let data = json!({"text": UNTITLED, "call": "c", "transcript": [+ {"from": "user", "text": "看一下 git", "at": 0},+ {"from": "voice", "text": "It's clean.", "at": i64::MAX},+ ]});+ let line = store.insert_entry(&chat, EntryKind::Notice, 2, &data).unwrap();+ let said: Vec<String> =+ conversation(&store, "b", &line).into_iter().map(|(who, text)| format!("{who}: {text}")).collect();+ assert_eq!(said, ["User: 看一下 git", "Voice (relayed): check git", "Bot: Clean.", "Voice: It's clean."]);+ }++ #[tokio::test]+ async fn a_call_keeps_what_was_said_and_hands_the_users_words_to_the_bot() {+ let hub = context::tests::hub();+ let id = uuid::Uuid::new_v4().to_string();+ // No agent to run: the title writer gives up at once.+ let cfg = BotConfig { backend: "none".into(), ..context::tests::bot(&id, "Mika", "/tmp") };+ hub.store.save_bot(&cfg).unwrap();+ let started = start(&hub, &json!({"botId": id, "callId": "c1", "mode": "device"})).await.unwrap();+ assert!(started["instructions"].as_str().unwrap().contains("voice relay for Mika"));+ assert!(started["tools"].as_array().unwrap().iter().any(|t| t["name"] == "search_memory"));+ assert!(started.get("credential").is_none(), "an on-device call has no provider");+ add_lines(&hub.store, "c1", &json!([{"from": "user", "text": "首頁", "at": 1}])).unwrap();++ // The rest of what the user said comes with the tool call that hands it on.+ let unsent = json!([{"from": "user", "text": "改成藍色", "at": 2}, {"from": "voice", "text": "好"}]);+ let sent = tools::call(&hub, "c1", "send_to_bot", &json!({"text": "Make the home page blue"}), &unsent).await;+ // No bot actor runs in this test, so delivery fails; the message is in the chat all the same.+ assert!(sent["error"].is_string() || sent["sent"] == true);+ let relayed = hub.store.call_entries(&id, "c1").unwrap();+ assert_eq!(relayed.len(), 1);+ assert_eq!(relayed[0].data["from"], "voice");+ let text = relayed[0].data["text"].as_str().unwrap();+ assert!(text.starts_with("Make the home page blue") && text.contains("«首頁 改成藍色»"), "{text}");+ assert_eq!(take_said(&hub.store, "c1").unwrap(), "", "the bot already heard it");++ let last = json!([{"from": "voice", "text": "Done."}]);+ let line = end(&hub, &id, "c1", 30, &last).unwrap().unwrap();+ assert_eq!((line.data["callSeconds"].as_u64(), line.data["call"].as_str()), (Some(30), Some("c1")));+ assert_eq!(line.data["transcript"].as_array().map(Vec::len), Some(4), "with the lines the app still held");+ assert!(end(&hub, &id, "c1", 31, &last).unwrap().is_none(), "an app trying again ends it once");+ assert!(bot_of(&hub.store, "c1").is_none(), "an ended call takes no more lines");+ assert!(start(&hub, &json!({"botId": id, "callId": "c1", "mode": "device"})).await.is_err());+ assert!(of_turn(&hub.store, &[relayed[0].id.clone()]).is_none(), "its replies show again");+ assert!(tools::call(&hub, "c1", "bot_status", &json!({}), &Value::Null).await["error"].is_string());+ }++ #[test]+ fn a_turn_answers_a_call_only_when_all_its_messages_came_from_it() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ let chat = Lane::main("b");+ let id = |data: Value| store.insert_entry(&chat, EntryKind::User, 1, &data).unwrap().id;+ let a = id(json!({"text": "one", "call": "c1"}));+ let b = id(json!({"text": "two", "call": "c1"}));+ let typed = id(json!({"text": "typed"}));+ assert_eq!(of_turn(&store, &[a.clone(), b.clone()]).as_deref(), Some("c1"));+ assert_eq!(of_turn(&store, &[a.clone(), typed]), None);+ store.kv_set(&ended_key("c1"), "1").unwrap();+ assert_eq!(of_turn(&store, &[a, b]), None);+ }+}diff --git a/host/src/chat/calls/project.rs b/host/src/chat/calls/project.rsnew file mode 100644index 00000000..70bb4ff3--- /dev/null+++ b/host/src/chat/calls/project.rs@@ -0,0 +1,70 @@+//! The project a call's bot works in, from git: what the voice knows of it before it speaks.++use std::path::{Path, PathBuf};+use std::time::Duration;++const GIT_TIMEOUT: Duration = Duration::from_secs(2);++/// The project in `cwd` now: branch, changed files and the last commits; nothing outside a repository.+pub async fn now(cwd: &str) -> String {+ let dir = Path::new(cwd);+ if cwd.is_empty() || !dir.ancestors().any(|d| d.join(".git").exists()) {+ return String::new();+ }+ let Some(git) = git_program().await else { return String::new() };+ let run = |args: &'static [&'static str]| {+ let (git, dir) = (git.clone(), dir.to_owned());+ async move {+ let mut cmd = tokio::process::Command::new(git);+ // The bot's folder only: a `GIT_DIR`, `GIT_INDEX_FILE`… this process inherited (from a git hook, say)+ // would point git at another repository.+ for (key, _) in std::env::vars_os().filter(|(k, _)| k.to_string_lossy().starts_with("GIT_")) {+ cmd.env_remove(key);+ }+ // No optional locks: a status killed at the timeout can't leave `.git/index.lock` behind.+ cmd.args(args)+ .current_dir(dir)+ .env("GIT_OPTIONAL_LOCKS", "0")+ .stdin(std::process::Stdio::null())+ .kill_on_drop(true);+ let out = tokio::time::timeout(GIT_TIMEOUT, cmd.output()).await.ok()?.ok()?;+ // Only the end: a porcelain line starts with its status column, a space when the change is unstaged.+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim_end().to_owned())+ }+ };+ let (branch, changes, commits) = tokio::join!(+ run(&["rev-parse", "--abbrev-ref", "HEAD"]),+ run(&["status", "--porcelain"]),+ run(&["log", "-3", "--format=%s"]),+ );+ let mut lines = Vec::new();+ if let Some(branch) = branch.filter(|b| !b.is_empty()) {+ lines.push(format!("Branch: {branch}"));+ }+ if let Some(changes) = changes {+ let files: Vec<&str> = changes.lines().map(|l| l.get(3..).unwrap_or(l)).collect();+ if files.is_empty() {+ lines.push("No uncommitted changes".into());+ } else {+ let shown = files.iter().take(10).copied().collect::<Vec<_>>().join(", ");+ let more = if files.len() > 10 { format!(" and {} more", files.len() - 10) } else { String::new() };+ lines.push(format!("Changed files ({}): {shown}{more}", files.len()));+ }+ }+ if let Some(commits) = commits.filter(|c| !c.is_empty()) {+ lines.push(format!("Last commits: {}", commits.lines().collect::<Vec<_>>().join(" · ")));+ }+ lines.join("\n")+}++/// git, where running it can't open macOS's "install the command line tools" prompt.+async fn git_program() -> Option<PathBuf> {+ let git = crate::agent::backends::which("git")?;+ if cfg!(target_os = "macos") && git == Path::new("/usr/bin/git") {+ let tools = tokio::process::Command::new("/usr/bin/xcode-select").arg("-p").output().await.ok()?;+ if !tools.status.success() {+ return None;+ }+ }+ Some(git)+}diff --git a/host/src/chat/calls/tools.rs b/host/src/chat/calls/tools.rsnew file mode 100644index 00000000..1eede41e--- /dev/null+++ b/host/src/chat/calls/tools.rs@@ -0,0 +1,224 @@+//! The voice's tools (`callTool`): what it may do for the user on the call. They run here, on the bot's chat.++use super::context::{self, RECENT};+use crate::agent::bot::Cmd;+use crate::hub::{Hub, Runtime};+use crate::store::{BotConfig, Entry, EntryKind};+use anyhow::{Result, anyhow};+use serde_json::{Value, json};+use std::sync::Arc;++/// The tools' declarations in JSON Schema form (each client spells them for its provider).+pub fn declarations() -> Value {+ json!([+ {"name": "send_to_bot", "description": "Send a message to the bot on the computer, as if the user typed it. Its reply arrives later.",+ "parameters": {"type": "object", "properties": {"text": {"type": "string", "description": "The message"}}, "required": ["text"]}},+ {"name": "bot_status", "description": "Whether the bot is idle or working, what it is doing, and any approval it is waiting for.",+ "parameters": {"type": "object", "properties": {}}},+ {"name": "recent_messages", "description": "The latest messages in the chat with the bot, oldest first.",+ "parameters": {"type": "object", "properties": {"count": {"type": "integer", "description": "How many, 1-20"}}}},+ {"name": "answer_approval", "description": "Answer the bot's pending approval request with one of its options.",+ "parameters": {"type": "object", "properties": {"option": {"type": "string", "description": "The option's name"}}, "required": ["option"]}},+ {"name": "stop_bot", "description": "Stop what the bot is doing now.",+ "parameters": {"type": "object", "properties": {}}},+ {"name": "search_memory", "description": "Search what the bot remembers about the user and their work.",+ "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Words to look for"}}, "required": ["query"]}},+ ])+}++/// Runs one of the voice's tool calls on call `call`'s bot, after adding what was said that the app still held+/// (`lines`). A failure is the tool's answer, for the voice to say.+pub async fn call(hub: &Arc<Hub>, call: &str, name: &str, args: &Value, lines: &Value) -> Value {+ let run = async {+ let bot = super::bot_of(&hub.store, call).ok_or_else(|| anyhow!("The call has ended."))?;+ super::add_lines(&hub.store, call, lines)?;+ let cfg =+ hub.store.bot(&bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("The bot isn't available."))?.config;+ match name {+ "send_to_bot" => relay(hub, &cfg, call, args["text"].as_str().unwrap_or_default()),+ "bot_status" => Ok(status(hub, &cfg)),+ "recent_messages" => Ok(recent(hub, &cfg, args["count"].as_i64().unwrap_or(6))),+ "answer_approval" => answer(hub, &cfg, args["option"].as_str().unwrap_or_default()),+ "stop_bot" => stop(hub, &cfg),+ "search_memory" if !cfg.is_group() => {+ crate::chat::memory::tool_call(hub, &cfg.id, "search_memory", args).await+ }+ _ => Err(anyhow!("Unknown tool {name}.")),+ }+ };+ run.await.unwrap_or_else(|e| json!({"error": format!("{e:#}")}))+}++/// `send_to_bot`: the voice's words to the bot, with what the user said since the bot last heard from the call,+/// word for word. The message is the call's, so the chat shows it only there.+fn relay(hub: &Arc<Hub>, cfg: &BotConfig, call: &str, text: &str) -> Result<Value> {+ let text = text.trim();+ if text.is_empty() {+ return Ok(json!({"error": "Nothing to send."}));+ }+ let said = super::take_said(&hub.store, call)?;+ let text = if said.is_empty() || said == text {+ text.to_owned()+ } else {+ format!("{text}\n\n[The user's own words on the call: «{said}»]")+ };+ let data = json!({"text": text, "attachments": [], "call": call, "from": "voice"});+ crate::chat::messages::post(hub, cfg, data)?;+ Ok(json!({"sent": true, "note": "The bot's reply will arrive as a separate message."}))+}++fn status(hub: &Hub, cfg: &BotConfig) -> Value {+ let rt = runtime(hub, cfg);+ let mut out = json!({"status": rt.status, "activity": rt.activity});+ let recent = hub.store.history(&cfg.id, i64::MAX, RECENT).unwrap_or_default();+ if let Some(w) = waiting(&recent) {+ out["approval"] = json!({"request": w.request, "options": w.options});+ }+ out+}++fn recent(hub: &Hub, cfg: &BotConfig, count: i64) -> Value {+ let said = context::said(hub, cfg, count.clamp(1, 20), 1_500);+ json!({"messages": said.into_iter().map(|(from, text)| json!({"from": from, "text": text})).collect::<Vec<_>>()})+}++/// The bot's runtime; a group's is that of the member working in it.+pub(super) fn runtime(hub: &Hub, cfg: &BotConfig) -> Runtime {+ if cfg.is_group() { hub.group_runtime(cfg) } else { hub.runtime(&cfg.id) }+}++/// An approval the bot waits for: its card, what it asks and its options' names.+pub(super) struct Waiting<'a> {+ pub card: &'a Entry,+ pub request: &'a str,+ pub options: Vec<&'a str>,+}++/// The newest approval card still pending in `recent` (oldest first).+pub(super) fn waiting(recent: &[Entry]) -> Option<Waiting<'_>> {+ let card =+ recent.iter().rev().find(|e| e.kind == EntryKind::Permission.as_str() && e.data["status"] == "pending")?;+ Some(Waiting {+ card,+ request: card.data["title"].as_str().or_else(|| card.data["command"].as_str()).unwrap_or_default(),+ options: card.data["options"].as_array().into_iter().flatten().filter_map(|o| o["name"].as_str()).collect(),+ })+}++fn answer(hub: &Hub, cfg: &BotConfig, option: &str) -> Result<Value> {+ let recent = hub.store.history(&cfg.id, i64::MAX, RECENT).unwrap_or_default();+ let Some(card) = waiting(&recent).map(|w| w.card) else {+ return Ok(json!({"error": "Nothing is waiting for approval."}));+ };+ let options = card.data["options"].as_array().cloned().unwrap_or_default();+ let Some(pick) = pick(&options, option) else {+ let names: Vec<String> = options.iter().map(option_name).collect();+ return Ok(json!({"error": "No such option.", "options": names}));+ };+ // A card in a group belongs to the bot that asked.+ let owner = card.data["author"].as_str().unwrap_or(&card.bot_id).to_owned();+ let option_id = pick["optionId"].as_str().map(str::to_owned);+ hub.send_cmd(&owner, Cmd::Permission { entry_id: card.id.clone(), option_id })?;+ Ok(json!({"answered": pick["name"]}))+}++fn option_name(o: &Value) -> String {+ o["name"].as_str().unwrap_or_default().to_lowercase()+}++/// The option the user picked by name (any case) or id, else the one whose name holds what they said or the other+/// way round.+fn pick<'a>(options: &'a [Value], wanted: &str) -> Option<&'a Value> {+ let lower = wanted.to_lowercase();+ options.iter().find(|o| option_name(o) == lower || o["optionId"] == wanted).or_else(|| {+ let near =+ |o: &&Value| !lower.is_empty() && (option_name(o).contains(&lower) || lower.contains(&option_name(o)));+ options.iter().find(near)+ })+}++fn stop(hub: &Arc<Hub>, cfg: &BotConfig) -> Result<Value> {+ if cfg.is_group() {+ hub.groups.stop(hub, &cfg.id);+ } else {+ hub.send_cmd(&cfg.id, Cmd::Stop)?;+ }+ Ok(json!({"stopped": true}))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::store::{BotKind, EntryKind, Lane};++ fn options() -> Vec<Value> {+ ["Allow", "Always", "Reject"]+ .iter()+ .map(|name| json!({"optionId": name.to_lowercase(), "name": name}))+ .collect()+ }++ #[test]+ fn an_approval_is_answered_by_name_id_or_part_of_either() {+ let options = options();+ let picked = |wanted: &str| pick(&options, wanted).map(|o| o["name"].as_str().unwrap().to_owned());+ assert_eq!(picked("ALLOW").as_deref(), Some("Allow"), "any case");+ assert_eq!(picked("always").as_deref(), Some("Always"), "an id");+ assert_eq!(picked("rej").as_deref(), Some("Reject"), "part of a name");+ assert_eq!(picked("Allow once").as_deref(), Some("Allow"), "a name within what was said");+ assert_eq!(picked("maybe"), None);+ assert_eq!(picked(""), None);+ }++ #[test]+ fn the_status_names_what_waits_for_approval_and_a_groups_busy_member() {+ let hub = context::tests::hub();+ let bot = context::tests::bot("b1", "Mika", "/tmp");+ hub.store.save_bot(&bot).unwrap();+ assert_eq!(status(&hub, &bot), json!({"status": "idle", "activity": ""}));+ let card = json!({"title": "Edit a.txt", "status": "pending", "options": options()});+ hub.store.insert_entry(&Lane::main("b1"), EntryKind::Permission, 1, &card).unwrap();+ assert_eq!(+ status(&hub, &bot)["approval"],+ json!({"request": "Edit a.txt", "options": ["Allow", "Always", "Reject"]})+ );++ let group =+ BotConfig { kind: BotKind::Group, members: vec!["b1".into()], ..context::tests::bot("g", "Team", "") };+ hub.set_runtime("b1", |rt| {+ rt.status = crate::hub::BotStatus::Working;+ rt.activity = "Running tests".into();+ rt.lane = Some(Lane::main("g"));+ });+ let busy = status(&hub, &group);+ assert_eq!(+ (busy["status"].as_str(), busy["activity"].as_str()),+ (Some("working"), Some("Mika: Running tests"))+ );+ }++ #[test]+ fn recent_messages_name_who_wrote_each_and_keep_to_twenty() {+ let hub = context::tests::hub();+ let bot = context::tests::bot("b1", "Mika", "/tmp");+ hub.store.save_bot(&bot).unwrap();+ let chat = Lane::main("b1");+ hub.store.insert_entry(&chat, EntryKind::User, 1, &json!({"text": "check git"})).unwrap();+ hub.store+ .insert_entry(&chat, EntryKind::User, 2, &json!({"text": "Check git", "from": "voice", "call": "c"}))+ .unwrap();+ hub.store+ .insert_entry(&chat, EntryKind::Agent, 2, &json!({"text": "**Clean.**", "final": true, "author": "b1"}))+ .unwrap();+ let said = recent(&hub, &bot, 99)["messages"].clone();+ assert_eq!(+ said,+ json!([+ {"from": "User", "text": "check git"},+ {"from": "Voice (relayed)", "text": "Check git"},+ {"from": "Mika", "text": "Clean."},+ ])+ );+ assert_eq!(recent(&hub, &bot, 0)["messages"].as_array().map(Vec::len), Some(1), "at least one");+ }+}diff --git a/host/src/chat/group.rs b/host/src/chat/group.rsindex 5c671b4f..3c69ccea 100644--- a/host/src/chat/group.rs+++ b/host/src/chat/group.rs@@ -47,6 +47,8 @@ pub struct GroupTurn {pub late: bool,/// The reply the room sees, or `None` for a pass.pub reply: oneshot::Sender<Result<Option<String>>>,+ /// The user's message the room turn answers: one a voice call carried makes the reply the call's (`chat::calls`).+ pub answers: Vec<String>,}/// Room turn epochs per group.@@ -153,7 +155,15 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<asked.insert(member.id.clone(), shown);let (reply, answer) = oneshot::channel();let busy = busy_elsewhere(hub, &member.id, lane);- let turn = GroupTurn { lane: lane.clone(), prompt, shown, epoch, late: busy, reply };+ let turn = GroupTurn {+ lane: lane.clone(),+ prompt,+ shown,+ epoch,+ late: busy,+ reply,+ answers: answers(&since_user),+ };if hub.send_cmd(&member.id, Cmd::Group(turn)).is_err() {continue;}@@ -220,6 +230,7 @@ pub fn refresh(hub: &Hub, turn: &mut GroupTurn, me: &BotConfig) -> Result<()> {bail!("no longer in the group");}(turn.prompt, turn.shown) = ask(hub, &group, &members(hub, &group), me, &turn.lane)?;+ turn.answers = answers(&since_last_user_message(hub, &turn.lane)?);Ok(())}@@ -250,6 +261,11 @@ fn since_last_user_message(hub: &Hub, lane: &Lane) -> Result<Vec<Entry>> {Ok(recent[start..].to_vec())}+/// The user's message a room turn answers: the first of `since` (see [`since_last_user_message`]).+fn answers(since: &[Entry]) -> Vec<String> {+ since.first().filter(|e| e.kind == EntryKind::User.as_str()).map(|e| e.id.clone()).into_iter().collect()+}+/// Who answers the user: the members @-mentioned or replied to since the user's last message, or/// everyone when nobody (or `@all` / `@everyone`) is.fn responders<'a>(members: &'a [BotConfig], messages: &[Entry]) -> Vec<&'a BotConfig> {diff --git a/host/src/chat/memory/dream.rs b/host/src/chat/memory/dream.rsindex a21f19af..5839c376 100644--- a/host/src/chat/memory/dream.rs+++ b/host/src/chat/memory/dream.rs@@ -107,6 +107,8 @@ pub fn spawn_dreamer(hub: Arc<Hub>, bot_id: String) -> mpsc::UnboundedSender<Drewaiting >= BATCH && retry_at.is_none()}Some(DreamEvent::Flush) => {+ // Recount: what waits may not have come as a turn (a call's spoken lines, a stopped turn).+ waiting = self::waiting(&hub.store, &bot_id);idle.as_mut().reset(retry_at.unwrap_or_else(Instant::now));false}@@ -138,11 +140,21 @@ pub fn spawn_dreamer(hub: Arc<Hub>, bot_id: String) -> mpsc::UnboundedSender<Dretx}-/// The user's messages since the bookmark.+/// The user's messages since the bookmark, a call's spoken lines each counting as one.fn waiting(store: &Store, bot: &str) -> usize {- store- .conversation_since(bot, bookmark(store, bot), READ_LIMIT)- .map_or(0, |entries| entries.iter().filter(|e| e.kind == EntryKind::User.as_str()).count())+ store.conversation_since(bot, bookmark(store, bot), READ_LIMIT).map_or(0, |entries| {+ entries.iter().map(|e| if e.kind == EntryKind::User.as_str() { 1 } else { spoken(e).count() }).sum()+ })+}++/// What the user said on a call (`chat::calls`), from the voice's transcript.+fn spoken(e: &Entry) -> impl Iterator<Item = &str> {+ e.data["transcript"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|l| l["from"] == "user")+ .filter_map(|l| l["text"].as_str())}/// Once a day, when the bot's MEMORY.md holds a dated line it may rewrite (the time review).@@ -197,7 +209,7 @@ async fn run(hub: &Arc<Hub>, bot_id: &str) -> Result<Ran> {let read = within_batch(&entries);let more = read.len() < entries.len() || i64::try_from(entries.len()).is_ok_and(|n| n == READ_LIMIT);let last_seq = read.last().map_or(after, |e| e.seq);- let messages: Vec<Message> = read.iter().filter_map(message).collect();+ let messages: Vec<Message> = read.iter().flat_map(messages).collect();let today = today();let review = review_due(&hub.store, bot_id);let tidy = tidy_due(&hub.store, bot_id);@@ -298,19 +310,38 @@ fn within_batch(entries: &[Entry]) -> &[Entry] {}/// What a run sees of an entry. A user message counts only for what the user typed themselves; one the host wrote-/// in the user's place (`from: host`) isn't the user's words.-fn message(e: &Entry) -> Option<Message> {+/// in the user's place (`from: host`) isn't the user's words, nor one a call's voice model wrote (`from: voice`, it+/// may rephrase or translate: the call's transcript holds what the user said). A call's line gives its transcript,+/// line by line: the user's lines are their own words, the voice's are context.+fn messages(e: &Entry) -> Vec<Message> {let clip = |text: &str| crate::agent::acp::truncate(text, MESSAGE_CHARS);- let (from_user, text) = if e.kind == EntryKind::User.as_str() {- if e.data["from"] == "host" {- return None;+ let said: Vec<(bool, Vec<String>)> = if e.kind == EntryKind::Notice.as_str() {+ e.data["transcript"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|l| (l["from"] == "user", vec![clip(l["text"].as_str().unwrap_or_default())]))+ .collect()+ } else if e.kind == EntryKind::User.as_str() {+ match e.data["from"].as_str() {+ Some("host") => Vec::new(),+ Some("voice") => vec![(false, vec![clip(e.data["text"].as_str().unwrap_or_default())])],+ _ => vec![(true, typed(&e.data).iter().map(|run| clip(run)).collect())],}- (true, typed(&e.data).iter().map(|run| clip(run)).collect::<Vec<_>>())} else {- (false, vec![clip(e.data["text"].as_str().unwrap_or_default())])+ vec![(false, vec![clip(e.data["text"].as_str().unwrap_or_default())])]};- let text: Vec<String> = text.into_iter().filter(|run| !run.trim().is_empty()).collect();- (!text.is_empty()).then(|| Message { id: e.id.clone(), from_user, text, date: super::dates::ymd(e.created_at) })+ said.into_iter()+ .filter_map(|(from_user, text)| {+ let text: Vec<String> = text.into_iter().filter(|run| !run.trim().is_empty()).collect();+ (!text.is_empty()).then(|| Message {+ id: e.id.clone(),+ from_user,+ text,+ date: super::dates::ymd(e.created_at),+ })+ })+ .collect()}/// The runs of a user message the user typed themselves: not pasted, quoted or forwarded text.@@ -322,7 +353,41 @@ fn typed(data: &serde_json::Value) -> Vec<String> {#[cfg(test)]mod tests {- use super::dated;+ use super::{dated, messages};+ use crate::store::{Entry, EntryKind};+ use serde_json::json;++ fn entry(kind: EntryKind, data: serde_json::Value) -> Entry {+ Entry {+ id: "e".into(),+ seq: 1,+ bot_id: "b".into(),+ rev: 1,+ kind: kind.as_str().into(),+ turn: 1,+ data,+ created_at: 0,+ updated_at: 0,+ }+ }++ #[test]+ fn a_call_counts_what_the_user_said_not_what_the_voice_wrote() {+ let call = entry(+ EntryKind::Notice,+ json!({"text": "Voice chat", "call": "c", "transcript": [+ {"from": "user", "text": "我每週日早上去游泳"},+ {"from": "voice", "text": "好,記下了。"},+ ]}),+ );+ let seen: Vec<(bool, Vec<String>)> = messages(&call).into_iter().map(|m| (m.from_user, m.text)).collect();+ assert_eq!(seen, vec![(true, vec!["我每週日早上去游泳".to_owned()]), (false, vec!["好,記下了。".to_owned()])]);+ let relayed = entry(EntryKind::User, json!({"text": "Note: swims on Sundays", "call": "c", "from": "voice"}));+ assert!(messages(&relayed).iter().all(|m| !m.from_user));+ let spoken = entry(EntryKind::User, json!({"text": "swims on Sundays", "call": "c"}));+ assert!(messages(&spoken).iter().all(|m| m.from_user));+ assert!(messages(&entry(EntryKind::User, json!({"text": "x", "from": "host"}))).is_empty());+ }#[test]fn only_dates_trigger_the_time_review() {diff --git a/host/src/chat/messages.rs b/host/src/chat/messages.rsnew file mode 100644index 00000000..86f10ae4--- /dev/null+++ b/host/src/chat/messages.rs@@ -0,0 +1,31 @@+//! The user's messages in a chat: typed (`send`) or relayed from a voice call (`chat::calls`).++use crate::agent::bot::Cmd;+use crate::hub::Hub;+use crate::store::{BotConfig, Entry, EntryKind, Lane};+use anyhow::{Result, anyhow};+use serde_json::Value;+use std::sync::Arc;++/// Posts `data` (the message's text and what it carries) as the user's newest message in `cfg`'s chat and hands it+/// on: to the bot's agent, or to a group's members.+pub fn post(hub: &Arc<Hub>, cfg: &BotConfig, mut data: Value) -> Result<Entry> {+ // A group has no agent of its own to queue behind: its message is simply sent.+ data["status"] = (if cfg.is_group() { "sent" } else { "queued" }).into();+ let lane = Lane::main(&cfg.id);+ let turn = hub.store.max_turn(&cfg.id) + 1;+ let e = hub.add_entry(&lane, EntryKind::User, turn, &data).ok_or_else(|| anyhow!("couldn't save the message"))?;+ // Before the turn starts, so its reply lands unread.+ if let Err(error) = hub.mark_read(&cfg.id) {+ tracing::warn!(%error, bot = %cfg.id, "couldn't mark bot read after send");+ }+ if cfg.is_group() {+ // Each member reads it in its room prompt (`chat::group`).+ crate::chat::group::start(hub, cfg, lane);+ } else {+ // `/skill …` reaches the agent as "read this skill first"; the chat keeps what was typed.+ let prompt = crate::chat::prompt::of_entry(hub, cfg, &e.data);+ hub.send_cmd(&cfg.id, Cmd::Send { lane, entry_id: e.id.clone(), text: prompt })?;+ }+ Ok(e)+}diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rsindex 89322315..fa1a6472 100644--- a/host/src/chat/mod.rs+++ b/host/src/chat/mod.rs@@ -2,6 +2,7 @@//! bot-to-bot requests, artifacts and the Library, team management, a bot's own fallbacks, prompt snapshots, long-term memory, automatic bot names and the lead bot.pub mod artifacts;+pub mod calls;pub mod context;pub mod fallbacks;pub mod files;@@ -11,6 +12,7 @@ pub mod lead;pub mod library;pub mod manage;pub mod memory;+pub mod messages;pub mod naming;pub mod oneshot;pub mod outbox;diff --git a/host/src/hub.rs b/host/src/hub.rsindex 696a68c5..0ccd9a71 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -195,7 +195,7 @@ impl Hub {}/// A group is busy while one of its members works in it: that member's status and activity.- fn group_runtime(&self, group: &BotConfig) -> Runtime {+ pub fn group_runtime(&self, group: &BotConfig) -> Runtime {let busy = {let runtime = self.runtime.locked();group.members.iter().find_map(|m| {diff --git a/host/src/store/bots.rs b/host/src/store/bots.rsindex d413b62f..cc9be3f5 100644--- a/host/src/store/bots.rs+++ b/host/src/store/bots.rs@@ -100,12 +100,12 @@ impl Store {/// Final agent messages + pending permission cards newer than what the user has read. A reacted-to message/// doesn't count again when it changes: the user reacted, so they have seen it. A bot's reaction isn't a change- /// either (`contentRev`, see `Hub::bot_react`).+ /// either (`contentRev`, see `Hub::bot_react`). Nor is a reply on a voice call: the user heard it.pub fn unread(&self, id: &str, read_rev: i64) -> i64 {let c = self.db.locked();let n = c.query_row("SELECT COUNT(*) FROM entries WHERE bot_id = ?1 AND- ((kind = 'agent' AND json_extract(data, '$.final') = 1) OR+ ((kind = 'agent' AND json_extract(data, '$.final') = 1 AND json_extract(data, '$.call') IS NULL) OR(kind = 'permission' AND json_extract(data, '$.status') = 'pending')) ANDjson_extract(data, '$.reactions') IS NULL ANDCOALESCE(json_extract(data, '$.contentRev'), rev) > ?2",@@ -116,12 +116,14 @@ impl Store {}/// Newest chat-visible line for the roster preview, with its author- /// (`None` for the user; a group reply names the bot that wrote it).+ /// (`None` for the user; a group reply names the bot that wrote it). A voice call's messages show only behind+ /// its line, so they aren't it.pub fn last_message(&self, id: &str) -> Option<LastMessage> {let c = self.db.locked();let row = c.query_row("SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND- (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)) AND+ json_extract(data, '$.call') IS NULLORDER BY seq DESC LIMIT 1",[id],|r| {@@ -198,6 +200,12 @@ mod tests {assert_eq!(s.history("b1", a.seq, 10).unwrap().len(), 1);assert_eq!(s.bot("b1").unwrap().unwrap().config.permission, Permission::Ask);assert!(s.bot("missing").unwrap().is_none());+ // A voice call's messages show only behind its line: neither preview nor unread.+ let said = serde_json::json!({"text": "said on a call", "call": "c"});+ s.insert_entry(&Lane::main("b1"), EntryKind::User, 2, &said).unwrap();+ let heard = serde_json::json!({"text": "heard on it", "final": true, "call": "c"});+ s.insert_entry(&Lane::main("b1"), EntryKind::Agent, 2, &heard).unwrap();+ assert_eq!((s.unread("b1", r), s.last_message("b1").unwrap().text.as_str()), (0, "yo!"));let reply = serde_json::json!({"text": "done", "final": true});// A deleted bot stays deleted, and its winding-down actor leaves no lines behind.diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex 01420dcc..99208e21 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -115,6 +115,17 @@ impl Store {logged("entry by nonce", row.optional()).flatten()}+ /// What a voice call carried in `bot_id`'s chat (`chat::calls`), oldest first: its messages and final replies.+ pub fn call_entries(&self, bot_id: &str, call: &str) -> Result<Vec<Entry>> {+ let c = self.db.locked();+ let mut st = c.prepare(&format!(+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND json_extract(data, '$.call') = ?2 AND+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))+ ORDER BY seq"+ ))?;+ Ok(st.query_map(params![bot_id, call], row_entry)?.collect::<rusqlite::Result<_>>()?)+ }+pub fn max_turn(&self, bot_id: &str) -> i64 {let c = self.db.locked();let n = c.query_row("SELECT COALESCE(MAX(turn), 0) FROM entries WHERE bot_id = ?1", [bot_id], |r| r.get(0));@@ -225,12 +236,13 @@ impl Store {}/// Messages in `bot_id`'s chat after `after_seq`, oldest first: the- /// user's, and final replies. Dreaming reads these.+ /// user's, final replies and voice calls' transcripts. Dreaming reads these.pub fn conversation_since(&self, bot_id: &str, after_seq: i64, limit: i64) -> Result<Vec<Entry>> {let c = self.db.locked();let mut st = c.prepare(&format!("SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq > ?2 AND- (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)+ OR (kind = 'notice' AND json_extract(data, '$.transcript') IS NOT NULL))ORDER BY seq LIMIT ?3"))?;Ok(st.query_map(params![bot_id, after_seq, limit], row_entry)?.collect::<rusqlite::Result<_>>()?)diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex f52d16cd..ef47f9d2 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -233,6 +233,9 @@ impl App {/// A chat's entries, in display order.pub fn lane(&self, bot: &str) -> Vec<&Entry> {let mut v: Vec<&Entry> = self.entries.get(bot).map(|m| m.values().collect()).unwrap_or_default();+ // What a finished voice call carried shows behind its line (`o`).+ let ended: HashSet<&str> = v.iter().filter(|e| e.kind == Kind::Notice).filter_map(|e| e.call()).collect();+ v.retain(|e| e.kind == Kind::Notice || e.call().is_none_or(|c| !ended.contains(c)));// A message sent mid-turn belongs after that turn's reply.v.sort_by_key(|e| (e.turn, e.seq));vdiff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex 67aed03b..9a5aecad 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -184,9 +184,14 @@ impl Entry {if self.is_final() { self.data["artifact"]["id"].as_str() } else { None }}- /// A line that folds away a longer text: a handoff (`o` shows it).+ /// A line that folds away a longer text: a handoff, or a voice call's conversation (`o` shows it).pub fn unfolds(&self) -> bool {- crate::tui::view::unfoldable(self).is_some()+ crate::tui::view::unfoldable(self).is_some() || (self.kind == Kind::Notice && self.call().is_some())+ }++ /// The voice call this was said in, or that this line ends (`chat::calls`).+ pub fn call(&self) -> Option<&str> {+ self.data["call"].as_str()}/// A failure notice that offers adding a fallback agent (`A`).diff --git a/host/src/tui/app/tests.rs b/host/src/tui/app/tests.rsindex c847c580..4549917e 100644--- a/host/src/tui/app/tests.rs+++ b/host/src/tui/app/tests.rs@@ -39,3 +39,22 @@ async fn r_on_a_picked_message_replies_to_it() {assert_eq!(app.replying_to().map(Entry::quoted).as_deref(), Some("hi"));assert!(app.typing && app.pick.is_none());}++#[tokio::test]+async fn a_finished_calls_messages_hide_behind_its_line() {+ let mut app = test_app();+ let messages = [+ (1, "user", json!({"text": "spoken", "call": "c"})),+ (2, "agent", json!({"text": "reply", "final": true, "call": "c"})),+ (3, "user", json!({"text": "on a live call", "call": "live"})),+ (4, "notice", json!({"text": "Release plan", "callSeconds": 26, "call": "c"})),+ ];+ for (seq, kind, data) in messages {+ let v = json!({"botId": "b", "id": format!("e{seq}"), "seq": seq, "turn": 1, "kind": kind, "data": data});+ let (bot, e) = Entry::parse(&v).expect("a full entry parses");+ app.entries.entry(bot).or_default().insert(e.seq, e);+ }+ let shown: Vec<&str> = app.lane("b").iter().map(|e| e.id.as_str()).collect();+ assert_eq!(shown, ["e3", "e4"], "an ended call's messages hide; a call without its line yet doesn't");+ assert!(app.lane("b").last().is_some_and(|e| e.unfolds()), "the call's line opens its conversation");+}diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex e67679ba..6c824309 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -270,6 +270,9 @@ fn entry_lines(out: &mut Built, app: &App, b: &Bot, e: &Entry, info: &HashMap<i6// Another agent took over (or the bot's own came back): `o` shows what it was told.let hint = if unfoldable(e).is_some() { " · o shows what it carried" } else { "" };format!("↪ {}{hint}", e.notice_text())+ } else if e.call().is_some() {+ // A voice call's line: its title and length; `o` shows the conversation.+ format!("{} · o shows the call", e.notice_text())} else if app.fallback_owner(&b.id, e).is_some() {format!("{} · A adds a fallback", e.notice_text())} else if e.retries() {@@ -293,17 +296,18 @@ fn entry_lines(out: &mut Built, app: &App, b: &Bot, e: &Entry, info: &HashMap<i6)),}let folded = unfoldable(e);- if app.unfolded.contains(&e.id)- && let Some(full) = folded- {- out.lines.extend(md::wrap(- &[Span::styled(full.to_owned(), t.dim)],- width,- &[Span::raw(" │ ")],- &[Span::raw(" │ ")],- ));+ if app.unfolded.contains(&e.id) {+ let full = folded.map_or_else(|| call_lines(app, b, e), |f| vec![f.to_owned()]);+ for text in full {+ out.lines.extend(md::wrap(+ &[Span::styled(text, t.dim)],+ width,+ &[Span::raw(" │ ")],+ &[Span::raw(" │ ")],+ ));+ }}- if e.data["connectionRequest"].is_object() || folded.is_some() || e.retries() || e.adds_fallback() {+ if e.data["connectionRequest"].is_object() || e.unfolds() || e.retries() || e.adds_fallback() {out.messages.push((e.id.clone(), from, out.lines.len()));}}@@ -311,6 +315,32 @@ fn entry_lines(out: &mut Built, app: &App, b: &Bot, e: &Entry, info: &HashMap<i6}}+/// A voice call's conversation, oldest first: what was said (the voice's transcript) and the messages the call+/// carried, which the chat shows only here.+fn call_lines(app: &App, b: &Bot, line: &Entry) -> Vec<String> {+ let Some(call) = line.call() else { return Vec::new() };+ let mut said: Vec<(i64, String)> = line.data["transcript"]+ .as_array()+ .into_iter()+ .flatten()+ .map(|l| {+ let who = if l["from"] == "user" { "you" } else { "voice" };+ (l["at"].as_i64().unwrap_or(line.created_at), format!("{who}: {}", l["text"].as_str().unwrap_or_default()))+ })+ .collect();+ let carried = app.entries.get(&b.id).into_iter().flat_map(|m| m.values());+ for e in carried.filter(|e| e.call() == Some(call) && (e.kind == Kind::User || e.is_final())) {+ let who = match (e.kind, e.data["from"].as_str()) {+ (Kind::User, Some("voice")) => "voice → bot",+ (Kind::User, _) => "you",+ _ => b.name.as_str(),+ };+ said.push((e.created_at, format!("{who}: {}", e.text())));+ }+ said.sort_by_key(|(at, _)| *at);+ said.into_iter().map(|(_, text)| text).collect()+}+/// The full text a chat line folds away: what a handoff carries, or what an agent taking over was told.pub(in crate::tui) fn unfoldable(e: &Entry) -> Option<&str> {e.data["handoff"]["text"].as_str().or_else(|| e.data["agentSwitch"]["carried"].as_str()).filter(|t| !t.is_empty())diff --git a/host/tests/calls_e2e.rs b/host/tests/calls_e2e.rsnew file mode 100644index 00000000..c73cac16--- /dev/null+++ b/host/tests/calls_e2e.rs@@ -0,0 +1,103 @@+//! Voice calls on a real host driving scripted agents: what a call hands the bot, and the replies to it, are the+//! call's while it lasts; a reply to a typed message, or one after the call ended, shows in the chat as usual.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use serde_json::{Value, json};+use std::path::PathBuf;+use std::time::{Duration, Instant};++/// Polls `chat`'s history until an entry matches `pred`, past the ones `seen` already matched.+async fn wait_for(host: &Host, chat: &str, seen: usize, pred: impl Fn(&Value) -> bool) -> Value {+ let deadline = Instant::now() + Duration::from_secs(30);+ loop {+ let history = host.call("history", json!({"botId": chat})).await;+ if let Some(e) = history["entries"].as_array().unwrap().iter().filter(|e| pred(e)).nth(seen) {+ return e.clone();+ }+ assert!(Instant::now() < deadline, "timed out; history: {history}");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+}++fn pending(e: &Value) -> bool {+ e["kind"] == "permission" && e["data"]["status"] == "pending"+}++fn reply(e: &Value) -> bool {+ e["kind"] == "agent" && e["data"]["final"] == true+}++async fn tool(host: &Host, call: &str, name: &str, arguments: Value) -> Value {+ host.call("callTool", json!({"callId": call, "name": name, "arguments": arguments})).await["result"].clone()+}++#[tokio::test]+async fn replies_are_the_calls_while_it_lasts() {+ let host = Host::start().await;+ // Each turn asks to edit a file, then answers with how it was approved.+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_agent.py");+ let bot = json!({"name": "Mika", "backend": "custom", "command": common::python_agent(&agent), "permission": "ask",+ "connectors": [], "notify": false});+ let bot = host.call("createBot", bot).await["bot"]["id"].as_str().unwrap().to_owned();+ host.call("startCall", json!({"botId": bot, "callId": "c1", "mode": "device"})).await;++ // The user's words the app hadn't sent yet ride along with the hand-off.+ let lines = json!([{"from": "user", "text": "改一下 a.txt", "at": 1}]);+ let body = json!({"callId": "c1", "name": "send_to_bot", "arguments": {"text": "Edit a.txt"}, "lines": lines});+ assert_eq!(host.call("callTool", body).await["result"]["sent"], true);+ let relayed = wait_for(&host, &bot, 0, |e| e["kind"] == "user").await;+ assert_eq!((relayed["data"]["call"].as_str(), relayed["data"]["from"].as_str()), (Some("c1"), Some("voice")));+ assert!(relayed["data"]["text"].as_str().unwrap().contains("«改一下 a.txt»"), "{relayed}");++ wait_for(&host, &bot, 0, pending).await;+ // While it waits: a message said on the call and a typed one, answered together.+ host.call("send", json!({"botId": bot, "text": "and b.txt", "clientNonce": "n1", "call": "c1"})).await;+ host.call("send", json!({"botId": bot, "text": "typed", "clientNonce": "n2"})).await;+ let status = tool(&host, "c1", "bot_status", json!({})).await;+ assert_eq!(status["approval"], json!({"request": "Edit a.txt", "options": ["Allow", "Always", "Reject"]}));+ assert_eq!(tool(&host, "c1", "answer_approval", json!({"option": "allow"})).await["answered"], "Allow");+ let first = wait_for(&host, &bot, 0, reply).await;+ assert_eq!(first["data"]["call"], "c1", "a reply to the call is the call's: {first}");++ wait_for(&host, &bot, 0, pending).await;+ assert_eq!(tool(&host, "c1", "answer_approval", json!({"option": "ALLOW"})).await["answered"], "Allow");+ let mixed = wait_for(&host, &bot, 1, reply).await;+ assert!(mixed["data"]["call"].is_null(), "a typed message in the batch shows its reply: {mixed}");+ let said = tool(&host, "c1", "recent_messages", json!({"count": 3})).await;+ assert_eq!(said["messages"][0]["from"], "User", "{said}");++ // The call ends while the bot works on what it was handed last.+ assert_eq!(tool(&host, "c1", "send_to_bot", json!({"text": "Edit a.txt again"})).await["sent"], true);+ let card = wait_for(&host, &bot, 0, pending).await;+ let end =+ json!({"botId": bot, "callId": "c1", "seconds": 42, "lines": [{"from": "voice", "text": "Asking Mika."}]});+ let line = host.call("endCall", end.clone()).await["entry"].clone();+ assert_eq!(line["data"]["transcript"].as_array().map(Vec::len), Some(2), "{line}");+ assert!(host.call("endCall", end).await["entry"].is_null(), "an app trying again ends the call once");+ host.call("respondPermission", json!({"entryId": card["id"], "optionId": "allow"})).await;+ let after = wait_for(&host, &bot, 2, reply).await;+ assert!(after["data"]["call"].is_null(), "after the call, replies show in the chat: {after}");+ assert!(tool(&host, "c1", "bot_status", json!({})).await["error"].is_string(), "an ended call runs no tools");+}++#[tokio::test]+async fn a_group_calls_replies_are_the_calls() {+ let host = Host::start().await;+ let member = host.fixture_bot("Mika", "relay_agent.py", "mika").await;+ let group = json!({"name": "Room", "kind": "group", "members": [member]});+ let group = host.call("createBot", group).await["bot"]["id"].as_str().unwrap().to_owned();+ host.call("startCall", json!({"botId": group, "callId": "g1", "mode": "device"})).await;++ assert_eq!(tool(&host, "g1", "send_to_bot", json!({"text": "Who's here?"})).await["sent"], true);+ let answer = wait_for(&host, &group, 0, reply).await;+ assert_eq!((answer["data"]["call"].as_str(), answer["data"]["author"].as_str()), (Some("g1"), Some(&*member)));++ host.call("endCall", json!({"botId": group, "callId": "g1", "seconds": 5})).await;+ host.call("send", json!({"botId": group, "text": "And now?", "clientNonce": "n1"})).await;+ let typed = wait_for(&host, &group, 1, reply).await;+ assert!(typed["data"]["call"].is_null(), "{typed}");+}diff --git a/web/content/docs/memory.mdx b/web/content/docs/memory.mdxindex ce6448a2..1c8bd853 100644--- a/web/content/docs/memory.mdx+++ b/web/content/docs/memory.mdx@@ -61,9 +61,9 @@ The tab has these sections:Between chats, the bot tidies its memory from your own words. This is called dreaming.-- **When:** after five quiet minutes or eight of your messages, sooner after a new session and before Codync compacts a conversation, and once a day to update lines whose date has passed (putting them in the past tense).+- **When:** after five quiet minutes or eight of your messages (each thing you say on a call counts as one), sooner after a new session and before Codync compacts a conversation, and once a day to update lines whose date has passed (putting them in the past tense).- **What:** it reads what you said since its last run, then adds lines to MEMORY.md, takes out lines that went out of date, and adds lines to notes.-- **Only your words:** every change has to quote something you typed yourself. Pasted text, code blocks, quoted or forwarded messages, the bot's replies and other bots don't count. Group chats and bot requests never feed it.+- **Only your words:** every change has to quote something you typed yourself, or said on a call (from the call's transcript). Pasted text, code blocks, quoted or forwarded messages, the voice's wording of what it passed on, the bot's replies and other bots don't count. Group chats and bot requests never feed it.- **Small steps:** at most 10 changes a run, never taking out more than a quarter of the lines. It never removes or rewrites a line you wrote, never brings back something you had a bot forget, and never rewrites a note.- **Tidying:** when a MEMORY.md is nearly full, dreaming moves detail word for word into notes by topic, your lines too, and leaves one line per topic that points to its note, such as "Allergic to peanuts → health/allergies.md". That way memory doesn't fill up.@@ -115,5 +115,5 @@ The bot's chat, its memory and the agent's session are separate things.## Limits- Memory search looks for the words you give it, so a fact worded differently won't match.-- Dreaming treats voice transcripts like typed text.+- What you say on a call reaches dreaming as speech recognition heard it, so a misheard word counts as said.- In your own chat, a bot can still change memory because of something it read along the way, such as a web page or a file. Outside your own chat, it can only add.diff --git a/web/content/docs/privacy.mdx b/web/content/docs/privacy.mdxindex 46b74001..84f7ca72 100644--- a/web/content/docs/privacy.mdx+++ b/web/content/docs/privacy.mdx@@ -44,7 +44,7 @@ What leaves your device in a voice call or during dictation depends on the engin| Engine | Where your voice goes || --- | --- || On device (the default) | Recognized on your iPhone or Mac with Apple speech. Apple's servers may be used when on-device recognition isn't available for your language. Only the recognized text goes to your computer, as an ordinary message. |-| OpenAI or Gemini, Realtime mode | Straight from your device to the provider. Your computer gives the device a short-lived credential made from your key. The provider also gets the bot's name and description and the chat messages the call reads during the call. |+| OpenAI or Gemini, Realtime mode | Straight from your device to the provider. Your computer gives the device a short-lived credential made from your key. Before the call, the provider also gets the background your computer writes for the voice: the date and time, what your bots remember about you (shared memory and the names of its notes), this bot's settings, routines and memory, the project's git branch, changed files and recent commits, what the bot is working on, the recent messages and calls in the chat, your other bots, and the names of files shared in the chat. During the call it gets the messages and results the voice reads. A written transcript of the call stays on your computer, in the chat. || OpenAI or Gemini, Speech mode, and dictation with a provider | Your recording goes to your computer over the encrypted connection, and your computer sends it to the provider with your key and the names of the bots on the computer as spelling hints. The provider's spoken replies come back the same way. |Your provider key stays on your computer, encrypted. It's never sent to the relay or Codync's cloud. Calls with your own key run under your provider account and its privacy policy.diff --git a/web/content/docs/voice.mdx b/web/content/docs/voice.mdxindex 75675511..131bbf03 100644--- a/web/content/docs/voice.mdx+++ b/web/content/docs/voice.mdx@@ -3,7 +3,7 @@ You can talk to your bots two ways:- **Voice call:** a hands-free conversation with a bot or a group chat. You speak, the bot's replies are read aloud.- **Dictation:** speak into the message box, check the text, then send it yourself.-Both work in the iPhone app and the desktop app. The terminal UI has no microphone, so it has neither, but it shows the notice a call leaves in the chat.+Both work in the iPhone, Android and desktop apps. The terminal UI has no microphone, so it has neither, but it shows the line a call leaves in the chat (press `o` on it to read the call).A call doesn't change the bot. It's the same agent on your computer; you're just talking to it instead of typing.@@ -20,7 +20,9 @@ The call bar floats at the top of the chat, and the chat stays readable and usabMost bots wait for you to speak. Your [lead bot](/docs/bots#your-lead-bot) speaks first: once the call connects, it tells you in a sentence or two what deserves your attention, or greets you. If it's busy working, its reply comes when the work is done instead.-When the call ends, the chat gets a notice such as "Voice chat · 00:16", in every app.+What you say on a call, and the bot's replies during it, don't fill up the chat. When the call ends, the chat gets one line instead: a waveform, a short title for what the call was about (such as "Release plan · 03:12"; "Voice chat" until the title is written), and its length. Tap it to read the whole call: what you said, what the voice said, and what went to the bot and back.++The bot remembers what matters from the call like from any conversation: its memory picks up what you said, not the voice's wording.On the iPhone, the first call asks for Microphone and Speech Recognition access. The call keeps going if you leave Codync for the Home Screen.@@ -46,7 +48,7 @@ Under **Engine**, pick one. The choice is kept on this device. Changed during a### On device- You speak in the language set under **Language** (by default, your device's first language).-- A pause ends what you said and sends it as an ordinary message. If the bot is busy, it's queued like any other message. Set the pause under **Send after a pause of** (1 s, 1.5 s or 2.5 s).+- A pause ends what you said and sends it to the bot as part of the call. If the bot is busy, it's queued like any other message. Set the pause under **Send after a pause of** (1 s, 1.5 s or 2.5 s).- Each reply is read aloud in the language it's written in, skipping code blocks and formatting. Set **Reading speed** to Slower, Normal or Faster. The microphone pauses while a reply is read.- When the bot asks for approval, the call tells you; answer it in the chat.@@ -59,7 +61,9 @@ Each provider has two modes, under **Mode**:- **Realtime:** a live conversation with the provider's realtime model. You can talk over replies.- **Speech:** the same loop as On device, using the provider's speech-to-text and text-to-speech models instead. What you say is sent when you pause, and replies are read aloud.-In Realtime mode, the voice model works in front of your bot, and the bot still does the work. The voice model passes your requests to the bot as ordinary messages, reads the bot's replies out in shortened form, can tell you what the bot is doing ("what are you working on?") from its status and recent messages, and answers an approval for you once you've said which option. The chat stays the record: only the messages sent to the bot and the bot's replies are saved, and the small talk with the voice model isn't.+In Realtime mode, the voice model is the bot's voice line, not the bot: it talks with you, and the bot does the work. It passes your requests on to the bot (along with your own words, so nothing gets lost in its wording), reads the bot's replies out in shortened form, tells you what the bot is doing ("what are you working on?"), answers an approval for you once you've said which option, can stop the bot, and can look up what the bot remembers.++Before a Realtime call, your computer gives the voice model the background it needs: the date and time, what your bots remember about you, this bot's settings and memory, the project's git branch and recent changes, what the bot is working on, the recent messages and calls in this chat, your other bots, and the files shared in the chat. Like your audio, it goes to OpenAI or Google on your own key.Below the key you can pick the **Model** (or, in Speech mode, **Speech to text** and **Text to speech**) and the **Voice**. The default models follow each provider's newest ones. **This month** shows an estimate of the minutes used, counted on each device. The provider bills you; it isn't a bill.@@ -82,7 +86,7 @@ The key is stored encrypted in Codync's vault on the computer (with the system k| You use | Your audio | Your key || --- | --- | --- || On device | Stays on your device. Only the recognized text goes to the computer, as a message. Apple's speech recognition may use Apple's servers when on-device recognition isn't available for your language. | Not needed |-| Realtime | Streams directly between your device and the provider (OpenAI over WebRTC, Gemini over a WebSocket). It doesn't pass through your computer or the relay. | Stays on the computer, which gives your device a short-lived credential for each call |+| Realtime | Streams directly between your device and the provider (OpenAI over WebRTC, Gemini over a WebSocket). It doesn't pass through your computer or the relay. The written transcript of the call is kept on your computer. | Stays on the computer, which gives your device a short-lived credential for each call || Speech mode, or dictation with a provider | Recordings go to your computer over the encrypted connection, and the computer sends them to the provider, with the names of the bots on the computer as spelling hints. The spoken replies come back the same way. | Stays on the computer |The relay only ever sees encrypted data. Whenever audio leaves your device, the call bar names the provider.