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
fix: a call's conversation is whole, and calls stay out of every chat
leepokai6efe220af5fa
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.ktindex 10abdf77..4b5c9b07 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppStoreChat.kt@@ -36,6 +36,14 @@ internal fun AppStore.acknowledgeVisible(chats: List<String> = state.value.readifor (chat in chats) action("read:" + chat) { channel?.call("markRead", body("botId" to chat)) }}+/** The entries of a host reply (`callEntries`, `botConversation`). */+internal fun entriesOf(response: JsonElement): List<Entry> =+ response.jsonObject["entries"]?.jsonArray?.map { Entry.decode(it.jsonObject) }.orEmpty()++/** What a voice call carried (iOS `BotStore.callEntries`): the chat this phone holds may not reach back to it. */+internal suspend fun AppStore.callEntries(botId: String, call: String): List<Entry> =+ entriesOf(hostCall("callEntries", buildJsonObject { put("botId", botId); put("callId", call) }, 20_000))+fun AppStore.loadHistory() {val id = state.value.selectedBot ?: returnaction("history") {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 635822a0..2dc2a86b 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@@ -128,9 +128,9 @@ private fun AppStore.begin(call: VoiceBinding, provider: VoiceProvider?) {}}-/** The call's audio is live: the lead speaks first (only a host with leads marks one, so an older host never gets this). */+/** The call's audio is live: the lead speaks first, on the call (only a host with leads marks one, so an older host never gets this). */private fun AppStore.callStarted(call: VoiceBinding) {- if (state.value.bots.any { it.id == call.botId && it.lead }) command("callStarted", body("botId" to call.botId), "callStarted:" + call.botId)+ if (state.value.bots.any { it.id == call.botId && it.lead }) command("callStarted", body("botId" to call.botId, "callId" to call.id), "callStarted:" + call.botId)}/** After the call settings close: a different engine picked there takes over the call, which goes on. */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt b/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.ktindex 007d970c..64c3c95b 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/BotConversation.kt@@ -42,8 +42,6 @@ import com.kyant.shapes.RoundedRectangleimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.launchimport kotlinx.serialization.json.buildJsonObject-import kotlinx.serialization.json.jsonArray-import kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.putprivate fun AppState.authorName(id: String): String = bots.firstOrNull { it.id == id }?.name ?: "A deleted bot"@@ -71,8 +69,7 @@ private fun AppState.authorName(id: String): String = bots.firstOrNull { it.id =var error by remember(peerId) { mutableStateOf<String?>(null) }LaunchedEffect(bot.id, peerId) {try {- val result = store.hostCall("botConversation", buildJsonObject { put("botId", bot.id); put("peerId", peerId) }, 20_000)- fetched = result.jsonObject["entries"]?.jsonArray?.map { Entry.decode(it.jsonObject) }.orEmpty()+ fetched = entriesOf(store.hostCall("botConversation", buildJsonObject { put("botId", bot.id); put("peerId", peerId) }, 20_000))} catch (cancelled: CancellationException) { throw cancelled }catch (failure: Exception) { fetched = emptyList(); error = failure.message ?: "Couldn't load the conversation." }}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.ktindex c29b193f..8f3ad876 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/CallRows.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/CallRows.kt@@ -16,9 +16,14 @@ import androidx.compose.foundation.text.selection.SelectionContainerimport androidx.compose.material3.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.clip+import androidx.compose.ui.semantics.clearAndSetSemanticsimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.text.style.TextAlign@@ -26,9 +31,12 @@ import androidx.compose.ui.text.style.TextOverflowimport androidx.compose.ui.unit.dpimport com.codync.android.core.CallMessageimport com.codync.android.core.Entry+import com.codync.android.core.callimport com.codync.android.core.callConversation+import com.codync.android.core.withCallEntriesimport com.codync.android.design.*import com.kyant.shapes.RoundedRectangle+import kotlinx.coroutines.CancellationExceptionimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.longOrNull@@ -50,19 +58,33 @@ import kotlinx.serialization.json.longOrNull* 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) {+@Composable internal fun CallConversationView(botId: String, lineId: String, state: AppState, store: AppStore) {val entries = state.entries.filter { it.botId == botId }val line = entries.firstOrNull { it.id == lineId }- val messages = line?.let { entries.callConversation(it) }.orEmpty()+ val call = line?.call+ // The call's own messages, which the chat this phone holds may not reach back to; null while they load.+ var fetched by remember(lineId) { mutableStateOf<List<Entry>?>(null) }+ var error by remember(lineId) { mutableStateOf<String?>(null) }+ LaunchedEffect(botId, call) {+ if (call == null) return@LaunchedEffect+ try { fetched = store.callEntries(botId, call) }+ catch (cancelled: CancellationException) { throw cancelled }+ catch (failure: Exception) { fetched = emptyList(); error = failure.message ?: "Couldn't load the call." }+ }+ val loading = tr("Loading the call")+ val messages = line?.let { entries.withCallEntries(fetched.orEmpty()).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)+ if (error != null || fetched != null && messages.isEmpty()) item("empty") {+ Text(tr(error ?: "Nothing was said on this call."), Modifier.fillMaxWidth().padding(top = 24.dp), style = Type.footnote,+ color = if (error != null) Palette.danger else Palette.tertiary, textAlign = TextAlign.Center)+ } else if (fetched == null && call != null) item("loading") {+ Box(Modifier.fillMaxWidth().padding(top = 24.dp).clearAndSetSemantics { contentDescription = loading },+ contentAlignment = Alignment.Center) { Spinner(14.dp) }}itemsIndexed(messages) { _, message -> CallMessageRow(message) }}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 a06ba86c..04ab2479 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@@ -138,7 +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(callLine, { callLine = null }) { CallConversationView(bot.id, it, state, store) }CodyncSheet(app, { app = null; setupEntry = null }) { ComposioConnectSheet(it, state, store, setupEntry) { store.refreshPlugins() } }CodyncSheet(connector, { connector = null; setupEntry = null }) { InstallConnectorSheet(it, state, store, setupEntry) }}@@ -200,7 +200,7 @@ import com.kyant.shapes.CapsuleindicatorTop: Dp, openRoutine: (String) -> Unit, reply: (Entry) -> Unit, addFallback: (Bot) -> Unit, openArtifact: (OpenArtifact) -> Unit,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))+ val entries = state.entries.filter { it.botId == bot.id && it.isChat }.hidingCalls()// 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)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.ktindex 5679c0cd..721911a6 100644--- 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.kt@@ -59,15 +59,16 @@ data class CallTool(val name: String, val description: String, val parameters: J})}-/** 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)+/** One line of a call: what the user said (`user`) or the voice answered (`voice`), with when (ms) and the phone's+ * id for it (one sent again, its first answer lost, is kept once). */+@Serializable data class CallLine(val from: String, val text: String, val at: Long? = null, val id: String? = 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 newId: () -> String = { java.util.UUID.randomUUID().toString() }, private val turnEnded: () -> Unit) {private val lines = mutableListOf<CallLine>()private var open = false@@ -75,7 +76,7 @@ class CallTranscript(private val clock: () -> Long = System::currentTimeMillis,if (piece.isEmpty()) returnval 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 }+ else { endTurn(); lines += CallLine(from, piece, clock(), newId()); open = true }}fun endTurn() { open = false; turnEnded() }@@ -102,10 +103,14 @@ data class CallMessage(val speaker: Speaker, val text: String) {/** 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 }+/** Without what voice calls carry, whichever device the call is on: it shows behind the call's line, which the computer+ * writes when the call ends or its app went away. A file or an artifact the bot sent stays, to be opened. */+fun List<Entry>.hidingCalls(): List<Entry> = filter { it.kind == "notice" || it.call == null || it.files.isNotEmpty() || it.artifact != null }++/** With a call's own entries (`callEntries`), which the chat may not hold: each entry once, the chat's copy first. */+fun List<Entry>.withCallEntries(fetched: List<Entry>): List<Entry> {+ val held = mapTo(HashSet()) { it.id }+ return this + fetched.filter { it.id !in held }}/** A call's conversation, oldest first: what was said (the voice's transcript) and the messages it carried. */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 b2d6805b..24e0b826 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@@ -112,11 +112,11 @@ class VoiceEnginesTest {@Test fun aCallsTranscriptJoinsEachTurnAndItsMessagesHideBehindItsLine() {var now = 0L- val transcript = CallTranscript({ ++now }, { it.uppercase() }) { }+ val transcript = CallTranscript({ ++now }, { it.uppercase() }, { "l$now" }) { }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))+ assertEquals("the line being said stays", listOf(CallLine("user", "看一下 GIT", 1, "l1")), 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))+ assertEquals(listOf(CallLine("user", "AGAIN", 0), CallLine("voice", "CHECKING.", 2, "l2")), 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")@@ -127,9 +127,18 @@ class VoiceEnginesTest {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("x1", "n1"), entries.hidingCalls().map(Entry::id))+ val file = entry("f1", 10, "agent", { put("text", "log.txt (3 bytes)"); put("final", true); put("call", "c")+ putJsonArray("files") { addJsonObject { put("id", "f"); put("name", "log.txt"); put("size", 3); put("sha256", "") } } })+ assertEquals("a file the call brought stays, to be opened", listOf("x1", "n1", "f1"), (entries + file).hidingCalls().map(Entry::id))assertEquals(listOf("User: 看一下 git", "VoiceToBot: check git", "Bot: Clean"),entries.callConversation(line).map { "${it.speaker}: ${it.text}" })+ // A call older than the chat the phone holds: its own entries, fetched, fill in the conversation once each.+ val old = listOf(line)+ assertTrue(old.callConversation(line).size == 1)+ val fetched = entries.filter { it.call == "c" && it.kind != "notice" }+ assertEquals(old.callConversation(line).size + 2, old.withCallEntries(fetched).callConversation(line).size)+ assertEquals(entries.size, entries.withCallEntries(fetched).size)val declarations = runBlocking { Link().start(VoiceProvider.Gemini, "m", "v") }.tools.map(CallTool::gemini)assertNull(declarations.first { it["name"]!!.jsonPrimitive.content == "bot_status" }["parameters"])assertEquals("STRING", declarations[0]["parameters"]!!.jsonObject["properties"]!!.jsonObject["text"]!!.jsonObject["type"]!!.jsonPrimitive.content)diff --git a/apps/desktop/src/renderer/lib/use-fetched.ts b/apps/desktop/src/renderer/lib/use-fetched.tsnew file mode 100644index 00000000..a2f8798c--- /dev/null+++ b/apps/desktop/src/renderer/lib/use-fetched.ts@@ -0,0 +1,28 @@+import { useEffect, useState, type DependencyList } from 'react'++/**+ * What `load` resolves to, null while it loads (or when it has nothing to load); `error` says why it failed. An answer+ * that arrives after `deps` changed is dropped.+ */+export function useFetched<T>(load: () => Promise<T> | null, deps: DependencyList): { fetched: T | null; error: string | null } {+ const [fetched, setFetched] = useState<T | null>(null)+ const [error, setError] = useState<string | null>(null)+ useEffect(() => {+ const loading = load()+ if (!loading) return+ let current = true+ loading.then(+ (value) => {+ if (current) setFetched(value)+ },+ (reason: unknown) => {+ console.warn('load failed', reason)+ if (current) setError(reason instanceof Error ? reason.message : String(reason))+ },+ )+ return () => {+ current = false+ }+ }, deps)+ return { fetched, error }+}diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 3c962aab..7a68b1ad 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -148,14 +148,6 @@ export class BotStore extends BotSync {this.perform((c) => c.call('switchBack', { botId }), true)}- /** 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 {@@ -165,14 +157,13 @@ export class BotStore extends BotSync {} 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). */- callStarted(botId: string) {+ callStarted(botId: string, call: string) {if (!this.bots.get(botId)?.lead) return- this.perform((c) => c.call('callStarted', { botId }))+ // Its opening is the call's, like everything said on it.+ this.perform((c) => c.call('callStarted', { botId, callId: call }))}screenTakeover(on: boolean) {@@ -358,6 +349,11 @@ export class BotStore extends BotSync {this.perform((c) => c.call('updateBot', draft), true)}+ /** What a voice call carried, from the computer: the loaded chat may not reach back to it. */+ async callEntries(botId: string, call: string): Promise<Entry[]> {+ return (await (await this.ready()).call<{ entries: Entry[] }>('callEntries', { botId, callId: call })).entries+ }+/** The history between a bot and one peer. Never upserted: old notices would break `loadOlder`'s paging. */async botConversation(botId: string, peerId: string): Promise<Entry[]> {return (await this.ready()).botConversation(botId, peerId)diff --git a/apps/desktop/src/renderer/views/call/CallRows.tsx b/apps/desktop/src/renderer/views/call/CallRows.tsxindex decdced6..24b6b448 100644--- a/apps/desktop/src/renderer/views/call/CallRows.tsx+++ b/apps/desktop/src/renderer/views/call/CallRows.tsx@@ -1,10 +1,12 @@-import { callConversation, type CallMessage } from '@shared/calls'+import { callConversation, withCallEntries, type CallMessage } from '@shared/calls'import type { Entry } from '@shared/models'import { useEffect, useRef } from 'react'+import { Spinner } from '../../components/Controls'import { Icon } from '../../components/Icon'import { ModalHeader } from '../../components/Overlay'import { VStack } from '../../components/Stack'import { Text } from '../../components/Text'+import { useFetched } from '../../lib/use-fetched'import { useTr } from '../../lib/use-language'import { useStore } from '../../store/context'import { Bubble } from '../thread/ChatRows'@@ -35,9 +37,12 @@ export function CallLineRow({ entry, open }: { entry: Entry; open: () => void })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 live = store.allEntries(botId)+ const line = live.find((e) => e.id === lineId)+ const call = line?.data.call+ // The call's own messages, which the loaded chat may not reach back to; null while they load.+ const { fetched, error } = useFetched(() => (call ? store.callEntries(botId, call) : null), [store, botId, call])+ const messages = line ? callConversation(withCallEntries(live, fetched ?? []), line) : []const scroller = useRef<HTMLDivElement>(null)useEffect(() => {const el = scroller.current@@ -48,7 +53,9 @@ export function CallConversationView({ botId, lineId }: { botId: string; lineId:<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}+ {error ? <Text as="div" size="footnote" tone="danger" className="bot-conversation-note">{error}</Text> : null}+ {fetched === null && !error && call ? <div className="bot-conversation-note" aria-label={tr('Loading the call')}><Spinner /></div> : null}+ {!error && fetched !== null && 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>diff --git a/apps/desktop/src/renderer/views/call/CallView.tsx b/apps/desktop/src/renderer/views/call/CallView.tsxindex 20c2daa6..bdd9bb6d 100644--- a/apps/desktop/src/renderer/views/call/CallView.tsx+++ b/apps/desktop/src/renderer/views/call/CallView.tsx@@ -172,7 +172,6 @@ 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)@@ -195,7 +194,7 @@ export function CallView({ botId, onSpeaking, interrupt, onEnd }: {if (session.isActive && !counted.current) {counted.current = trueanalytics.track({ event: 'voice_call_started', engine: engineName.current })- store.callStarted(botId)+ store.callStarted(botId, link.current!.call)}// A cloud engine that can't start or drops mid-call hands over to on-device voice.if (phase === 'failed' && session.provider && onDeviceAvailable()) {diff --git a/apps/desktop/src/renderer/views/call/call-link.ts b/apps/desktop/src/renderer/views/call/call-link.tsindex 1e51235f..c5a60ca5 100644--- a/apps/desktop/src/renderer/views/call/call-link.ts+++ b/apps/desktop/src/renderer/views/call/call-link.ts@@ -69,7 +69,7 @@ export class CallLink {last.text += piece} else {this.endTurn()- this.lines.push({ from, text: piece, at: Date.now() })+ this.lines.push({ from, text: piece, at: Date.now(), id: crypto.randomUUID() })this.open = true}}diff --git a/apps/desktop/src/renderer/views/thread/BotConversation.tsx b/apps/desktop/src/renderer/views/thread/BotConversation.tsxindex fac0ab3c..c13f8fe2 100644--- a/apps/desktop/src/renderer/views/thread/BotConversation.tsx+++ b/apps/desktop/src/renderer/views/thread/BotConversation.tsx@@ -1,15 +1,15 @@-import { useEffect, useRef, useState } from 'react'+import { useEffect, useRef } from 'react'import { BotAvatar } from '../../components/Avatar'import { Icon } from '../../components/Icon'import { ModalHeader } from '../../components/Overlay'import { HStack, VStack } from '../../components/Stack'import { Text } from '../../components/Text'import { useStore } from '../../store/context'-import type { Entry } from '@shared/models'import { botConversation, buildBotConversation, groupSummary, verbOf, type BotConversationRow, type BotExchange } from './bot-exchange'import { AuthorLabel, Bubble, TimeSeparator } from './ChatRows'import { MarkdownText } from './Markdown'import './bot-conversation.css'+import { useFetched } from '../../lib/use-fetched'import { useTr } from '../../lib/use-language'@@ -59,29 +59,10 @@ export function BotConversationView({ botId, peerId }: { botId: string; peerId:const tr = useTr()const store = useStore()// null while the host's history loads.- const [fetched, setFetched] = useState<Entry[] | null>(null)- const [error, setError] = useState<string | null>(null)+ const { fetched, error } = useFetched(() => store.botConversation(botId, peerId), [store, botId, peerId])const scroller = useRef<HTMLDivElement>(null)const rows = buildBotConversation(botConversation(fetched ?? [], store.allEntries(botId), peerId))- useEffect(() => {- let current = true- store.botConversation(botId, peerId).then(- (entries) => {- if (current) setFetched(entries)- },- (reason: unknown) => {- console.warn('botConversation failed', reason)- if (!current) return- setFetched([])- setError(reason instanceof Error ? reason.message : String(reason))- },- )- return () => {- current = false- }- }, [store, botId, peerId])-useEffect(() => {const el = scroller.currentif (el) el.scrollTop = el.scrollHeightdiff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex d29e877f..94dd5f5e 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -283,8 +283,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRou// Rebuilt only when this chat changes: the store replaces a chat's list on every change.const entries = store.allEntries(botId)// 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 all = useMemo(() => buildChat(hidingCalls(entries)), [entries])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)@@ -324,7 +323,7 @@ const Transcript = memo(function Transcript({ botId, openTrace, onReply, openRouif (at === 0) {const anchor = list[0]?.idawait store.loadOlder(botId)- list = buildChat(hidingCalls(store.allEntries(botId), store.liveCalls))+ list = buildChat(hidingCalls(store.allEntries(botId)))at = anchor ? Math.max(0, list.findIndex((i) => i.id === anchor)) : 0}if (at > 0) setFirstShown(list[Math.max(0, at - PAGE)]!.id)diff --git a/apps/desktop/src/shared/calls.test.ts b/apps/desktop/src/shared/calls.test.tsindex 3432c508..1158e02f 100644--- a/apps/desktop/src/shared/calls.test.ts+++ b/apps/desktop/src/shared/calls.test.ts@@ -1,22 +1,23 @@import assert from 'node:assert/strict'import { test } from 'node:test'-import { callConversation, hidingCalls } from './calls.ts'+import { callConversation, hidingCalls, withCallEntries } 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", () => {+test("a call hides what it carries, while it lasts too", () => {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' }),+ entry('f1', 'agent', 6, { text: 'log.txt (3 bytes)', final: true, call: 'c', files: [{ id: 'f', name: 'log.txt', size: 3, sha256: '' }] }),+ entry('n1', 'notice', 7, { text: 'Release plan', callSeconds: 26, call: 'c' }),]- assert.deepEqual(hidingCalls(entries, new Set(['live'])).map((e) => e.id), ['u2', 'local-n', 'n1'])+ assert.deepEqual(hidingCalls(entries).map((e) => e.id), ['local-n', 'f1', 'n1'])})test("a call's conversation merges its transcript with what it carried", () => {@@ -32,3 +33,16 @@ test("a call's conversation merges its transcript with what it carried", () => {'user: 看一下 git', 'voiceToBot: check git', 'bot: Working tree clean', 'voice: Clean.',])})++test("a call's own entries fill in what the loaded chat doesn't hold", () => {+ const line = entry('n1', 'notice', 10, { text: 'Old call', callSeconds: 30, call: 'c' })+ const live = [line]+ const fetched = [+ entry('u1', 'user', 2, { text: 'from before the loaded chat', call: 'c' }),+ entry('a1', 'agent', 3, { text: 'its reply', final: true, call: 'c' }),+ ]+ assert.deepEqual(callConversation(live, line), [])+ const merged = withCallEntries(live, fetched)+ assert.deepEqual(callConversation(merged, line).map((m) => `${m.speaker}: ${m.text}`), ['user: from before the loaded chat', 'bot: its reply'])+ assert.equal(withCallEntries(merged, fetched).length, merged.length, 'each entry once')+})diff --git a/apps/desktop/src/shared/calls.ts b/apps/desktop/src/shared/calls.tsindex 26114b8d..820fd4b0 100644--- a/apps/desktop/src/shared/calls.ts+++ b/apps/desktop/src/shared/calls.ts@@ -8,6 +8,8 @@ export interface CallLine {from: 'user' | 'voice'text: stringat?: number+ /** The app's id for the line: one sent again (its first answer lost) is kept once. */+ id?: string}/** One message of a call's conversation. */@@ -16,12 +18,14 @@ export interface CallMessage {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] : [])))+/**+ * Without what voice calls carry, whichever device the call is on: it shows behind the call's line, which the host+ * writes when the call ends or its app went away. A message that failed to send stays, to be sent again, and a file or+ * an artifact the bot sent, to be opened.+ */+export function hidingCalls(entries: Entry[]): Entry[] {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!)))+ return entries.filter((e) => shown(e) || !!e.data.files?.length || !!e.data.artifact)}/** A call's conversation, oldest first: what was said (the voice's transcript) and the messages it carried. */@@ -40,3 +44,9 @@ export function callConversation(entries: Entry[], line: Entry): CallMessage[] {// 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)}++/** The chat's entries with a call's own (`callEntries`), which the chat may not hold: each entry once, the chat's copy first. */+export function withCallEntries(entries: Entry[], fetched: Entry[]): Entry[] {+ const held = new Set(entries.map((e) => e.id))+ return [...entries, ...fetched.filter((e) => !held.has(e.id))]+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 3dd457e5..038234cc 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -140,6 +140,13 @@ public extension HostClient {return res.entries}+ /// What a voice call carried, from the computer: the chat this device holds may not reach back to it.+ func callEntries(botId: String, call: String) async throws -> [Entry] {+ struct Res: Decodable { var entries: [Entry] }+ let res: Res = try await self.call("callEntries", ["botId": botId, "callId": call])+ return res.entries+ }+/// The newest 200 bot-to-bot notices between a bot's chat and a peer, oldest first.func botConversation(botId: String, peerId: String) async throws -> [Entry] {struct Res: Decodable { var entries: [Entry] }@@ -238,8 +245,9 @@ public extension HostClient {return out}- func callStarted(_ botId: String) async throws {- let _: Empty = try await call("callStarted", ["botId": botId])+ /// A call's audio is live: a lead opens it, and its opening is the call's.+ func callStarted(_ botId: String, call: String) async throws {+ let _: Empty = try await self.call("callStarted", ["botId": botId, "callId": call])}// MARK: voice calls (host/src/chat/calls)diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swiftindex 84354405..6bcd1c5b 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Calls.swift@@ -31,16 +31,22 @@ public struct CallMessage: Hashable, Sendable {}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)+ /// Without what voice calls carry, whichever device the call is on: it shows behind the call's line, which the+ /// computer writes when the call ends or its app went away. One that failed to send stays, to be sent again, and a+ /// file or an artifact the bot sent, to be opened.+ func hidingCalls() -> [Entry] {+ filter { e in+ e.kind == "notice" || e.data.call == nil || e.data.status == "failed" || e.data.files?.isEmpty == false+ || e.data.artifact != nil}}+ /// With a call's own entries (`callEntries`), which the chat may not hold: each entry once, the chat's copy first.+ func withCallEntries(_ fetched: [Entry]) -> [Entry] {+ let held = Set(map(\.id))+ return self + fetched.filter { !held.contains($0.id) }+ }+/// 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] {diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swiftindex 23918d39..c98667ca 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/EntryData.swift@@ -80,11 +80,14 @@ public struct CallLine: Codable, Hashable, Sendable {public var from: Stringpublic var text: Stringpublic var at: Int64?+ /// The app's id for the line: one sent again (its first answer lost) is kept once.+ public var id: String?- public init(from: String, text: String, at: Int64?) {+ public init(from: String, text: String, at: Int64?, id: String? = nil) {self.from = fromself.text = textself.at = at+ self.id = id}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex 2f694d0d..f2aefc28 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -1208,5 +1208,7 @@"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"+ "Opens the call": "Öffnet den Anruf",+ "Loading the call": "Anruf wird geladen",+ "Couldn't load the call.": "Der Anruf konnte nicht geladen werden."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 861e0501..e6e856ba 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -1208,5 +1208,7 @@"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"+ "Opens the call": "Abre la llamada",+ "Loading the call": "Cargando la llamada",+ "Couldn't load the call.": "No se pudo cargar la llamada."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 3efd6fb4..cfe0a52a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -1208,5 +1208,7 @@"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"+ "Opens the call": "Ouvre l'appel",+ "Loading the call": "Chargement de l'appel",+ "Couldn't load the call.": "Impossible de charger l'appel."}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex 2c0d5d92..da3b78da 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -1208,5 +1208,7 @@"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": "通話を開きます"+ "Opens the call": "通話を開きます",+ "Loading the call": "通話を読み込んでいます",+ "Couldn't load the call.": "通話を読み込めませんでした。"}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 57067e42..c46d4347 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -1208,5 +1208,7 @@"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": "통화를 엽니다"+ "Opens the call": "통화를 엽니다",+ "Loading the call": "통화를 불러오는 중",+ "Couldn't load 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 c79083dd..609fad3c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -1208,5 +1208,7 @@"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": "打开这通电话"+ "Opens the call": "打开这通电话",+ "Loading the call": "正在加载这通电话",+ "Couldn't load 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 8b0f0caa..1760456d 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -1208,5 +1208,7 @@"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": "打開這通電話"+ "Opens the call": "打開這通電話",+ "Loading the call": "正在載入這通電話",+ "Couldn't load the call.": "無法載入這通電話。"}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swiftindex 2e34b14d..bf7102ca 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallLink.swift@@ -64,7 +64,7 @@ final class CallLink {lines[last].text += piece} else {endTurn()- lines.append(CallLine(from: from, text: piece, at: Int64(Date.now.timeIntervalSince1970 * 1000)))+ lines.append(CallLine(from: from, text: piece, at: Int64(Date.now.timeIntervalSince1970 * 1000), id: UUID().uuidString))open = true}}@@ -109,7 +109,7 @@ final class CallLink {lines.removeFirst(taken.count)return taken.compactMap { line inlet text = VoiceSettings.inReadersScript(line.text.trimmingCharacters(in: .whitespacesAndNewlines))- return text.isEmpty ? nil : CallLine(from: line.from, text: text, at: line.at)+ return text.isEmpty ? nil : CallLine(from: line.from, text: text, at: line.at, id: line.id)}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swiftindex c95fcca6..50afa526 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallRows.swift@@ -33,15 +33,24 @@ struct CallLineRow: View {struct CallConversationView: View {let line: Entry@Environment(BotStore.self) private var model+ /// The call's own messages, which the chat this device holds may not reach back to; nil while they load.+ @State private var fetched: [Entry]?+ @State private var error: String?var body: some View {let entry = model.chat(line.botId).first { $0.id == line.id } ?? line- let messages = model.chat(line.botId).callConversation(entry)+ let messages = model.chat(line.botId).withCallEntries(fetched ?? []).callConversation(entry)VStack(spacing: 0) {ModalHeader(entry.data.text ?? "Voice chat")ScrollView {LazyVStack(alignment: .leading, spacing: 10) {- if messages.isEmpty {+ if let error {+ Text(L10n.tr(error)).font(.footnote).foregroundStyle(Palette.danger)+ .frame(maxWidth: .infinity).padding(.top, 24)+ } else if fetched == nil, line.data.call != nil {+ Spinner(size: 14).frame(maxWidth: .infinity).padding(.top, 24)+ .accessibilityLabel(L10n.tr("Loading the call"))+ } else if messages.isEmpty {Text(L10n.tr("Nothing was said on this call.")).font(.footnote).foregroundStyle(Palette.tertiary).frame(maxWidth: .infinity).padding(.top, 24)}@@ -53,6 +62,15 @@ struct CallConversationView: View {.defaultScrollAnchor(.bottom)}.background(Palette.background)+ .task(id: line.id) {+ guard let call = line.data.call else { return }+ do {+ fetched = try await model.callEntries(line.botId, call: call)+ } catch {+ fetched = []+ self.error = error.localizedDescription+ }+ }}@ViewBuilder private func row(_ message: CallMessage) -> some View {diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swiftindex c98b0758..9d13a725 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift@@ -45,7 +45,6 @@ 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)}@@ -64,7 +63,7 @@ struct CallView: View {if phase?.isActive == true, !reported, let session {reported = trueAnalytics.shared.capture(.voiceCallStarted(session.analyticsName))- model.callStarted(botId)+ model.callStarted(botId, call: call)}// A cloud engine that can't start or drops mid-call hands over to on-device voice.if case .failed(let message) = phase, let provider = session?.provider {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex 3ff84bd5..1cae1bf6 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -68,10 +68,10 @@ extension BotStore {}public func stop(_ botId: String) { perform(replay: true) { try await $0.stop(botId) } }- /// A call's audio is on: the lead speaks first (an older host, which has no lead, never gets this).- public func callStarted(_ botId: String) {+ /// A call's audio is on: the lead speaks first, on the call (an older host, which has no lead, never gets this).+ public func callStarted(_ botId: String, call: String) {guard bots[botId]?.lead == true else { return }- perform { try await $0.callStarted(botId) }+ perform { try await $0.callStarted(botId, call: call) }}public func newSession(_ botId: String) { perform { try await $0.newSession(botId) } }/// The bot's own agent again, off the fallback it runs on.@@ -279,6 +279,11 @@ extension BotStore {bots[group.id] = group}+ /// What a voice call carried, for its conversation. Never `upsert`ed, like `botConversation`.+ public func callEntries(_ botId: String, call: String) async throws -> [Entry] {+ try await ready().callEntries(botId: botId, call: call)+ }+/// The bot-to-bot notices between a chat and a peer. Never `upsert`ed: old notices in the/// mirror would break `loadOlder`, which pages from the oldest loaded `seq`.public func botConversation(_ botId: String, peer: String) async throws -> [Entry] {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swiftindex d44b8475..b3a07690 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Calls.swift@@ -2,11 +2,6 @@ import CodyncKitimport Foundationextension 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 {@@ -17,6 +12,5 @@ extension BotStore {} catch {lastError = error.localizedDescription}- liveCalls.remove(call)}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex 692cc595..f357626b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -118,8 +118,6 @@ 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/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex 1b45fbed..8ce7f0c3 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -324,7 +324,7 @@ extension ThreadView {/// revealed steadily as it's written.var transcript: some View {// 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))+ let items = ChatItem.build(model.chat(botId).hidingCalls())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.swiftindex 02c98a52..a084b521 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/CallTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/CallTests.swift@@ -7,16 +7,17 @@ private func entry(_ id: String, _ kind: String, at: Int64, _ json: String) throreturn Entry(id: id, seq: at, botId: "b", rev: 1, kind: kind, turn: 1, data: data, createdAt: at, updatedAt: at)}-@Test func finishedAndLiveCallsHideWhatTheyCarried() throws {+@Test func aCallsMessagesHideBehindItsLine() 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"}"#),+ try entry("f1", "agent", at: 6, #"{"text":"log.txt (3 bytes)","final":true,"call":"c","files":[{"id":"f","name":"log.txt","size":3,"sha256":""}]}"#),+ try entry("n1", "notice", at: 7, #"{"text":"Release plan","callSeconds":26,"call":"c"}"#),]- #expect(entries.hidingCalls(live: ["live"]).map(\.id) == ["u2", "local-n", "n1"])+ #expect(entries.hidingCalls().map(\.id) == ["local-n", "f1", "n1"])}@Test func aCallsConversationMergesItsTranscriptWithWhatItCarried() throws {@@ -33,3 +34,15 @@ private func entry(_ id: String, _ kind: String, at: Int64, _ json: String) throlet said = entries.callConversation(line).map { "\($0.speaker): \($0.text)" }#expect(said == ["user: 看一下 git", "voiceToBot: check git", "bot: Working tree clean", "voice: Clean."])}++@Test func aCallsOwnEntriesFillInWhatTheChatDoesNotHold() throws {+ let line = try entry("n1", "notice", at: 10, #"{"text":"Old call","callSeconds":30,"call":"c"}"#)+ let fetched = [+ try entry("u1", "user", at: 2, #"{"text":"from before the loaded chat","call":"c"}"#),+ try entry("a1", "agent", at: 3, #"{"text":"its reply","final":true,"call":"c"}"#),+ ]+ #expect([line].callConversation(line).isEmpty)+ let merged = [line].withCallEntries(fetched)+ #expect(merged.callConversation(line).map { "\($0.speaker): \($0.text)" } == ["user: from before the loaded chat", "bot: its reply"])+ #expect(merged.withCallEntries(fetched).count == merged.count)+}diff --git a/docs/features/lead-bot.md b/docs/features/lead-bot.mdindex c8a02c10..3e7987f4 100644--- a/docs/features/lead-bot.md+++ b/docs/features/lead-bot.md@@ -35,13 +35,13 @@ to be asked. Everything about it lives in the host (`host/src/chat/lead.rs`); thcancelled while the agent's plan is above 75% in any window (`usage::near_limit`, the same headroom dreamingkeeps), so it never spends the user's last usage. Test runs still run.- **It speaks first on a call.** When a call's audio is first live (the moment `voice_call_started` is counted),- the iPhone, Android and desktop apps send `callStarted {botId}` once per call (an engine switch doesn't send it+ the iPhone, Android and desktop apps send `callStarted {botId, callId}` once per call (an engine switch doesn't send itagain), only for a bot marked lead. Unless a turn is under way (working, or waiting on an approval), the host startsa turn in its chat with no message of the user's (`Cmd::Prompt`): it greets the user, or says in a sentence or twowhat deserves their attention. The reply is an ordinary message, read aloud by every engine. It is the host's turn(`TurnSource::Host`), not the user's: a turn of its own in the trace, never resumed after a host restart (the call- is over by then), no push alert, and nothing for memory or dreaming. Other bots, or a lead already at work, wait- for the user.+ is over by then), no push alert, and nothing for memory or dreaming. The reply carries the call's id, so it stays+ behind the call's line with the rest of the call. Other bots, or a lead already at work, wait for the user.## Shortcutsdiff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex bd80081b..ca03f5b2 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -7,8 +7,8 @@ The bot is the same agent on the computer; the call only changes how you talk to([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 the-apps send `callStarted {botId}` (once per call, only to a lead), and the host has a lead with no turn under way open-with a sentence or two, read aloud like any reply.+apps send `callStarted {botId, callId}` (once per call, only to a lead), and the host has a lead with no turn under+way open with a sentence or two, read aloud like any reply and part of the call (its reply carries the call's id).## On-device voice@@ -271,27 +271,34 @@ carries audio and talks to these methods:- **The user's own words:** `send_to_bot` attaches what the user said since the bot last heard from the call, wordfor word from the transcript ("[The user's own words on the call: «…»]"), so the bot sees both, and the messageis 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+- **`callLines`** `{callId, lines: [{from: user | voice, text, at, id}]}` appends the transcript as it is spoken, turnby 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+ always has the words it hands on. Lines a request didn't deliver go with the next one; each line carries the app's+ id, and the host keeps a line once, so a request whose answer was lost can go again. OpenAI writes the user'swords down after their turn: a tool call waits up to 2 s for them (`input_audio_buffer.committed` until thetranscription 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'sreplies 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.+ message stays visible, and a reply after the call ends shows). Every client leaves them out of the chat whichever+ device the call is on (`hidingCalls`): they show behind the call's line; a message that failed to send stays,+ with Resend, and so does a file or an artifact the bot sent, to be opened. A call whose app went away (killed,+ offline) still gets its line: the host keeps the open calls (`calls.open` in `kv`) and ends one nothing happened+ on for 2 hours: no lines from its app, no message or reply of it, its bot not at work (`chat::calls::sweep`). 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 itacross 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'slanguage, into the notice's `text` ("Voice chat" until then, or when there's nothing to sum up); older appsshow 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.+ it relayed and the bot's messages, in order. The chat an app holds may not reach back to an older call (the+ desktop mirror keeps the newest 200 entries), so opening the conversation fetches the call's own messages,+ `callEntries {botId, callId}` → the newest 500, and merges them with the loaded chat, each entry once; it shows+ a spinner until they arrive and the error if they can't. `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 andits relayed messages context only, and a call's spoken lines count toward the dream trigger; the call's endasks for a run soon.diff --git a/host/src/agent/bot/cmd.rs b/host/src/agent/bot/cmd.rsindex df934010..c105a3c7 100644--- a/host/src/agent/bot/cmd.rs+++ b/host/src/agent/bot/cmd.rs@@ -18,8 +18,12 @@ pub enum Cmd {BotRequest(crate::chat::team::BotRequest),/// How a request this bot sent came out: a turn of its own, with any others that arrive meanwhile.BotReply(crate::chat::team::BotReply),- /// A turn the host starts in the bot's own chat, with no message of the user's (the lead opening a call).- Prompt(String),+ /// A turn the host starts in the bot's own chat, with no message of the user's (the lead opening a call): its+ /// reply is that call's (`chat::calls`).+ Prompt {+ text: String,+ call: Option<String>,+ },/// `send_message` from the bot's `chat` MCP server: a message for the user, now.SendToUser {text: String,@@ -81,7 +85,10 @@ pub(super) enum Queued {},BotRequest(crate::chat::team::BotRequest),BotReply(crate::chat::team::BotReply),- Prompt(String),+ Prompt {+ text: String,+ call: Option<String>,+ },/// A compaction the host decided on (see `compaction`); `idle` while the user is away.Compact {idle: bool,diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex ae87bbde..202f225d 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -110,6 +110,7 @@ pub fn spawn(hub: Arc<Hub>, base: BotConfig) -> BotHandle {active_request: None,reply_hops: None,active_prompt: false,+ prompt_call: None,seg: Seg::None,tools: HashMap::new(),plan_entry: None,@@ -273,6 +274,8 @@ struct Actor {reply_hops: Option<u8>,/// The running turn is one the host started, with no message of the user's (`Cmd::Prompt`).active_prompt: bool,+ /// The call the next host-started turn opens (`Cmd::Prompt`), whose replies are that call's.+ prompt_call: Option<String>,seg: Seg,tools: HashMap<String, String>,plan_entry: Option<String>,diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rsindex d8c71026..b0ec5a91 100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@ -33,7 +33,7 @@ impl Actor {}Cmd::BotRequest(request) => self.enqueue(Queued::BotRequest(request), done_tx).await,Cmd::BotReply(reply) => self.enqueue(Queued::BotReply(reply), done_tx).await,- Cmd::Prompt(prompt) => self.enqueue(Queued::Prompt(prompt), done_tx).await,+ Cmd::Prompt { text, call } => self.enqueue(Queued::Prompt { text, call }, done_tx).await,Cmd::SendToUser { text, reply } => {let _ = reply.send(self.send_to_user(text));}@@ -236,12 +236,13 @@ impl Actor {}continue;}- Some(Queued::Prompt(_)) => {- let Some(Queued::Prompt(prompt)) = self.queue.pop_front() else {+ Some(Queued::Prompt { .. }) => {+ let Some(Queued::Prompt { text, call }) = self.queue.pop_front() else {unreachable!("front is a prompt")};self.active_prompt = true;- if let Err(e) = self.start_turn(main.clone(), &[], &prompt, false, done_tx).await {+ self.prompt_call = call;+ if let Err(e) = self.start_turn(main.clone(), &[], &text, false, done_tx).await {self.start_error(e, done_tx).await;}continue;diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex b56aeee9..3b9cb4bb 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -106,7 +106,8 @@ impl Actor {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);+ let opens = self.prompt_call.take().filter(|call| crate::chat::calls::is_live(&self.hub.store, call));+ self.turn_call = crate::chat::calls::of_turn(&self.hub.store, answered).or(opens);self.turn_memory_revision.clear();self.announce = None;self.stop_requested = false;diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex d54c00b9..2a311ff2 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -168,12 +168,14 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr// 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();+ crate::chat::calls::heard(&hub.store, bot, call)?;}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")?)?;+ let call = b["callId"].as_str().map(crate::chat::calls::checked).transpose()?;+ crate::chat::lead::call_started(hub, str_arg(&b, "botId")?, call)?;json!({})}// A finished voice call from an app older than `endCall`, as a line in the chat ("Voice chat · 0:16").@@ -201,6 +203,12 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr)?;json!({})}+ // What a call carried, for its conversation: the chat an app holds may not reach back that far.+ "callEntries" => {+ let bot = str_arg(&b, "botId")?;+ let call = crate::chat::calls::checked(str_arg(&b, "callId")?)?;+ json!({"entries": hub.store.call_entries(bot, call, crate::chat::calls::CALL_ENTRIES)?})+ }"endCall" => {let call = crate::chat::calls::checked(str_arg(&b, "callId")?)?;let seconds = b["seconds"].as_u64().unwrap_or(0);diff --git a/host/src/background.rs b/host/src/background.rsindex a79c8270..45e28122 100644--- a/host/src/background.rs+++ b/host/src/background.rs@@ -16,6 +16,7 @@ pub fn start(hub: &Arc<Hub>) {tokio::spawn(market::refresh_first_page());tokio::spawn(market::automatic_loop(hub.clone()));tokio::spawn(voice::refresh_loop(hub.clone()));+ tokio::spawn(crate::chat::calls::sweep_loop(hub.clone()));tokio::spawn({let hub = hub.clone();async move { market::agent_sign_in::refresh(&hub).await }diff --git a/host/src/chat/calls/mod.rs b/host/src/chat/calls/mod.rsindex ed73f179..484b6ba6 100644--- a/host/src/chat/calls/mod.rs+++ b/host/src/chat/calls/mod.rs@@ -7,8 +7,11 @@pub mod context;mod project;+mod sweep;pub mod tools;+pub use sweep::sweep_loop;+use crate::LockExt;use crate::agent::bot::Cmd;use crate::hub::Hub;@@ -17,6 +20,7 @@ use anyhow::{Result, anyhow, bail};use serde::{Deserialize, Serialize};use serde_json::{Value, json};use std::sync::{Arc, Mutex};+use sweep::mark_open;const MAX_LINES: usize = 500;const MAX_LINE_CHARS: usize = 2_000;@@ -25,6 +29,8 @@ 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";+/// The most of a call's messages the host reads or hands an app (`callEntries`), newest first.+pub const CALL_ENTRIES: i64 = 500;/// One read-modify-write of a call's state at a time (lines and hand-offs arrive together).static STATE: Mutex<()> = Mutex::new(());@@ -37,13 +43,16 @@ pub enum Speaker {Voice,}-/// One line of what was said on a call, with when (ms, the app's clock).+/// One line of what was said on a call, with when (ms, the app's clock) and the app's id for it, so a line sent+/// again (its first answer was lost) is kept once.#[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>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub id: Option<String>,}/// A call in progress, kept in `kv` so a host restart or a dropped client loses nothing: its bot, the transcript@@ -54,6 +63,16 @@ struct CallState {lines: Vec<CallLine>,handoff: usize,started: i64,+ /// When the call last heard from its app.+ #[serde(default)]+ last: i64,+}++impl CallState {+ fn new(bot: &str) -> Self {+ let now = now_ms();+ Self { bot: bot.to_owned(), lines: Vec::new(), handoff: 0, started: now, last: now }+ }}/// What carries a call's voice: a realtime provider, speech to text and back, or the device's own speech.@@ -87,11 +106,40 @@ fn save(store: &Store, call: &str, s: &CallState) -> Result<()> {store.kv_set(&state_key(call), &serde_json::to_string(s)?)}+/// A call's state for an update, made (and kept among the open calls) when a message of it arrives first (its+/// `startCall` lost); `None` once it ended.+fn begun(store: &Store, bot: &str, call: &str) -> Result<Option<CallState>> {+ if store.kv_get(&ended_key(call)).is_some() {+ return Ok(None);+ }+ if let Some(mut s) = state(store, call) {+ s.last = now_ms();+ return Ok(Some(s));+ }+ mark_open(store, call, true)?;+ Ok(Some(CallState::new(bot)))+}++/// A message said on call `call` reached `bot`'s chat (`send`): the call is alive, and the host knows of it even+/// if its `startCall` never came.+pub fn heard(store: &Store, bot: &str, call: &str) -> Result<()> {+ let _one = STATE.locked();+ match begun(store, bot, call)? {+ Some(s) if s.bot == bot => save(store, call, &s),+ _ => Ok(()),+ }+}+/// 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)}+/// Whether `call` is in progress (started, not ended).+pub fn is_live(store: &Store, call: &str) -> bool {+ store.kv_get(&ended_key(call)).is_none() && state(store, call).is_some()+}+/// 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> {@@ -121,15 +169,22 @@ fn transcript(raw: &Value) -> Vec<CallLine> {from: line.from,text: crate::agent::acp::truncate(text, MAX_LINE_CHARS),at: line.at,+ id: line.id.filter(|id| checked(id).is_ok()),})}).take(MAX_LINES).collect()}-/// Adds what was just said to the call, keeping its last [`MAX_LINES`].+/// Adds what was just said to the call, keeping its last [`MAX_LINES`]. A line it already has (an app sending it+/// again) is skipped.fn append(s: &mut CallState, lines: Vec<CallLine>) {- s.lines.extend(lines);+ for line in lines {+ if line.id.is_some() && s.lines.iter().any(|l| l.id == line.id) {+ continue;+ }+ s.lines.push(line);+ }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.@@ -145,16 +200,10 @@ pub async fn start(hub: &Arc<Hub>, b: &Value) -> Result<Value> {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) {+ match begun(&hub.store, bot, 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)?;- }+ Some(s) => save(&hub.store, call, &s)?,+ None => bail!("that call has ended"),}}let provider = b["provider"].as_str().map(crate::voice::Provider::parse).transpose()?;@@ -179,6 +228,7 @@ pub fn add_lines(store: &Store, call: &str, raw: &Value) -> Result<()> {}let _one = STATE.locked();let mut s = state(store, call).ok_or_else(|| anyhow!("no such call"))?;+ s.last = now_ms();append(&mut s, lines);save(store, call, &s)}@@ -187,6 +237,7 @@ pub fn add_lines(store: &Store, call: &str, raw: &Value) -> Result<()> {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"))?;+ s.last = now_ms();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(" ");@@ -209,6 +260,7 @@ pub fn end(hub: &Arc<Hub>, bot: &str, call: &str, seconds: u64, raw: &Value) ->}hub.store.kv_set(&ended_key(call), "1")?;hub.store.kv_delete(&state_key(call))?;+ mark_open(&hub.store, call, false)?;s};let bot = s.as_ref().map_or(bot, |s| s.bot.as_str()).to_owned();@@ -249,7 +301,7 @@ fn conversation(store: &Store, bot: &str, line: &Entry) -> Vec<(String, String)>(l.at.unwrap_or(line.created_at), who.to_owned(), l.text)}).collect();- for e in store.call_entries(bot, call).unwrap_or_default() {+ for e in store.call_entries(bot, call, CALL_ENTRIES).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()));}@@ -377,7 +429,7 @@ mod tests {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();+ let relayed = hub.store.call_entries(&id, "c1", CALL_ENTRIES).unwrap();assert_eq!(relayed.len(), 1);assert_eq!(relayed[0].data["from"], "voice");let text = relayed[0].data["text"].as_str().unwrap();@@ -395,6 +447,19 @@ mod tests {assert!(tools::call(&hub, "c1", "bot_status", &json!({}), &Value::Null).await["error"].is_string());}+ #[test]+ fn a_line_sent_again_is_kept_once() {+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();+ heard(&store, "b", "c1").unwrap();+ let batch = json!([{"from": "user", "text": "hi", "at": 1, "id": "l1"}, {"from": "voice", "text": "Hello.", "id": "l2"}]);+ add_lines(&store, "c1", &batch).unwrap();+ // The answer to the first send was lost, so the app sends the batch again, and one more line.+ add_lines(&store, "c1", &batch).unwrap();+ add_lines(&store, "c1", &json!([{"from": "user", "text": "hi", "id": "l3"}])).unwrap();+ let lines: Vec<String> = state(&store, "c1").unwrap().lines.iter().map(|l| l.text.clone()).collect();+ assert_eq!(lines, ["hi", "Hello.", "hi"], "repeats skipped, a new line with the same words kept");+ }+#[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();diff --git a/host/src/chat/calls/sweep.rs b/host/src/chat/calls/sweep.rsnew file mode 100644index 00000000..d7c1bde4--- /dev/null+++ b/host/src/chat/calls/sweep.rs@@ -0,0 +1,129 @@+//! Calls whose app went away (a crash, a phone switched off): the host keeps the calls in progress and ends one+//! nothing happened on for a long while, writing its line, so what it carried never stays hidden without one.++use super::{STATE, end, state};+use crate::LockExt;+use crate::hub::{BotStatus, Hub};+use crate::store::{Store, now_ms};+use anyhow::Result;+use serde_json::Value;+use std::sync::Arc;++/// A call nothing happened on this long (its app, the user, its bot) has lost its app. Generous: a live call ended by+/// mistake loses what is said after.+const ABANDONED_MS: i64 = 2 * 60 * 60 * 1000;+/// How often the host looks for abandoned calls.+const SWEEP_EVERY: std::time::Duration = std::time::Duration::from_secs(5 * 60);+/// The calls in progress (`kv`): what the sweep looks through.+const OPEN_KEY: &str = "calls.open";++pub(super) fn open_calls(store: &Store) -> Vec<String> {+ store.kv_get(OPEN_KEY).and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()+}++/// Keeps `call` in the open calls (`open`) or takes it out. Under [`STATE`], like every change to a call.+pub(super) fn mark_open(store: &Store, call: &str, open: bool) -> Result<()> {+ let mut calls = open_calls(store);+ calls.retain(|c| c != call);+ if open {+ calls.push(call.to_owned());+ }+ store.kv_set(OPEN_KEY, &serde_json::to_string(&calls)?)+}++/// Ends abandoned calls (see [`ABANDONED_MS`]), at start-up and every [`SWEEP_EVERY`] after.+pub async fn sweep_loop(hub: Arc<Hub>) {+ loop {+ sweep(&hub, now_ms());+ tokio::time::sleep(SWEEP_EVERY).await;+ }+}++fn sweep(hub: &Arc<Hub>, now: i64) {+ for call in open_calls(&hub.store) {+ let Some(s) = state(&hub.store, &call) else {+ let _one = STATE.locked();+ if state(&hub.store, &call).is_none()+ && let Err(e) = mark_open(&hub.store, &call, false)+ {+ tracing::warn!(call, error = format!("{e:#}"), "couldn't forget a call with no state");+ }+ continue;+ };+ let last = s.last.max(s.started).max(newest_entry(&hub.store, &s.bot, &call));+ if now - last < ABANDONED_MS || busy(hub, &s.bot) {+ continue;+ }+ let seconds = u64::try_from((last - s.started) / 1000).unwrap_or(0);+ tracing::info!(call, bot = s.bot, "ending a call its app abandoned");+ if let Err(e) = end(hub, &s.bot, &call, seconds, &Value::Null) {+ tracing::warn!(call, error = format!("{e:#}"), "couldn't end an abandoned call");+ }+ }+}++/// When the call's newest message or reply was written (0 for none): the bot answering it is work on the call.+fn newest_entry(store: &Store, bot: &str, call: &str) -> i64 {+ store.call_entries(bot, call, 1).ok().and_then(|e| e.first().map(|e| e.updated_at)).unwrap_or(0)+}++/// Whether the call's bot is at work (a turn under way, or waiting on an approval; a group: a member in it): its+/// reply is still to come on the call.+fn busy(hub: &Hub, bot: &str) -> bool {+ let status = match hub.store.bot(bot) {+ Ok(Some(row)) if row.config.is_group() => hub.group_runtime(&row.config).status,+ _ => hub.runtime(bot).status,+ };+ matches!(status, BotStatus::Working | BotStatus::NeedsInput)+}++#[cfg(test)]+mod tests {+ use super::super::{context, heard, is_live, save};+ use super::*;+ use crate::store::{BotConfig, EntryKind, Lane};+ use serde_json::json;++ fn hub_with_bot() -> (Arc<Hub>, String) {+ let hub = context::tests::hub();+ let id = uuid::Uuid::new_v4().to_string();+ let cfg = BotConfig { backend: "none".into(), ..context::tests::bot(&id, "Mika", "/tmp") };+ hub.store.save_bot(&cfg).unwrap();+ (hub, id)+ }++ #[tokio::test]+ async fn an_abandoned_call_gets_its_line() {+ let (hub, id) = hub_with_bot();+ // A message said on a call whose app then went away (its startCall never reached the host).+ heard(&hub.store, &id, "gone").unwrap();+ assert!(is_live(&hub.store, "gone"));+ sweep(&hub, now_ms());+ assert!(is_live(&hub.store, "gone"), "a call heard from just now stays open");+ sweep(&hub, now_ms() + ABANDONED_MS + 1);+ assert!(!is_live(&hub.store, "gone"), "a quiet call is ended");+ let lines = hub.store.history(&id, i64::MAX, 10).unwrap();+ assert!(lines.iter().any(|e| e.data["call"] == "gone" && e.data["callSeconds"].is_number()), "with its line");+ assert_eq!(open_calls(&hub.store), Vec::<String>::new());+ }++ #[tokio::test]+ async fn a_call_its_bot_works_on_stays_open() {+ let (hub, id) = hub_with_bot();+ heard(&hub.store, &id, "long").unwrap();+ // The app last spoke long ago: the user asked for a long job and stayed quiet.+ let mut s = state(&hub.store, "long").unwrap();+ (s.started, s.last) = (0, 0);+ save(&hub.store, "long", &s).unwrap();+ hub.set_runtime(&id, |r| r.status = BotStatus::Working);+ sweep(&hub, now_ms());+ assert!(is_live(&hub.store, "long"), "its bot is still on the job");+ hub.set_runtime(&id, |r| r.status = BotStatus::Idle);+ let reply = json!({"text": "Done.", "final": true, "call": "long"});+ hub.store.insert_entry(&Lane::main(&id), EntryKind::Agent, 1, &reply).unwrap();+ sweep(&hub, now_ms());+ assert!(is_live(&hub.store, "long"), "its reply just came");+ sweep(&hub, now_ms() + ABANDONED_MS + 1);+ assert!(!is_live(&hub.store, "long"), "then quiet for good");+ }+}diff --git a/host/src/chat/lead.rs b/host/src/chat/lead.rsindex 8e8beb46..7123b0c8 100644--- a/host/src/chat/lead.rs+++ b/host/src/chat/lead.rs@@ -64,10 +64,11 @@ pub fn may_delete(store: &Store, bot: &str) -> Result<()> {}/// A call with `bot` is on: the lead speaks first, unless a turn is under way (the reply on its way comes first).-pub fn call_started(hub: &Hub, bot: &str) -> Result<()> {+pub fn call_started(hub: &Hub, bot: &str, call: Option<&str>) -> Result<()> {let row = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;if row.config.lead && !matches!(hub.runtime(bot).status, BotStatus::Working | BotStatus::NeedsInput) {- hub.send_cmd(bot, Cmd::Prompt(OPENING.to_owned()))?;+ // The opening is the call's: said on it, kept in its conversation, not in the chat.+ hub.send_cmd(bot, Cmd::Prompt { text: OPENING.to_owned(), call: call.map(str::to_owned) })?;}Ok(())}diff --git a/host/src/chat/lead/tests.rs b/host/src/chat/lead/tests.rsindex 2c3e023f..9afff0a2 100644--- a/host/src/chat/lead/tests.rs+++ b/host/src/chat/lead/tests.rs@@ -130,18 +130,20 @@ async fn the_lead_speaks_first_on_a_call() {let f = Fixture::new();let lead = make(&f.hub, f.cfg(NAME)).unwrap();let other = f.hub.create_bot(f.cfg("Other")).unwrap()["id"].as_str().unwrap().to_owned();- call_started(&f.hub, &other).unwrap();- call_started(&f.hub, &lead).unwrap();+ call_started(&f.hub, &other, None).unwrap();+ crate::chat::calls::heard(&f.hub.store, &lead, "c1").unwrap();+ call_started(&f.hub, &lead, Some("c1")).unwrap();until(|| f.hub.runtime(&lead).status == BotStatus::Idle && !f.agent_texts(&lead).is_empty(), "the lead opens").await;assert_eq!(f.agent_texts(&lead), ["opened"]);assert!(f.agent_texts(&other).is_empty(), "other bots wait for the user");let opening = f.hub.store.history(&lead, i64::MAX, 50).unwrap().into_iter().find(|e| e.kind == "agent").unwrap();assert_eq!(opening.turn, 1, "a turn of its own");+ assert_eq!(opening.data["call"], "c1", "the opening is the call's, kept in its conversation");// A lead whose last turn failed still opens the next call.f.hub.set_runtime(&lead, |r| r.status = BotStatus::Error);- call_started(&f.hub, &lead).unwrap();+ call_started(&f.hub, &lead, None).unwrap();until(|| f.agent_texts(&lead).len() == 2, "the lead opens again").await;f.shutdown().await;}diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex 99208e21..f07734e3 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -116,14 +116,18 @@ impl Store {}/// 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>> {+ /// The newest `limit` of them.+ pub fn call_entries(&self, bot_id: &str, call: &str, 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 json_extract(data, '$.call') = ?2 AND(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))- ORDER BY seq"+ ORDER BY seq DESC LIMIT ?3"))?;- Ok(st.query_map(params![bot_id, call], row_entry)?.collect::<rusqlite::Result<_>>()?)+ let mut rows: Vec<Entry> =+ st.query_map(params![bot_id, call, limit], row_entry)?.collect::<rusqlite::Result<_>>()?;+ rows.reverse();+ Ok(rows)}pub fn max_turn(&self, bot_id: &str) -> i64 {diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex ef47f9d2..e53c6469 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -104,6 +104,8 @@ pub struct App {pub pick: Option<String>,/// Chat lines showing their full text: a handoff (`o` on the picked line).pub unfolded: HashSet<String>,+ /// Voice calls' own messages, by call id (`callEntries`): the chat loaded here may not reach back to them.+ pub call_entries: HashMap<String, Vec<Entry>>,pub market: (Vec<Toggle>, Vec<Toggle>),/// Installed connectors and skills as the host lists them.pub plugins: (Vec<Value>, Vec<Value>),@@ -176,6 +178,7 @@ impl App {reply: None,pick: None,unfolded: HashSet::new(),+ call_entries: HashMap::new(),market: (vec![], vec![]),plugins: (vec![], vec![]),models: HashMap::new(),@@ -233,9 +236,10 @@ 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)));+ // What a voice call carries shows behind its line (`o`), on whichever device the call is: the host writes the+ // line when the call ends, or when its app went away. A file or an artifact the bot sent stays, to be opened.+ let opens = |e: &Entry| e.artifact().is_some() || e.data["files"].as_array().is_some_and(|f| !f.is_empty());+ v.retain(|e| e.kind == Kind::Notice || e.call().is_none() || opens(e));// 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/navigate.rs b/host/src/tui/app/navigate.rsindex c85963c5..6d8f9e9c 100644--- a/host/src/tui/app/navigate.rs+++ b/host/src/tui/app/navigate.rs@@ -201,6 +201,12 @@ impl App {if let Some(e) = picked&& !self.unfolded.remove(&e.id){+ // A call's own messages, which the loaded chat may not reach back to.+ if let Some(call) =+ e.call().filter(|c| e.kind == super::Kind::Notice && !self.call_entries.contains_key(*c))+ {+ self.fetch_call(&id, call);+ }self.unfolded.insert(e.id);}}diff --git a/host/src/tui/app/tests.rs b/host/src/tui/app/tests.rsindex 4549917e..9feacd52 100644--- a/host/src/tui/app/tests.rs+++ b/host/src/tui/app/tests.rs@@ -41,13 +41,14 @@ async fn r_on_a_picked_message_replies_to_it() {}#[tokio::test]-async fn a_finished_calls_messages_hide_behind_its_line() {+async fn a_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"})),+ (4, "agent", json!({"text": "log.txt (3 bytes)", "final": true, "files": [{"name": "log.txt"}], "call": "c"})),+ (5, "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});@@ -55,6 +56,6 @@ async fn a_finished_calls_messages_hide_behind_its_line() {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_eq!(shown, ["e4", "e5"], "a call's messages hide, also while it lasts (on another device); a file stays");assert!(app.lane("b").last().is_some_and(|e| e.unfolds()), "the call's line opens its conversation");}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 980ab121..2f8d7cac 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -54,6 +54,8 @@ pub enum Reply {bot: String,peer: String,},+ /// A voice call's own messages, by call id.+ CallEntries(String),Registry {more: bool,},@@ -247,6 +249,11 @@ impl App {self.call(method, body, After::Sheet(r));}+ /// Loads what voice call `call` in `bot`'s chat carried, for its unfolded conversation.+ pub(in crate::tui) fn fetch_call(&self, bot: &str, call: &str) {+ self.sheet("callEntries", json!({"botId": bot, "callId": call}), Reply::CallEntries(call.to_owned()));+ }+// ---------- a message's actions ----------pub(super) fn react(&mut self, entry: &str, i: usize) {diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rsindex 83c0e90b..ba81caf6 100644--- a/host/src/tui/manage/replies.rs+++ b/host/src/tui/manage/replies.rs@@ -56,9 +56,11 @@ impl App {}}}+ Reply::CallEntries(call) => {+ self.call_entries.insert(call, entries_of(&v));+ }Reply::BotChat { bot, peer } => {- let entries: Vec<Entry> =- v["entries"].as_array().into_iter().flatten().filter_map(Entry::parse).map(|(_, e)| e).collect();+ let entries = entries_of(&v);for o in &mut self.overlays {if let Overlay::BotChat(c) = o&& c.bot == bot@@ -230,6 +232,18 @@ impl App {m.error = Some(e);}}+ Reply::CallEntries(call) => {+ // The call's line folds again with nothing kept, so the next `o` asks again.+ let lines: Vec<String> = self+ .entries+ .values()+ .flat_map(|m| m.values())+ .filter(|l| l.unfolds() && l.call() == Some(call.as_str()))+ .map(|l| l.id.clone())+ .collect();+ self.unfolded.retain(|id| !lines.contains(id));+ self.flash(&e);+ }Reply::BotChat { bot, peer } => {for o in &mut self.overlays {if let Overlay::BotChat(c) = o@@ -327,3 +341,8 @@ impl App {list}}++/// The entries in a host reply (`callEntries`, `botConversation`).+fn entries_of(v: &Value) -> Vec<Entry> {+ v["entries"].as_array().into_iter().flatten().filter_map(Entry::parse).map(|(_, e)| e).collect()+}diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex 6c824309..aeab2aa0 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -2,7 +2,7 @@use ratatui::style::{Modifier, Style};use ratatui::text::{Line, Span};-use std::collections::{BTreeSet, HashMap};+use std::collections::{BTreeMap, BTreeSet, HashMap};use super::super::app::{App, Bot, Click, Entry, Exchange, Item, Kind, Outcome, Status, group};use super::super::md::{self, truncate, width as w};@@ -328,8 +328,15 @@ fn call_lines(app: &App, b: &Bot, line: &Entry) -> Vec<String> {(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 fetched = app.call_entries.get(call);+ if fetched.is_none() {+ said.push((i64::MAX, "loading the call…".to_owned()));+ }+ // What the host sent of the call (`callEntries`) and the chat loaded here, each entry once (the chat's copy).+ let held = app.entries.get(&b.id).into_iter().flat_map(|m| m.values());+ let carried: BTreeMap<i64, &Entry> =+ fetched.into_iter().flatten().chain(held).filter(|e| e.call() == Some(call)).map(|e| (e.seq, e)).collect();+ for e in carried.into_values().filter(|e| 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",diff --git a/host/src/tui/view/transcript/tests.rs b/host/src/tui/view/transcript/tests.rsindex 8f8945db..6da75da4 100644--- a/host/src/tui/view/transcript/tests.rs+++ b/host/src/tui/view/transcript/tests.rs@@ -160,3 +160,33 @@ fn a_reply_shows_the_message_it_answers() {assert_eq!(text[1], " ↳ “Plan”", "{text:?}");assert!(text[2].contains("why?"));}++#[tokio::test]+async fn a_calls_conversation_takes_what_the_host_sent_beyond_the_loaded_chat() {+ use crate::tui::app::Msg;+ use serde_json::json;+ let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(crate::tui::net::Client::new("http://127.0.0.1:1", Some("fixture")), tx, String::new());+ app.on_msg(Msg::Event(+ json!({"type":"bot", "bot":{"id":"b", "name":"Mika", "cwd":"/w", "backend":"custom", "status":"idle"}}),+ ));+ app.on_msg(Msg::Event(+ json!({"type":"entry", "entry":{"id":"line", "botId":"b", "seq":9, "kind":"notice", "turn":1,+ "createdAt": 9, "data":{"text":"Old call", "callSeconds":30, "call":"c"}}}),+ ));+ let line = app.lane("b").into_iter().find(|e| e.id == "line").cloned().unwrap();+ let bot = app.bots["b"].clone();+ assert_eq!(call_lines(&app, &bot, &line), ["loading the call…"]);+ // Older than anything loaded here.+ let parse = |v: serde_json::Value| Entry::parse(&v).unwrap().1;+ app.call_entries.insert(+ "c".into(),+ vec![+ parse(json!({"id":"u", "botId":"b", "seq":2, "kind":"user", "turn":1, "createdAt":2,+ "data":{"text":"check git", "call":"c", "from":"voice"}})),+ parse(json!({"id":"a", "botId":"b", "seq":3, "kind":"agent", "turn":1, "createdAt":3,+ "data":{"text":"Clean.", "final":true, "call":"c"}})),+ ],+ );+ assert_eq!(call_lines(&app, &bot, &line), ["voice → bot: check git", "Mika: Clean."]);+}diff --git a/host/tests/calls_e2e.rs b/host/tests/calls_e2e.rsindex c73cac16..860540bc 100644--- a/host/tests/calls_e2e.rs+++ b/host/tests/calls_e2e.rs@@ -82,6 +82,16 @@ async fn replies_are_the_calls_while_it_lasts() {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");++ // Its conversation, whatever part of the chat an app holds: the call's messages and replies only.+ let carried = host.call("callEntries", json!({"botId": bot, "callId": "c1"})).await["entries"].clone();+ let kinds: Vec<(&str, &str)> = carried+ .as_array()+ .unwrap()+ .iter()+ .map(|e| (e["kind"].as_str().unwrap(), e["data"]["call"].as_str().unwrap()))+ .collect();+ assert_eq!(kinds, [("user", "c1"), ("user", "c1"), ("agent", "c1"), ("user", "c1")], "{carried}");}#[tokio::test]diff --git a/web/content/docs/voice.mdx b/web/content/docs/voice.mdxindex 131bbf03..833e1cc1 100644--- a/web/content/docs/voice.mdx+++ b/web/content/docs/voice.mdx@@ -20,7 +20,7 @@ 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.-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.+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. Your other devices keep the call out of the chat too. If the app closes before the call ends (or loses its connection), the line appears once the call has been quiet for 2 hours.The bot remembers what matters from the call like from any conversation: its memory picks up what you said, not the voice's wording.