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(apps): calls keep their audio and Live Activity under CallKit
leepokai1ecd83535173
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.ktindex 460a10c3..88877909 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/VoiceService.kt@@ -12,7 +12,8 @@ import androidx.core.app.NotificationCompatimport androidx.core.content.ContextCompatimport com.codync.android.core.*import kotlinx.coroutines.*-import kotlinx.coroutines.flow.*+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.flow.combine/** The call the UI shows; `notice` is the line under the bar, e.g. why it fell back to on-device voice. */data class VoiceCallViewState(val id: String, val botId: String, val state: VoiceState = VoiceState(), val notice: String? = null)@@ -90,13 +91,9 @@ class VoiceService : Service() {receivers = trueval call = request.store.attachVoice(request.id, request.botId) ?: throw IllegalStateException("The active account changed")session = call- // At most one notification update a second: progress lines can come quickly.- scope.launch { combine(call.state, call.progress, ::Pair).conflate().collect { (state, progress) ->+ scope.launch { combine(call.state, call.progress, ::Pair).collectLatest { (state, progress) ->if (state.phase in listOf(VoicePhase.Failed, VoicePhase.Ended)) end(state.error)- else {- getSystemService(NotificationManager::class.java).notify(NOTIFICATION, notification(state, progress))- delay(1_000)- }+ else getSystemService(NotificationManager::class.java).notify(NOTIFICATION, notification(state, progress))} }} catch (_: Exception) { end("Couldn't start voice chat. Check microphone access and Android's audio settings.") }} else if (id == callId) {diff --git a/apps/ios/App/Push.swift b/apps/ios/App/Push.swiftindex 0043ec2c..ca96fd66 100644--- a/apps/ios/App/Push.swift+++ b/apps/ios/App/Push.swift@@ -204,38 +204,49 @@ final class LiveActivities {}private nonisolated static func find(_ ref: BotReference) -> Activity<BotActivityAttributes>? {- Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == ref.botId && $0.attributes.computerId == ref.computerId }+ BotActivityAttributes.shown(botId: ref.botId, computerId: ref.computerId)}/// Follows a message from this phone: the activity starts as it leaves (Sending), waits with/// it in the relay mailbox while the computer is offline, then follows the bot's own status.+ /// On a call with the bot, the activity stays up for the call and shows it.func sent(_ ref: BotReference, bot: Bot, progress: SendProgress, store: BotStore) {+ let onCall = CallActivity.isLive(botId: ref.botId)let status: Stringswitch progress {case .sending: status = "sending"case .queued: status = "queued"case .delivered: status = bot.needsInput ? "needsInput" : "working"case .failed:- let state = BotActivityAttributes.ContentState(status: "error", activity: "Couldn't send", startedAt: nil)- Task.detached { await Self.apply(ref, state: state, end: true) }+ let state = CallActivity.withCall(.init(status: "error", activity: "Couldn't send", startedAt: nil), botId: ref.botId)+ Task.detached { await Self.apply(ref, state: state, end: !onCall) }+ return+ case .cancelled where onCall:+ let state = CallActivity.withCall(.init(status: "idle", activity: "", startedAt: nil), botId: ref.botId)+ Task.detached { await Self.apply(ref, state: state, end: false) }returncase .cancelled:Task.detached { await Self.find(ref)?.end(nil, dismissalPolicy: .immediate) }return}- let state = BotActivityAttributes.ContentState(status: status, activity: "", startedAt: progress == .delivered ? .now : nil)+ let state = CallActivity.withCall(.init(status: status, activity: "", startedAt: progress == .delivered ? .now : nil),+ botId: ref.botId)// A mailbox message may wait hours for its computer: that isn't a delayed update.let staleDate: Date? = progress == .queued ? nil : .now + 15 * 60- if Self.find(ref) != nil {- let onCall = CallActivity.isLive(botId: ref.botId)+ if let current = Self.find(ref) {+ guard CallActivity.started(current) else {+ Task.detached { await Self.find(ref)?.update(.init(state: state, staleDate: staleDate)) }+ return+ }+ // The call's own activity can't take the computer's updates: the task gets one that can, in its place.+ let id = current.idTask.detached {- guard let activity = Self.find(ref) else { return }- await activity.update(.init(state: state.keepingCall(of: activity, onCall: onCall), staleDate: staleDate))+ for activity in Activity<BotActivityAttributes>.activities where activity.id == id {+ await activity.end(nil, dismissalPolicy: .immediate)+ }}- return}- guard UserDefaults.standard.object(forKey: "liveActivitiesEnabled") as? Bool ?? true,- ActivityAuthorizationInfo().areActivitiesEnabled else { return }+ guard BotActivityAttributes.mayStart else { return }let attributes = BotActivityAttributes(bot: bot, computerId: ref.computerId, link: store.storage.botURL(ref))do {let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: staleDate), pushType: .token)@@ -248,7 +259,7 @@ final class LiveActivities {/// Reattach token observers after a relaunch or connection replacement.func resume(with store: BotStore) {- guard UserDefaults.standard.object(forKey: "liveActivitiesEnabled") as? Bool ?? true else { return }+ guard BotActivityAttributes.isOn else { return }endLeftoverCalls()guard let client = store.client else { return }for activity in Activity<BotActivityAttributes>.activities@@ -257,22 +268,15 @@ final class LiveActivities {}}- /// A call the app was closed in the middle of leaves its fields on the activity: they go, and an activity that- /// only showed the call ends.+ /// A call the app was closed in the middle of leaves its fields on the activity: they go, and an activity with+ /// nothing else to show ends.private func endLeftoverCalls() {let over = Activity<BotActivityAttributes>.activities.filter { $0.content.state.call != nil && !CallActivity.isLive(botId: $0.attributes.botId) }.map(\.id)guard !over.isEmpty else { return }Task.detached {for activity in Activity<BotActivityAttributes>.activities where over.contains(activity.id) {- var state = activity.content.state- state.call = nil- state.callStartedAt = nil- if ["idle", "completed"].contains(state.status) {- await activity.end(nil, dismissalPolicy: .immediate)- } else {- await activity.update(.init(state: state, staleDate: activity.content.staleDate))- }+ await CallActivity.callEnded(on: activity, dismissNow: true)}}}@@ -313,15 +317,15 @@ final class LiveActivities {// Until the computer starts on the message, an idle bot just hasn't begun yet.let local = ["sending", "queued"].contains(current.content.state.status)guard !local || bot.isWorking else { return }- let state = BotActivityAttributes.ContentState(+ let state = CallActivity.withCall(.init(status: bot.status,// ACP activity is already visible in the app. Show it in the local Live Activity// while this phone is connected; APNs payloads continue to contain no free text.activity: bot.activity,startedAt: bot.startedAt.map(Date.init(milliseconds:))- ).keepingCall(of: current, onCall: CallActivity.isLive(botId: ref.botId))+ ), botId: ref.botId)// A call with the bot keeps its activity up after the task.- let working = bot.isWorking || state.call != nil+ let working = bot.isWorking || CallActivity.isLive(botId: ref.botId)Task.detached { await Self.apply(ref, state: state, end: !working) }}@@ -334,15 +338,3 @@ final class LiveActivities {}}}--private extension BotActivityAttributes.ContentState {- /// The call this phone is on with the bot stays on the activity (the app sets it, the computer never does); one- /// left by a call that's over (the app was closed mid-call) goes.- func keepingCall(of activity: Activity<BotActivityAttributes>, onCall: Bool) -> Self {- guard onCall else { return self }- var state = self- state.call = activity.content.state.call- state.callStartedAt = activity.content.state.callStartedAt- return state- }-}diff --git a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swiftindex 50e89188..8b2aada4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Design/ActivityCards.swift@@ -5,7 +5,7 @@ public extension BotActivityPresentation {switch phase {case .working: .workingcase .needsInput: .listening- case .sending, .waiting, .stale: .connecting+ case .sending, .waiting, .stale, .onCall: .connectingcase .queued, .completed, .failed: nil}}@@ -15,7 +15,7 @@ public extension BotActivityPresentation {case .needsInput: Palette.attentioncase .failed: Palette.dangercase .completed: Palette.added- case .sending, .queued, .stale, .waiting: Palette.secondary+ case .sending, .queued, .stale, .waiting, .onCall: Palette.secondarycase .working: Palette.text}}@@ -27,7 +27,7 @@ public extension BotActivityPresentation {var progressStep: Int {switch phase {case .sending, .queued: 1- case .working, .stale, .waiting: 2+ case .working, .stale, .waiting, .onCall: 2case .needsInput: 3case .completed, .failed: 4}@@ -37,7 +37,7 @@ public extension BotActivityPresentation {switch phase {case .working: .workingcase .needsInput: .needsInput- case .sending, .queued, .completed, .failed, .stale, .waiting: .idle+ case .sending, .queued, .completed, .failed, .stale, .waiting, .onCall: .idle}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swiftindex e7c9eafc..be48ade4 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivity.swift@@ -1,6 +1,29 @@import ActivityKitimport Foundation+/// A voice call with the bot this phone is on, as its Live Activity shows it.+public enum CallState: String, Codable, Hashable, Sendable {+ case connecting, listening, speaking, paused+}++public extension BotActivityAttributes {+ /// The in-app switch for Live Activities (State tab › Live Activity).+ static let enabledKey = "liveActivitiesEnabled"++ static var isOn: Bool { UserDefaults.standard.object(forKey: enabledKey) as? Bool ?? true }++ /// Whether a Live Activity may start: the in-app switch and iOS's.+ static var mayStart: Bool { isOn && ActivityAuthorizationInfo().areActivitiesEnabled }++ /// The bot's Live Activity on screen, not one that ended.+ static func shown(botId: String, computerId: ComputerID) -> Activity<Self>? {+ Activity<Self>.activities.first {+ $0.attributes.botId == botId && $0.attributes.computerId == computerId+ && ($0.activityState == .active || $0.activityState == .stale)+ }+ }+}+/// Live Activity for a bot working on something the user just delegated./// Content state keys must match what codync-host pushes (host/src/remote/push.rs).public struct BotActivityAttributes: ActivityAttributes {@@ -10,12 +33,12 @@ public struct BotActivityAttributes: ActivityAttributes {/// Local app updates may show the current step; remote pushes leave it empty (§6.7).public var activity: Stringpublic var startedAt: Date?- /// A voice call with the bot this phone is on: connecting | listening | speaking | paused. Set by the app only.- public var call: String?+ /// A voice call with the bot this phone is on. Set by the app only.+ public var call: CallState?/// When that call started, for its length.public var callStartedAt: Date?- public init(status: String, activity: String, startedAt: Date?, call: String? = nil, callStartedAt: Date? = nil) {+ public init(status: String, activity: String, startedAt: Date?, call: CallState? = nil, callStartedAt: Date? = nil) {self.status = statusself.activity = activityself.startedAt = startedAtdiff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swiftindex 5bddf6d2..99ac3f6c 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotActivityPresentation.swift@@ -2,18 +2,20 @@ import Foundation/// Presentation only; the ActivityKit payload and host push contract stay unchanged.public struct BotActivityPresentation: Hashable, Sendable {- public enum Phase: String, CaseIterable, Sendable {+ public enum Phase: Hashable, Sendable {/// `sending` and `queued` are this phone's own (a message on its way, or waiting in the/// relay mailbox for an offline computer); the computer only pushes the others.case sending, queued, working, needsInput, completed, failed, stale, waiting+ /// This phone is on a call with the bot, which isn't working or waiting on you.+ case onCall(CallState)}public let phase: Phasepublic let activity: String/// The voice call with the bot this phone is on (`ContentState.call`), if any.- public let call: String?+ public let call: CallState?- public init(status: String, activity: String, isStale: Bool = false, call: String? = nil) {+ public init(status: String, activity: String, isStale: Bool = false, call: CallState? = nil) {let phase: Phase = switch status {case "sending": .sendingcase "queued": .queued@@ -25,25 +27,13 @@ public struct BotActivityPresentation: Hashable, Sendable {}let shown = isStale && (phase == .working || phase == .needsInput || phase == .sending) ? .stale : phase// On a call, a bot that isn't working or waiting on you shows the call instead of "Done".- self.phase = call != nil && [.completed, .stale, .waiting].contains(shown) ? .waiting : shown+ self.phase = if let call, [.completed, .stale, .waiting].contains(shown) { .onCall(call) } else { shown }self.activity = activityself.call = call}- /// The call's state in words, while this phone is on one with the bot.- public var callTitle: String? {- switch call {- case "connecting": "Connecting the call"- case "speaking": "On a call · Speaking"- case "paused": "Call paused"- case nil: nil- default: "On a call · Listening"- }- }-public var title: String {- if phase == .waiting, let callTitle { return callTitle }- return switch phase {+ switch phase {case .sending: "Sending"case .queued: "Waiting for your computer"case .working: "Working"@@ -52,24 +42,27 @@ public struct BotActivityPresentation: Hashable, Sendable {case .failed: "Failed"case .stale: "Update delayed"case .waiting: "Waiting for update"+ case .onCall(.connecting): "Connecting the call"+ case .onCall(.listening): "On a call · Listening"+ case .onCall(.speaking): "On a call · Speaking"+ case .onCall(.paused): "Call paused"}}/// The one line of text beside the orb: the bot's current step while it's live, else the state.public var caption: String {- if phase == .waiting, let callTitle { return callTitle }- return switch phase {+ switch phase {case .working, .needsInput: activity.isEmpty ? title : activity- case .sending, .queued, .completed, .failed, .stale, .waiting: title+ case .sending, .queued, .completed, .failed, .stale, .waiting, .onCall: title}}public var symbol: String {- if phase == .waiting, call != nil { return "waveform" }- return switch phase {+ switch phase {case .completed: "checkmark"case .failed: "exclamationmark.triangle.fill"case .queued: "desktopcomputer"+ case .onCall: "waveform"case .sending, .working, .needsInput, .stale, .waiting: "ellipsis"}}diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.jsonindex 47c9d0e9..7879093a 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/de.json@@ -697,7 +697,7 @@"Compact": "Kompakt","Minimal": "Minimal","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Die Dynamic Island zeigt dieselbe Live-Aktivität wie der Sperrbildschirm. Dieser Schalter deaktiviert daher beide.",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Beginnt, wenn du von diesem iPhone eine Aufgabe sendest. Verfolge den Fortschritt und öffne das Gespräch, wenn dein Bot dich braucht.",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Beginnt, wenn du von diesem iPhone eine Aufgabe sendest oder einen Bot anrufst. Verfolge den Fortschritt und öffne das Gespräch, wenn dein Bot dich braucht.","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "Der Bot mit seiner Stimmung, sein aktueller Schritt in der Statusfarbe, die Laufzeit, eine Denkkugel und sein Fortschritt. Wenn der Bot dich braucht, öffnet „Prüfen“ die Anfrage.","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "Der Bot und eine Denkkugel neben der Kamera, mit einer Umrandung in der Statusfarbe. Die Kugel wird am Aufgabenende zu einem Häkchen oder Warnzeichen.","Just the orb when iOS displays multiple Live Activities.": "Nur die Kugel, wenn iOS mehrere Live-Aktivitäten anzeigt.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.jsonindex 536db55b..61c26411 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/es.json@@ -697,7 +697,7 @@"Compact": "Compacto","Minimal": "Mínimo","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Island muestra la misma actividad en directo que la pantalla de bloqueo, así que este interruptor desactiva ambas.",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Se inicia cuando envías una tarea desde este iPhone. Sigue su progreso y abre la conversación cuando el bot te necesite.",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Se inicia cuando envías una tarea o llamas a un bot desde este iPhone. Sigue su progreso y abre la conversación cuando el bot te necesite.","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "El bot con su estado de ánimo, el paso actual en el color del estado, el tiempo transcurrido, una esfera de reflexión y su progreso. Cuando te necesita, Revisar abre la solicitud.","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "El bot y una esfera de reflexión junto a la cámara, con un borde del color del estado. La esfera se convierte en una marca o aviso cuando termina la tarea.","Just the orb when iOS displays multiple Live Activities.": "Solo la esfera cuando iOS muestra varias actividades en directo.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.jsonindex 106b7fb0..e33cfde7 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/fr.json@@ -697,7 +697,7 @@"Compact": "Compact","Minimal": "Minimal","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "La Dynamic Island affiche la même activité en direct que l’écran verrouillé ; ce commutateur désactive donc les deux.",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Démarre lorsque vous envoyez une tâche depuis cet iPhone. Suivez sa progression, puis ouvrez la conversation lorsque le bot a besoin de vous.",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "Démarre lorsque vous envoyez une tâche ou appelez un bot depuis cet iPhone. Suivez sa progression, puis ouvrez la conversation lorsque le bot a besoin de vous.","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "Le bot et son humeur, l’étape en cours dans la couleur de l’état, la durée, une sphère de réflexion et sa progression. Lorsque le bot a besoin de vous, Examiner ouvre la demande.","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "Le bot et une sphère de réflexion près de la caméra, entourés de la couleur de l’état. La sphère devient une coche ou un avertissement à la fin de la tâche.","Just the orb when iOS displays multiple Live Activities.": "Uniquement la sphère lorsque iOS affiche plusieurs activités en direct.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.jsonindex ff7d8a98..9ff5cf16 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ja.json@@ -697,7 +697,7 @@"Compact": "コンパクト","Minimal": "最小限","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Islandにはロック画面と同じライブアクティビティが表示されるため、このスイッチで両方がオフになります。",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "このiPhoneからタスクを送信すると開始します。進行状況を追跡し、ボットがあなたを必要とするときに会話を開きます。",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "このiPhoneからタスクを送信するか、ボットに電話をかけると開始します。進行状況を追跡し、ボットがあなたを必要とするときに会話を開きます。","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "ボットの気分、状態の色での現在のステップ、実行時間、思考オーブと進捗。ボットがあなたを必要とするとき、Review はリクエストを開きます。","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "ボットとカメラの横にある考える球体が州の色で縁取られています。タスクが終了すると、オーブはチェックまたは警告になります。","Just the orb when iOS displays multiple Live Activities.": "iOS が複数のライブ アクティビティを表示するときのオーブだけです。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.jsonindex 8ab59460..f4879991 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/ko.json@@ -697,7 +697,7 @@"Compact": "축소형","Minimal": "최소형","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "Dynamic Island는 잠금 화면과 같은 실시간 현황을 표시하므로 이 스위치를 끄면 둘 다 꺼집니다.",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "이 iPhone에서 작업을 보내면 시작됩니다. 진행 상황을 확인하고 봇이 나를 필요로 할 때 대화를 여세요.",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "이 iPhone에서 작업을 보내거나 봇에게 전화를 걸면 시작됩니다. 진행 상황을 확인하고 봇이 나를 필요로 할 때 대화를 여세요.","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "봇의 표정, 상태 색상의 현재 단계, 실행 시간, 생각 중인 구체와 진행 상황을 표시합니다. 도움이 필요하면 검토를 눌러 요청을 엽니다.","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "카메라 옆에 봇과 생각 중인 구체가 상태 색상의 테두리로 표시됩니다. 작업이 끝나면 구체가 체크 표시나 경고로 바뀝니다.","Just the orb when iOS displays multiple Live Activities.": "iOS가 여러 실시간 현황을 표시할 때는 구체만 표시됩니다.",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.jsonindex 9edeb82e..ee1562e0 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hans.json@@ -697,7 +697,7 @@"Compact": "紧凑","Minimal": "最小","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "灵动岛和锁定屏幕用的是同一个实时活动,所以这个开关会同时关掉两边。",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "从这台 iPhone 发出任务时开始。可以看进度,Bot 需要你时再打开对话。",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "从这台 iPhone 发出任务或和 Bot 通话时开始。可以看进度,Bot 需要你时再打开对话。","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "显示 Bot 的状态、当前步骤(颜色跟着状态走)、已运行时间、一个思考球和进度。需要你时,点「查看」打开请求。","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "摄像头旁边是 Bot 和一个思考球,描边颜色跟着状态走。任务结束时,球会变成对勾或警告。","Just the orb when iOS displays multiple Live Activities.": "iOS 同时显示多个实时活动时,只留下这个球。",diff --git a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.jsonindex 92fc9b1e..82044f51 100644--- a/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json+++ b/apps/ios/Kit/Sources/CodyncKit/Resources/Languages/zh-Hant.json@@ -697,7 +697,7 @@"Compact": "緊湊","Minimal": "最小","The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both.": "靈動島和鎖定螢幕用的是同一個實時活動,所以這個開關會同時關掉兩邊。",- "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "從這臺 iPhone 發出任務時開始。可以看進度,Bot 需要你時再開啟對話。",+ "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.": "從這臺 iPhone 發出任務或和 Bot 通話時開始。可以看進度,Bot 需要你時再開啟對話。","The bot in its mood, its current step in the state's color, the running time, a thinking orb and its progress. When the bot needs you, Review opens the request.": "顯示 Bot 的狀態、當前步驟(顏色跟著狀態走)、已執行時間、一個思考球和進度。需要你時,點「檢視」開啟請求。","The bot and a thinking orb beside the camera, outlined in the state's color. The orb becomes a check or warning when the task ends.": "攝像頭旁邊是 Bot 和一個思考球,描邊顏色跟著狀態走。任務結束時,球會變成對勾或警告。","Just the orb when iOS displays multiple Live Activities.": "iOS 同時顯示多個實時活動時,只留下這個球。",diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swiftindex addcc613..85a56163 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallActivity.swift@@ -1,36 +1,57 @@import ActivityKitimport CodyncKitimport Foundation+import os++private let log = Logger(subsystem: "com.pokai.Codync", category: "Call")/// The bot's Live Activity while this phone is on a call with it: the call's state and length, and the bot's latest/// progress from the computer. Uses the bot's activity if one is up (a task it was given), else starts one for the call.+/// The call's fields live here: every update of the activity merges them in (`withCall`), and they go back on after+/// the computer's pushes, which replace its state without them.@MainActorpublic final class CallActivity {- /// Bots this phone is on a call with now: an activity's call fields outlive a killed app otherwise.- private static var live: Set<String> = []+ public typealias State = BotActivityAttributes.ContentState- /// Whether this phone is on a call with the bot (the activity's call fields are current).- public static func isLive(botId: String) -> Bool { live.contains(botId) }+ /// The calls this phone is on, by bot.+ private static var calls: [String: CallActivity] = [:]private let attributes: BotActivityAttributesprivate let startedAt = Date.now- /// The activity this call started itself (none was up), ended with the call.+ /// The activity this call started itself (none was up): the computer can't update it.private var ownID: String?- private var call: String?+ private var call: CallState?+ /// The computer's latest progress line, until the bot's reply.private var progress: String?+ /// The activity followed for the computer's updates, and the tasks following it.+ private var followed: (id: String, tasks: [Task<Void, Never>])?init(bot: Bot, computerId: ComputerID, link: URL?) {attributes = BotActivityAttributes(bot: bot, computerId: computerId, link: link)- Self.live.insert(bot.id)+ Self.calls[bot.id] = self+ }++ /// Whether this phone is on a call with the bot.+ public static func isLive(botId: String) -> Bool { calls[botId] != nil }++ /// Whether a call started this activity itself.+ public static func started(_ activity: Activity<BotActivityAttributes>) -> Bool {+ calls[activity.attributes.botId]?.ownID == activity.id+ }++ /// `state` with the fields of the call this phone is on with the bot, or with none.+ public static func withCall(_ state: State, botId: String) -> State {+ let live = calls[botId]+ return merge(state, call: live?.call, since: live?.startedAt)}/// `ContentState.call` for a phase: nil once the call can't go on.- static func state(_ phase: VoicePhase) -> String? {+ static func state(_ phase: VoicePhase) -> CallState? {switch phase {- case .starting, .reconnecting: "connecting"- case .listening: "listening"- case .speaking: "speaking"- case .interrupted: "paused"+ case .starting, .reconnecting: .connecting+ case .listening: .listening+ case .speaking: .speaking+ case .interrupted: .pausedcase .failed: nil}}@@ -42,51 +63,86 @@ public final class CallActivity {show()}- /// What the bot is doing, from the computer's progress cues.- func progress(_ text: String) {- progress = text- show()+ /// What the computer said on the call: its progress shows until the bot's reply.+ func heard(_ cue: CallCue) {+ switch cue.kind {+ case .progress:+ progress = cue.text+ show(activity: cue.text)+ case .reply: progress = nil+ case .notice: break+ }}func end() {call = nil- Self.live.remove(attributes.botId)+ followed?.tasks.forEach { $0.cancel() }+ followed = nil+ // A newer call with the bot keeps the activity.+ guard Self.calls[attributes.botId] === self else { return }+ Self.calls[attributes.botId] = nillet (botId, computerId, own) = (attributes.botId, attributes.computerId, ownID)Task.detached {- guard let activity = Self.find(botId: botId, computerId: computerId) else { return }- if activity.id == own {- await activity.end(nil, dismissalPolicy: .immediate)- } else {- var state = activity.content.state- state.call = nil- state.callStartedAt = nil- await activity.update(.init(state: state, staleDate: activity.content.staleDate))- }+ guard let activity = BotActivityAttributes.shown(botId: botId, computerId: computerId) else { return }+ await Self.callEnded(on: activity, dismissNow: activity.id == own)}}- private func show() {- let (botId, computerId) = (attributes.botId, attributes.computerId)- let (call, startedAt, progress) = (call, startedAt, progress)- if Self.find(botId: botId, computerId: computerId) == nil {- guard call != nil, UserDefaults.standard.object(forKey: "liveActivitiesEnabled") as? Bool ?? true,- ActivityAuthorizationInfo().areActivitiesEnabled else { return }- let state = BotActivityAttributes.ContentState(status: "idle", activity: progress ?? "", startedAt: nil,- call: call, callStartedAt: startedAt)- ownID = try? Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil), pushType: nil).id- return+ /// A call is over on `activity`: one whose bot has nothing left to show ends (at once with `dismissNow`), and one+ /// with a task under way goes on without the call.+ public nonisolated static func callEnded(on activity: Activity<BotActivityAttributes>, dismissNow: Bool) async {+ let state = merge(activity.content.state, call: nil, since: nil)+ if ["idle", "completed", "error"].contains(state.status) {+ await activity.end(.init(state: state, staleDate: nil), dismissalPolicy: dismissNow ? .immediate : .after(.now + 60))+ } else {+ await activity.update(.init(state: state, staleDate: .now + 15 * 60))}+ }++ nonisolated static func merge(_ state: State, call: CallState?, since: Date?) -> State {+ var state = state+ state.call = call+ state.callStartedAt = call == nil ? nil : since+ return state+ }++ /// Puts the call on the bot's activity, with `activity` as its line if given, or starts one for the call.+ private func show(activity text: String? = nil) {+ let (botId, computerId) = (attributes.botId, attributes.computerId)+ guard Self.calls[botId] === self else { return }+ guard let shown = BotActivityAttributes.shown(botId: botId, computerId: computerId) else { return start() }+ follow(shown)+ let (call, startedAt) = (call, startedAt)Task.detached {- guard let activity = Self.find(botId: botId, computerId: computerId) else { return }- var state = activity.content.state- state.call = call- state.callStartedAt = startedAt- if let progress { state.activity = progress }- await activity.update(.init(state: state, staleDate: nil))+ guard let activity = BotActivityAttributes.shown(botId: botId, computerId: computerId) else { return }+ var state = Self.merge(activity.content.state, call: call, since: startedAt)+ if let text { state.activity = text }+ guard state != activity.content.state else { return }+ await activity.update(.init(state: state, staleDate: activity.content.staleDate))+ }+ }++ private func start() {+ guard call != nil, BotActivityAttributes.mayStart else { return }+ let state = Self.merge(.init(status: "idle", activity: progress ?? "", startedAt: nil), call: call, since: startedAt)+ do {+ let activity = try Activity.request(attributes: attributes, content: .init(state: state, staleDate: nil), pushType: nil)+ ownID = activity.id+ follow(activity)+ } catch {+ log.error("Live activity for the call not started: \(error.localizedDescription, privacy: .public)")}}- private nonisolated static func find(botId: String, computerId: ComputerID) -> Activity<BotActivityAttributes>? {- Activity<BotActivityAttributes>.activities.first { $0.attributes.botId == botId && $0.attributes.computerId == computerId }+ /// Follows the activity showing the call: a push from the computer replaces its state without the call's fields,+ /// which go back on, and its last one ends it, which gives the call its own activity (one the user swiped away+ /// stays away).+ private func follow(_ activity: Activity<BotActivityAttributes>) {+ guard followed?.id != activity.id else { return }+ followed?.tasks.forEach { $0.cancel() }+ followed = (activity.id, [+ Task { [weak self] in for await _ in activity.contentUpdates { self?.show() } },+ Task { [weak self] in for await state in activity.activityStateUpdates where state == .ended { self?.show() } },+ ])}}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallAudio.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallAudio.swiftindex a1f125bb..443e035c 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallAudio.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallAudio.swift@@ -1,6 +1,7 @@import AVFoundationimport Foundationimport os+@preconcurrency import WebRTCprivate let log = Logger(subsystem: "com.pokai.Codync", category: "Call")@@ -29,22 +30,59 @@ enum AudioInterruption {case ended(shouldResume: Bool)}-/// Who lets go of a call's audio session: the call's engine, or the system when it runs the call (CallKit activates the-/// session itself and deactivates it once the call ends; an engine deactivating it mid-call would cut the audio).+/// The call's audio session, set up the same way for every engine. Under CallKit the system activates it (and+/// deactivates it as its call ends or is held), and WebRTC's audio runs only while it's active; otherwise the engines+/// activate and release it.@MainActorenum CallAudioSession {- /// A CallKit call carries the audio (`SystemCall`).- static var systemRuns = false+ /// The category options of every engine's audio, WebRTC's too.+ static let options: AVAudioSession.CategoryOptions = [.defaultToSpeaker, .allowBluetoothHFP]++ /// A CallKit call carries the audio (`CallKitCalls`). WebRTC then waits for the system's activation+ /// (`useManualAudio`) instead of activating the session itself, and deactivating it as a connection closes.+ static var systemRuns = false {+ didSet {+ let webRTC = RTCAudioSession.sharedInstance()+ webRTC.isAudioEnabled = false+ webRTC.useManualAudio = systemRuns+ }+ }++ /// Sets the call's category; CallKit activates the session it finds configured.+ static func configure() throws {+ try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .voiceChat, options: options)+ }++ /// Before an engine's audio starts or resumes: the session set up, and active unless the system activates it.+ static func activate() throws {+ try configure()+ guard !systemRuns else { return }+ try AVAudioSession.sharedInstance().setActive(true)+ }/// After an engine stops: deactivates the session unless the system runs the call.static func release() {guard !systemRuns else { return }try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)}++ /// CallKit activated the session (the call started, or came off hold): WebRTC's audio may run.+ static func systemActivated(_ session: AVAudioSession) {+ let webRTC = RTCAudioSession.sharedInstance()+ webRTC.audioSessionDidActivate(session)+ webRTC.isAudioEnabled = true+ }++ /// CallKit deactivated the session (held, or ended).+ static func systemDeactivated(_ session: AVAudioSession) {+ let webRTC = RTCAudioSession.sharedInstance()+ webRTC.audioSessionDidDeactivate(session)+ webRTC.isAudioEnabled = false+ }}extension Notification.Name {- /// CallKit put the call on hold (`held` true: a phone call took over) or took it off hold.+ /// CallKit put the call on hold (`held` true: a phone call took over) or gave it its audio back after one.static let callHeld = Notification.Name("CodyncCallHeld")}@@ -100,9 +138,7 @@ final class VoiceProcessingAudio: CallAudio {func start(mic: @escaping @MainActor (String, Float) -> Void) throws {self.mic = mic- let session = AVAudioSession.sharedInstance()- try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])- try session.setActive(true)+ try CallAudioSession.activate()try engine.inputNode.setVoiceProcessingEnabled(true)engine.attach(player)// The engine stops itself when it reconfigures; without a restart the microphone goes quiet.@@ -137,7 +173,7 @@ final class VoiceProcessingAudio: CallAudio {}func resume() throws {- try AVAudioSession.sharedInstance().setActive(true)+ try CallAudioSession.activate()if !engine.isRunning { try run() }}diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swiftindex 58fee6ab..12002dc9 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CallView.swift@@ -29,7 +29,7 @@ struct CallView: View {/// Each engine's `voice_call_quality`.@State private var quality = CallQuality()/// The call as the system shows it (CallKit); nil where CallKit isn't offered (mainland China) or it refused.- @State private var system: SystemCall?+ @State private var system: CallKitCall?/// The bot's Live Activity showing the call.@State private var activity: CallActivity?/// The call view went away (before its engine may have started).@@ -157,7 +157,7 @@ struct CallView: View {if active {model.beginVoiceCall(callID, hear: { [weak engine, activity] cue inengine?.hear(cue)- if cue.kind == .progress { activity?.progress(cue.text) }+ activity?.heard(cue)}, end: { [weak engine] in engine?.end() })} else {model.endVoiceCall(callID)diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swiftindex 6f87e96a..0ce9ea83 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/CloudSpeechEngine.swift@@ -82,9 +82,7 @@ final class CloudSpeechEngine: VoiceEngine {}guard !ended else { return }do {- let session = AVAudioSession.sharedInstance()- try session.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])- try session.setActive(true)+ try CallAudioSession.activate()try runMic()audioRunning = true} catch {@@ -115,7 +113,7 @@ final class CloudSpeechEngine: VoiceEngine {func resume() {guard !ended, phase == .interrupted else { return }do {- try AVAudioSession.sharedInstance().setActive(true)+ try CallAudioSession.activate()try runMic()} catch {return fail("Couldn't use the microphone: \(error.localizedDescription)", .microphone)@@ -148,7 +146,7 @@ final class CloudSpeechEngine: VoiceEngine {engine.stop()audioRunning = false}- CallAudioSession.release()+ CallAudioSession.release()}func interrupt() {diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swiftindex 70dd4099..d9f38969 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/OnDeviceEngine.swift@@ -84,13 +84,11 @@ final class OnDeviceEngine: VoiceEngine {return fail("Speech recognition isn't available for this language right now.", .provider)}guard !ended else { return }- do {- let audio = AVAudioSession.sharedInstance()- try audio.setCategory(.playAndRecord, mode: .voiceChat, options: [.defaultToSpeaker, .allowBluetoothHFP])- try audio.setActive(true)- } catch {- return fail("Couldn't start audio: \(error.localizedDescription)", .microphone)- }+ do {+ try CallAudioSession.activate()+ } catch {+ return fail("Couldn't start audio: \(error.localizedDescription)", .microphone)+ }// A route change (AirPods) stops the engine mid-utterance: listen again on the new microphone.events = AudioSessionEvents(engine: engine, interrupted: { [weak self] in self?.interrupted($0) },reconfigured: { [weak self] in@@ -104,7 +102,7 @@ final class OnDeviceEngine: VoiceEngine {/// listening again.func resume() {guard !ended, phase == .interrupted else { return }- try? AVAudioSession.sharedInstance().setActive(true)+ try? CallAudioSession.activate()listen()guard !unsaid.isEmpty else { return }let waiting = unsaid.joined(separator: "\n\n")@@ -132,7 +130,7 @@ final class OnDeviceEngine: VoiceEngine {events = nilstopListening()synthesizer.stopSpeaking(at: .immediate)- CallAudioSession.release()+ CallAudioSession.release()}/// Reads a reply aloud (the bot's final message), pausing the microphone meanwhile.diff --git a/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swiftindex 32e9149c..05790cf6 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/OpenAIRealtimeEngine.swift@@ -78,9 +78,10 @@ final class OpenAIRealtimeEngine: VoiceEngine {}private func connect(secret: String) async throws {- let audio = RTCAudioSessionConfiguration.webRTC()- audio.categoryOptions = [.defaultToSpeaker, .allowBluetoothHFP]- RTCAudioSessionConfiguration.setWebRTC(audio)+ // Under CallKit, WebRTC's audio waits for the system's activation (`CallAudioSession`).+ let audio = RTCAudioSessionConfiguration.webRTC()+ audio.categoryOptions = CallAudioSession.options+ RTCAudioSessionConfiguration.setWebRTC(audio)let config = RTCConfiguration()config.sdpSemantics = .unifiedPlandiff --git a/apps/ios/Kit/Sources/CodyncUI/Call/SystemCall.swift b/apps/ios/Kit/Sources/CodyncUI/Call/SystemCall.swiftindex b4ff820e..4f76e97a 100644--- a/apps/ios/Kit/Sources/CodyncUI/Call/SystemCall.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Call/SystemCall.swift@@ -6,24 +6,6 @@ import osprivate let log = Logger(subsystem: "com.pokai.Codync", category: "Call")-/// The call as the system shows it (CallKit): on the Lock Screen and in the Dynamic Island, ended or muted from there-/// or from AirPods, held by a phone call, with the audio session the system activates for it.-@MainActor-protocol SystemCall: AnyObject {- /// The system ended the call (Lock Screen, Dynamic Island, AirPods, another call answered instead).- var onEnd: (() -> Void)? { get set }- /// The system muted or unmuted the call.- var onMute: ((Bool) -> Void)? { get set }- /// The call reached its voice.- func connected()- /// The app muted or unmuted the call.- func setMuted(_ muted: Bool)- /// The app hung up.- func end()- /// Returns once the system activated the call's audio session, or after a moment if it doesn't (the Simulator).- func audioReady() async-}-/// Where CallKit may carry calls: not in apps offered in mainland China's App Store, which doesn't allow CallKit.enum SystemCallPolicy {static func allowed(storefront: String?, region: String?) -> Bool {@@ -57,7 +39,7 @@ final class CallKitCalls: NSObject {provider.setDelegate(self, queue: nil)}- func start(id: UUID, name: String) -> SystemCall {+ func start(id: UUID, name: String) -> CallKitCall {current?.systemEnded()let call = CallKitCall(id: id, calls: self)current = call@@ -66,10 +48,8 @@ final class CallKitCalls: NSObject {controller.request(CXTransaction(action: start)) { error inguard let error else { return }Task { @MainActor in- // The call goes on without the system's (the Simulator, CallKit unavailable).log.info("CallKit didn't take the call: \(error.localizedDescription, privacy: .public)")- call.declined()- self.finished(call)+ self.drop(call)}}return call@@ -85,8 +65,15 @@ final class CallKitCalls: NSObject {}}+ /// CallKit refused the call or lost it (the Simulator, CallKit unavailable, its daemon restarted): the call goes+ /// on without the system's.+ private func drop(_ call: CallKitCall) {+ call.declined()+ finished(call)+ }+/// The call is over for CallKit (ended, or never taken): the engines manage the audio session again.- fileprivate func finished(_ call: CallKitCall) {+ private func finished(_ call: CallKitCall) {call.systemEnded()guard current === call else { return }current = nil@@ -95,31 +82,20 @@ final class CallKitCalls: NSObject {}extension CallKitCalls: @preconcurrency CXProviderDelegate {- /// CallKit dropped its calls (its daemon restarted, or it isn't available): the call goes on without the system's.func providerDidReset(_ provider: CXProvider) {- guard let current else { return }- current.declined()- finished(current)+ if let current { drop(current) }}func provider(_ provider: CXProvider, perform action: CXStartCallAction) {- // CallKit activates the session it finds configured.- try? AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .voiceChat,- options: [.defaultToSpeaker, .allowBluetoothHFP])+ do { try CallAudioSession.configure() } catch {+ log.error("call audio category: \(error.localizedDescription, privacy: .public)")+ }provider.reportOutgoingCall(with: action.callUUID, startedConnectingAt: nil)action.fulfill()}func provider(_ provider: CXProvider, perform action: CXEndCallAction) {- if let current, current.id == action.callUUID {- // An end before the call ever got its audio or connected is CallKit dropping it (the Simulator ends- // calls right after starting them): the call goes on without the system's.- if !current.live {- log.info("CallKit ended the call before it connected; going on without it")- current.declined()- }- finished(current)- }+ if let current, current.id == action.callUUID { finished(current) }action.fulfill()}@@ -129,45 +105,66 @@ extension CallKitCalls: @preconcurrency CXProviderDelegate {}func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {- NotificationCenter.default.post(name: .callHeld, object: nil, userInfo: ["held": action.isOnHold])+ if let current, current.id == action.callUUID { current.held(action.isOnHold) }action.fulfill()}+ // Every activation has its deactivation, also after the call is over: WebRTC counts them.func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {+ CallAudioSession.systemActivated(audioSession)current?.audioActivated()}- func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {}+ func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {+ CallAudioSession.systemDeactivated(audioSession)+ current?.audioDeactivated()+ }}+/// The call as the system shows it (CallKit): on the Lock Screen and in the Dynamic Island, ended or muted from there+/// or from AirPods, held by a phone call, with the audio session the system activates for it.@MainActor-final class CallKitCall: SystemCall {+final class CallKitCall {+ /// The system ended the call (Lock Screen, Dynamic Island, AirPods, another call answered instead).var onEnd: (() -> Void)?+ /// The system muted or unmuted the call.var onMute: ((Bool) -> Void)?let id: UUIDprivate weak var calls: CallKitCalls?private var over = false/// The call got its audio session or connected: from here an end from the system is the user's.- fileprivate private(set) var live = false- private var audioActive = false+ private var live = false+ private var audio = Audio.awaited+ /// Taken off hold while the system still had its audio: the engine picks up once it's back.+ private var resumesOnAudio = falseprivate var waiting: [CheckedContinuation<Void, Never>] = []- fileprivate init(id: UUID, calls: CallKitCalls) {+ /// How long `audioReady` waits for the system's activation (it never comes on the Simulator).+ static var audioTimeout: Duration = .seconds(1.5)++ /// The call's audio session as the system hands it over.+ private enum Audio { case awaited, active, takenAway }++ /// `calls` is nil only in tests.+ init(id: UUID, calls: CallKitCalls? = nil) {self.id = idself.calls = calls}+ /// The call reached its voice.func connected() {guard !over else { return }live = truecalls?.connected(self)}+ /// The app muted or unmuted the call.func setMuted(_ muted: Bool) {guard !over else { return }calls?.request(CXSetMutedCallAction(call: id, muted: muted))}+ /// The app hung up.func end() {guard !over else { return }over = true@@ -175,33 +172,51 @@ final class CallKitCall: SystemCall {resumeWaiting()}+ /// Returns once the system activated the call's audio session, or after `audioTimeout` if it doesn't.func audioReady() async {- guard !audioActive, !over else { return }+ guard audio == .awaited, !over else { return }Task { [weak self] in- try? await Task.sleep(for: .seconds(1.5))+ try? await Task.sleep(for: Self.audioTimeout)self?.resumeWaiting()}await withCheckedContinuation { waiting.append($0) }}- fileprivate func audioActivated() {- audioActive = true+ func audioActivated() {+ audio = .activelive = trueresumeWaiting()+ if resumesOnAudio {+ resumesOnAudio = false+ Self.post(held: false)+ }+ }++ func audioDeactivated() {+ audio = .takenAway+ }++ /// CallKit held the call (a phone call took over) or took it off hold: the engine pauses at once, and picks up+ /// again once the system has given the audio back, so it doesn't start on a session that isn't active.+ func held(_ onHold: Bool) {+ resumesOnAudio = !onHold && audio == .takenAway+ if !resumesOnAudio { Self.post(held: onHold) }}/// CallKit refused the call: it goes on without the system's.- fileprivate func declined() {+ func declined() {over = trueresumeWaiting()}- /// CallKit ended the call; the app hangs up too unless it started the ending.- fileprivate func systemEnded() {+ /// CallKit ended the call. Before the call ever got its audio or connected, that's CallKit dropping it (the+ /// Simulator ends calls right after starting them) and the call goes on without the system's; after, the app+ /// hangs up too unless it started the ending.+ func systemEnded() {resumeWaiting()guard !over else { return }over = true- onEnd?()+ if live { onEnd?() } else { log.info("CallKit ended the call before it connected; going on without it") }}private func resumeWaiting() {@@ -209,4 +224,8 @@ final class CallKitCall: SystemCall {waiting = []for continuation in continuations { continuation.resume() }}++ private static func post(held: Bool) {+ NotificationCenter.default.post(name: .callHeld, object: nil, userInfo: ["held": held])+ }}diff --git a/apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swiftindex f91383db..7b452c62 100644--- a/apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swift+++ b/apps/ios/Kit/Tests/CodyncKitTests/ActivityPresentationTests.swift@@ -40,14 +40,20 @@ import Testing#expect(BotsTeamCard.slots(bots: bots, picks: ["gone"]).first??.id == "preview-review")}-@Test func aCallShowsOnTheActivityInsteadOfDone() {- let idle = BotActivityPresentation(status: "idle", activity: "Old step", call: "listening")- #expect(idle.phase == .waiting)+@Test func aCallShowsOnTheActivityInsteadOfDone() throws {+ let idle = BotActivityPresentation(status: "idle", activity: "Old step", call: .listening)+ #expect(idle.phase == .onCall(.listening))#expect(idle.caption == "On a call · Listening")#expect(idle.symbol == "waveform")- #expect(BotActivityPresentation(status: "idle", activity: "", call: "connecting").caption == "Connecting the call")- // While the bot works, its progress is the line; a waiting approval stays visible.- #expect(BotActivityPresentation(status: "working", activity: "Running the tests", call: "speaking").caption == "Running the tests")- #expect(BotActivityPresentation(status: "needsInput", activity: "Choose", call: "listening").phase == .needsInput)+ #expect(BotActivityPresentation(status: "idle", activity: "", call: .connecting).caption == "Connecting the call")+ #expect(BotActivityPresentation(status: "working", activity: "", isStale: true, call: .paused).title == "Call paused")+ // While the bot works, its progress is the line; a waiting approval and a failure stay visible.+ #expect(BotActivityPresentation(status: "working", activity: "Running the tests", call: .speaking).caption == "Running the tests")+ #expect(BotActivityPresentation(status: "needsInput", activity: "Choose", call: .listening).phase == .needsInput)+ #expect(BotActivityPresentation(status: "error", activity: "", call: .listening).phase == .failed)#expect(BotActivityPresentation(status: "idle", activity: "").title == "Done")+ // The app writes the call as its raw value (the widget decodes it).+ let state = BotActivityAttributes.ContentState(status: "idle", activity: "", startedAt: nil, call: .speaking)+ let json = try #require(String(data: try JSONEncoder().encode(state), encoding: .utf8))+ #expect(json.contains(#""call":"speaking""#))}diff --git a/apps/ios/Kit/Tests/CodyncUITests/SystemCallTests.swift b/apps/ios/Kit/Tests/CodyncUITests/SystemCallTests.swiftindex 07ef27f3..b62a92b2 100644--- a/apps/ios/Kit/Tests/CodyncUITests/SystemCallTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/SystemCallTests.swift@@ -1,5 +1,6 @@import Foundationimport Testing+@testable import CodyncKit@testable import CodyncUI@Test func callKitStaysOffWhereTheAppStoreIsMainlandChinas() {@@ -12,10 +13,107 @@ import Testing}@MainActor @Test func theLiveActivityFollowsTheCallsPhase() {- #expect(CallActivity.state(.starting) == "connecting")- #expect(CallActivity.state(.reconnecting) == "connecting")- #expect(CallActivity.state(.listening) == "listening")- #expect(CallActivity.state(.speaking) == "speaking")- #expect(CallActivity.state(.interrupted) == "paused")+ #expect(CallActivity.state(.starting) == .connecting)+ #expect(CallActivity.state(.reconnecting) == .connecting)+ #expect(CallActivity.state(.listening) == .listening)+ #expect(CallActivity.state(.speaking) == .speaking)+ #expect(CallActivity.state(.interrupted) == .paused)#expect(CallActivity.state(.failed("x", .connection)) == nil)}++@MainActor @Test func anActivityShowsTheCallOnlyWhileThisPhoneIsOnIt() throws {+ var bot = try #require(Bot.widgetPreview.first)+ bot.id = "call-activity-test"+ // The computer's push carries no call; one left on the activity by a call that's over goes.+ let pushed = BotActivityAttributes.ContentState(status: "working", activity: "", startedAt: nil)+ let leftover = CallActivity.merge(pushed, call: .listening, since: .now)+ #expect(CallActivity.withCall(leftover, botId: bot.id) == pushed)++ let older = CallActivity(bot: bot, computerId: "computer", link: nil)+ older.phase(.speaking)+ let shown = CallActivity.withCall(pushed, botId: bot.id)+ #expect(shown.call == .speaking && shown.callStartedAt != nil && shown.status == "working")+ // A newer call with the bot outlives the older one ending.+ let newer = CallActivity(bot: bot, computerId: "computer", link: nil)+ newer.phase(.listening)+ older.end()+ #expect(CallActivity.isLive(botId: bot.id))+ #expect(CallActivity.withCall(pushed, botId: bot.id).call == .listening)+ newer.end()+ #expect(!CallActivity.isLive(botId: bot.id))+ #expect(CallActivity.withCall(leftover, botId: bot.id) == pushed)+}++@MainActor @Test func callKitEndingTheCallHangsUpOnlyOnceTheCallWasLive() {+ var hungUp = 0+ func systemEnds(after setUp: (CallKitCall) -> Void) {+ let call = CallKitCall(id: UUID())+ call.onEnd = { hungUp += 1 }+ setUp(call)+ call.systemEnded()+ }+ // Ended before it got its audio or connected: CallKit dropped it (the Simulator), and the call goes on.+ systemEnds { _ in }+ #expect(hungUp == 0)+ systemEnds { $0.connected() }+ #expect(hungUp == 1)+ systemEnds { $0.audioActivated() }+ #expect(hungUp == 2)+ // The app hung up, or CallKit refused the call: nothing more to end.+ systemEnds { $0.connected(); $0.end() }+ systemEnds { $0.connected(); $0.declined() }+ #expect(hungUp == 2)+}++@MainActor @Test func theCallWaitsForCallKitsAudioAtMostAMoment() async throws {+ let timeout = CallKitCall.audioTimeout+ defer { CallKitCall.audioTimeout = timeout }+ let clock = ContinuousClock()++ CallKitCall.audioTimeout = .seconds(5)+ let call = CallKitCall(id: UUID())+ var start = clock.now+ let ready = Task { await call.audioReady() }+ try await Task.sleep(for: .milliseconds(50))+ call.audioActivated()+ await ready.value+ #expect(clock.now - start < .seconds(2))+ // Active already: no wait.+ start = clock.now+ await call.audioReady()+ #expect(clock.now - start < .seconds(1))+ // It never comes: the call goes on after the timeout.+ CallKitCall.audioTimeout = .milliseconds(50)+ start = clock.now+ await CallKitCall(id: UUID()).audioReady()+ #expect(clock.now - start < .seconds(2))+}++@MainActor @Test func callKitsHoldPausesTheCallAndItResumesOnceTheAudioIsBack() async {+ var heard: [String] = []+ let events = AudioSessionEvents(engine: nil, interrupted: { change in+ switch change {+ case .began: heard.append("paused")+ case .ended(let shouldResume): heard.append(shouldResume ? "resumed" : "ended")+ }+ })+ defer { events.stop() }+ func settle() async { try? await Task.sleep(for: .milliseconds(20)) }++ let call = CallKitCall(id: UUID())+ call.audioActivated()+ call.held(true)+ call.audioDeactivated()+ // Off hold before the system gave the audio back: the engine waits for it.+ call.held(false)+ await settle()+ #expect(heard == ["paused"])+ call.audioActivated()+ await settle()+ #expect(heard == ["paused", "resumed"])+ // Held without losing the audio: off hold resumes at once.+ call.held(true)+ call.held(false)+ await settle()+ #expect(heard == ["paused", "resumed", "paused", "resumed"])+}diff --git a/apps/ios/Views/ActivityGalleryView.swift b/apps/ios/Views/ActivityGalleryView.swiftindex be2cfcea..d9fe5fc4 100644--- a/apps/ios/Views/ActivityGalleryView.swift+++ b/apps/ios/Views/ActivityGalleryView.swift@@ -8,7 +8,7 @@ struct ActivityGalleryView: View {var forms = BotActivityPreview.Form.allCases@Environment(\.scenePhase) private var scenePhase@Environment(\.openURL) private var openURL- @AppStorage("liveActivitiesEnabled") private var enabled = true+ @AppStorage(BotActivityAttributes.enabledKey) private var enabled = true@State private var allowed = ActivityAuthorizationInfo().areActivitiesEnabled@State private var form: BotActivityPreview.Form?@State private var phase = BotActivityPresentation.Phase.working@@ -24,7 +24,7 @@ struct ActivityGalleryView: View {case .needsInput: "needsInput"case .completed: "idle"case .failed: "error"- case .waiting: "unknown"+ case .waiting, .onCall: "unknown"}return .init(status: status, activity: phase == .needsInput ? "Review the proposed changes." : "Running the test suite.",isStale: phase == .stale)@@ -45,7 +45,7 @@ struct ActivityGalleryView: View {.font(.subheadline.weight(.medium))Text(L10n.tr(island? "The Dynamic Island shows the same Live Activity as the Lock Screen, so this switch turns off both."- : "Starts when you send a task from this iPhone. Follow its progress, then open the conversation when your bot needs you."))+ : "Starts when you send a task or call a bot from this iPhone. Follow its progress, then open the conversation when your bot needs you.")).font(.footnote).foregroundStyle(Palette.secondary)if !allowed {Text(L10n.tr("Live Activities are turned off in iOS Settings."))diff --git a/docs/design/push-and-live-activity.md b/docs/design/push-and-live-activity.mdindex 74723a32..717ad81e 100644--- a/docs/design/push-and-live-activity.md+++ b/docs/design/push-and-live-activity.md@@ -40,7 +40,7 @@ flowchart LR- The extension then turns the alert into a communication notification (`INSendMessageIntent`) so the banner shows the bot's avatar instead of the app icon. A group alert carries the speaking member (`from`, sealed with the text) and shows as a group conversation: the group's avatar and name, with the member as sender. The sealed alert carries `faces` (name, shape and color of the chat, its first two members and the speaker), so a bot created while the app was closed still gets its avatar; alerts from an older host fall back to the widget snapshot in the App Group, and a bot in neither keeps the plain banner. Needs the app's Communication Notifications entitlement and `NSUserActivityTypes: INSendMessageIntent`. [Apple communication notifications](https://developer.apple.com/documentation/usernotifications/implementing-communication-notifications)- ActivityKit renders both Lock Screen and Dynamic Island. A separate Dynamic Island Worker or event API is unnecessary. APNs updates use a dedicated activity token, not the normal notification token. [Apple ActivityKit push updates](https://developer.apple.com/documentation/ActivityKit/starting-and-updating-live-activities-with-activitykit-push-notifications)-Remote activity content contains only `status`, empty `activity`, and `startedAt`. During a voice call the app also sets `call` and `callStartedAt` locally ([the call on the system](../features/voice-call.md#the-call-on-the-system)); the computer never sends them. Foreground app updates may show the current step from the encrypted connection; a remote update clears that free text. The notification service extension is not an ActivityKit decryption stage. The UI therefore does not promise private task summaries in background Live Activities. Bot identity and its deep link are set locally when starting the activity.+Remote activity content contains only `status`, empty `activity`, and `startedAt`. During a voice call the app also sets `call` and `callStartedAt` locally ([the call on the system](../features/voice-call.md#the-call-on-the-system)); the computer never sends them, so a remote update drops them and the app puts them back, and the app doesn't end the activity while the call lasts. Foreground app updates may show the current step from the encrypted connection; a remote update clears that free text. The notification service extension is not an ActivityKit decryption stage. The UI therefore does not promise private task summaries in background Live Activities. Bot identity and its deep link are set locally when starting the activity.## Registration and lifecyclediff --git a/docs/features/voice-call.md b/docs/features/voice-call.mdindex 8359f968..77e979aa 100644--- a/docs/features/voice-call.md+++ b/docs/features/voice-call.md@@ -370,18 +370,25 @@ carries audio and talks to these methods:- iPhone: a call is a CallKit outgoing call to the bot (`SystemCall.swift`, one `CXProvider`, audio only, not inRecents): it shows on the Lock Screen and in the Dynamic Island, ends or mutes from there and from AirPods, and a- phone call holds it (`CXSetHeldCallAction` pauses the engine the way an interruption does, and taking it off hold- resumes). CallKit activates the audio session: the engine starts once it has (at most 1.5 s later where it never- does, as on the Simulator), and the engines leave deactivating it to CallKit (`CallAudioSession`). The call reports- connected once the engine reaches ready. Where CallKit refuses the call, it goes on without it.+ phone call holds it (`CXSetHeldCallAction` pauses the engine the way an interruption does; off hold, it resumes once+ CallKit has activated the audio session again). CallKit activates and deactivates the audio session+ (`CallAudioSession`): the engine starts once it has (at most 1.5 s later where it never does, as on the Simulator),+ the engines set the session up but neither activate nor deactivate it, and OpenAI's WebRTC audio runs only while+ CallKit has it active (`useManualAudio`, `audioSessionDidActivate`/`DidDeactivate`), so a reconnect or an engine+ switch doesn't cut the call's audio. The call reports connected once the engine reaches ready. CallKit ending the+ call before that (the Simulator does at once), refusing it or resetting leaves the call going on without it.- CallKit isn't allowed in apps offered in mainland China's App Store: with the storefront `CHN` (or, without astorefront, the region `CN`) the call keeps the app's own audio session, as before (`SystemCallPolicy`).- iPhone Live Activity: while a call is on, the bot's activity shows it (`ContentState.call`: connecting, listening,- speaking, paused; `callStartedAt` for its length) and the bot's latest progress line from the computer- (`CallActivity`). It uses the bot's activity if one is up and starts one for the call otherwise (ended with the- call). The computer never sets these fields; the app's own updates keep them.+ speaking, paused; `callStartedAt` for its length) and the bot's latest progress line from the computer until its+ reply (`CallActivity`). It uses the bot's activity if one is up and starts one for the call otherwise; a task sent+ during the call replaces the call's own activity with one the computer can update. The computer never sets the call+ fields: the app keeps them in memory and merges them into every update, puts them back after a push from the+ computer replaces the state, and gives the call its own activity again when the computer's last push ends the+ task's. When the call ends, an activity whose bot is idle or failed ends (at once if the call started it, else a+ minute later) and one with a task under way stays without the call.- Android: the call's foreground notification shows its state and the bot's latest progress line (cleared by its- reply), updated in place at most once a second, with Mute and End call.+ reply), updated in place, with Mute and End call.- The desktop and the terminal have no system call UI to join.### Failure and costdiff --git a/docs/plans/voice-architecture.md b/docs/plans/voice-architecture.mdindex 52037c30..c5ca3f71 100644--- a/docs/plans/voice-architecture.md+++ b/docs/plans/voice-architecture.md@@ -79,8 +79,7 @@ replayed end to end in the iPhone and desktop tests (its events are).### 4. PlatformShipped in 2.26.0 ([the call on the system](../features/voice-call.md#the-call-on-the-system)). CallKit stays off where-the App Store storefront is mainland China's. OpenAI's WebRTC audio isn't handed to CallKit's session activation-(`useManualAudio`); it still activates the session itself.+the App Store storefront is mainland China's.- iPhone: CallKit for the call (lock screen, Dynamic Island, AirPods controls, interruptions handled by the system),and the bot's progress in the call's Live Activity.diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex cc9b391d..d506ab0e 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -142,7 +142,7 @@ To turn notifications off on the iPhone, open **Computers & settings** from the### Live Activities-When you send a message from the iPhone, a Live Activity for that bot appears on the Lock Screen and in the Dynamic Island. It shows whether the bot is working, needs you, is done or failed, without the message text. On the Lock Screen, a progress line of four segments in the state's color fills as the task moves: one while your message is sent or queued, two while the bot works, three when it needs you, four once it ends. Turn it off in the **State** tab under **Live Activity**.+When you send a message from the iPhone, a Live Activity for that bot appears on the Lock Screen and in the Dynamic Island. It shows whether the bot is working, needs you, is done or failed, without the message text. On the Lock Screen, a progress line of four segments in the state's color fills as the task moves: one while your message is sent or queued, two while the bot works, three when it needs you, four once it ends. A [voice call](/docs/voice#start-a-call) with the bot shows on its Live Activity too, with what the bot is doing while you talk. Turn it off in the **State** tab under **Live Activity**; that also keeps calls off it.## Usage limits