Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(ios): harden call leaving (#5801)

Peter Chinman4249ccf73ed6
diff --git a/apps/web/src/features/channel/Call/CallSessionController.ts b/apps/web/src/features/channel/Call/CallSessionController.ts
index 84bb1f3ffb..8102ea1f8f 100644
--- a/apps/web/src/features/channel/Call/CallSessionController.ts
+++ b/apps/web/src/features/channel/Call/CallSessionController.ts
@@ -4,6 +4,7 @@ import {
endCallKitCall,
isNativeIosCallKitEnabled,
startNativeCallKitOutgoingCall,
+ syncNativeCallStateAfterLeave,
} from './use-callkit';
type CallSessionControllerOptions = {
@@ -106,6 +107,12 @@ function createNativeCallKitSessionController(options: {
options.clearOptimisticJoin();
},
disconnect: async (disconnectOptions) => {
+ // Captured before any teardown: the post-leave sync may clear exactly
+ // this state — a newer call's state appearing mid-leave must survive.
+ const stateBeforeLeave = {
+ snapshot: options.nativeCall.snapshot(),
+ bootstrapChannelId: options.nativeCall.bootstrapChannelId(),
+ };
if (disconnectOptions?.endNativeCall !== false) {
try {
await endCallKitCall();
@@ -113,8 +120,23 @@ function createNativeCallKitSessionController(options: {
console.error('callkit: failed to dismiss call sheet', e);
}
}
- await options.jsDisconnect();
- options.clearOptimisticJoin();
+ try {
+ await options.jsDisconnect();
+ } finally {
+ options.clearOptimisticJoin();
+ // If the native call was already gone (orphaned in-call state), no
+ // disconnect event will arrive to clear the snapshot — reconcile with
+ // the plugin so leave always lands in a consistent state, even when
+ // the JS disconnect throws.
+ try {
+ await syncNativeCallStateAfterLeave(
+ options.nativeCall,
+ stateBeforeLeave
+ );
+ } catch (e) {
+ console.error('callkit: post-leave state sync failed', e);
+ }
+ }
},
};
}
diff --git a/apps/web/src/features/channel/Call/LivekitJsCallController.ts b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
index 2ddccb1df3..0e9738e2d0 100644
--- a/apps/web/src/features/channel/Call/LivekitJsCallController.ts
+++ b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
@@ -197,7 +197,15 @@ export function createLivekitJsCallController(
try {
await room.disconnect();
} finally {
- destroyRoom();
+ // Tear down only the session this disconnect captured: a slow
+ // room.disconnect() can settle after the user has rejoined, and
+ // destroying the replacement session would strand a live connection
+ // the UI no longer tracks.
+ if (options.room() === room) {
+ destroyRoom();
+ } else {
+ room.removeAllListeners();
+ }
}
}
diff --git a/apps/web/src/features/channel/Call/use-call.ts b/apps/web/src/features/channel/Call/use-call.ts
index 28c19d96b4..11eadd9117 100644
--- a/apps/web/src/features/channel/Call/use-call.ts
+++ b/apps/web/src/features/channel/Call/use-call.ts
@@ -57,7 +57,21 @@ let activeJoinAttempt: ActiveJoinAttempt | null = null;
// Module-level guard: only one leave can be in flight at a time across all
// useCall() instances. Prevents a user-initiated leave and a concurrent
// CallKit call-ended event from both proceeding to disconnect+leaveMutation.
-let leaveInFlight = false;
+// Tracked as a start timestamp so a leave stuck on a hung network request
+// cannot silently swallow every later leave tap.
+const LEAVE_IN_FLIGHT_STALE_MS = 10_000;
+let leaveInFlightSince: number | null = null;
+
+function isLeaveInFlight(): boolean {
+ if (leaveInFlightSince === null) return false;
+ // Deliberately wall-clock, not performance.now(): the performance timeline
+ // freezes while iOS suspends the webview, so a monotonic delta would keep a
+ // pre-suspension leave "in flight" after resume — the stuck-leave symptom
+ // this latch exists to prevent.
+ const elapsed = Date.now() - leaveInFlightSince;
+ // A backwards wall-clock jump must release the latch, not extend it.
+ return elapsed >= 0 && elapsed < LEAVE_IN_FLIGHT_STALE_MS;
+}
/**
* Hook that orchestrates joining/leaving calls by combining
@@ -84,7 +98,7 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
}
function scheduleAutoRejoin(reason?: DisconnectReason) {
- if (leaveInFlight) return;
+ if (isLeaveInFlight()) return;
if (!shouldAutoRejoin(reason)) {
options?.onLeave?.();
@@ -276,8 +290,9 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
};
async function leaveCall(leaveOptions?: { endNativeCall?: boolean }) {
- if (leaveInFlight) return;
- leaveInFlight = true;
+ if (isLeaveInFlight()) return;
+ const leaveStartedAt = Date.now();
+ leaveInFlightSince = leaveStartedAt;
const id = channelId();
// Detach before disconnect so the RoomEvent.Disconnected handler
// doesn't double-fire onLeave.
@@ -297,7 +312,11 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {
await leaveMutation.mutateAsync(id);
}
} finally {
- leaveInFlight = false;
+ // A staled-out leave releases the guard to a newer attempt; don't let
+ // its late completion clear that newer attempt's claim.
+ if (leaveInFlightSince === leaveStartedAt) {
+ leaveInFlightSince = null;
+ }
}
}
diff --git a/apps/web/src/features/channel/Call/use-callkit.ts b/apps/web/src/features/channel/Call/use-callkit.ts
index c2eac1e0ba..bd888780ea 100644
--- a/apps/web/src/features/channel/Call/use-callkit.ts
+++ b/apps/web/src/features/channel/Call/use-callkit.ts
@@ -128,11 +128,30 @@ function refreshActiveCallQueriesAfterLeave() {
);
}
+// Call setup has legitimate windows where JS already tracks a call but native
+// reports none yet (answered call before the LiveKit session connects, the
+// split-manager wait before a JS-driven join). syncNativeCallState must not
+// mistake those for orphaned state, so every live call-state signal marks
+// activity here and the destructive clear requires a quiet period first.
+const NATIVE_CALL_STATE_CLEAR_QUIET_MS = 30_000;
+let lastNativeCallActivityMs: number | null = null;
+
+function markNativeCallActivity() {
+ lastNativeCallActivityMs = Date.now();
+}
+
+function hasRecentNativeCallActivity(): boolean {
+ if (lastNativeCallActivityMs === null) return false;
+ const elapsed = Date.now() - lastNativeCallActivityMs;
+ return elapsed >= 0 && elapsed < NATIVE_CALL_STATE_CLEAR_QUIET_MS;
+}
+
function applyConnectionState(
nativeCall: NativeCallState,
payload: ConnectionStatePayload
) {
console.info('[callkit] connection state channel message', payload);
+ markNativeCallActivity();
if (
!payload.channelId ||
!payload.callId ||
@@ -347,6 +366,7 @@ export function useCallKitSetup() {
nativeMedia,
source,
});
+ markNativeCallActivity();
nativeCall.setBootstrapChannelId(channelId);
joinChannelCallWhenReady(channelId, nativeMedia).catch((err) =>
console.error('[callkit] joinChannelCallWhenReady failed', err)
@@ -386,6 +406,23 @@ export function useCallKitSetup() {
'call ended',
(payload) => {
console.info('[callkit] call ended event', payload);
+ // Native also emits call-ended for calls that never became the active
+ // one, e.g. declining a second incoming call while already on a call.
+ // Running the leave handler for those would hang up the current call.
+ // Only filter when we positively know the active call: with no
+ // snapshot (fresh webview) the event must still drive the leave.
+ const activeCallId = nativeCall.snapshot()?.callId;
+ if (
+ activeCallId !== undefined &&
+ activeCallId.toLowerCase() !== payload.callId.toLowerCase()
+ ) {
+ console.info('[callkit] ignoring ended call; not the active call', {
+ activeCallId,
+ endedCallId: payload.callId,
+ });
+ refreshActiveCallQueriesAfterLeave();
+ return;
+ }
lastHandledAnsweredCall = undefined;
refreshActiveCallQueriesAfterLeave();
nativeCall.setBootstrapChannelId(null);
@@ -427,6 +464,7 @@ export function useCallKitSetup() {
console.info('[callkit] drawer opened event', {
channelId,
});
+ markNativeCallActivity();
nativeCall.setBootstrapChannelId(channelId);
joinChannelCallWhenReady(channelId, true).catch((err) =>
console.error(
@@ -437,26 +475,127 @@ export function useCallKitSetup() {
}
);
- // Do not let a stale startup drain overwrite live listener state.
- invoke<GetActiveCallStateResponse>('plugin:call-kit|get_active_call_state')
- .then(({ state }) => {
- console.info('[callkit] initial active call state', { state });
- if (!state) return;
- nativeCall.setParticipantIdentities(state.participantIdentities ?? []);
- if (nativeCall.snapshot() !== null) return;
- nativeCall.setBootstrapChannelId(state.channelId);
- nativeCall.setSnapshot({
- channelId: state.channelId,
- callId: state.callId,
- connectionState: state.connectionState,
- isAudioMuted: state.isAudioMuted,
- isVideoMuted: state.isVideoMuted,
- videoOverlayMode: state.videoOverlayMode,
- });
- })
- .catch((err) =>
- console.error('[callkit] get_active_call_state failed', err)
+ syncNativeCallState(nativeCall).catch((err) =>
+ console.error('[callkit] initial native call state sync failed', err)
+ );
+
+ // The webview misses connection-state/call-ended channel events while iOS
+ // has it suspended, leaving whatever call state existed at suspension
+ // frozen in the UI. Re-sync with the plugin every time the app returns to
+ // the foreground so an ended call can never keep rendering as active.
+ const handleVisibilityChange = () => {
+ if (document.visibilityState !== 'visible') return;
+ syncNativeCallState(nativeCall).catch((err) =>
+ console.error('[callkit] foreground native call state sync failed', err)
);
+ };
+ document.addEventListener('visibilitychange', handleVisibilityChange);
+ onCleanup(() =>
+ document.removeEventListener('visibilitychange', handleVisibilityChange)
+ );
+ });
+}
+
+export type NativeCallStateBeforeLeave = {
+ snapshot: NativeCallSnapshot | null;
+ bootstrapChannelId: string | null;
+};
+
+/**
+ * Reconciles JS-side native call state with the plugin's actual state.
+ *
+ * Clears stale in-call state when native has no call (missed call-ended /
+ * disconnect events) and restores the snapshot when native has a call the
+ * webview does not know about (fresh webview during an active call). A live
+ * snapshot for the same call is never overwritten by this point-in-time
+ * query — the connection state watcher stays authoritative while events are
+ * flowing — but a snapshot tracking a different call than native reports is
+ * stale (both an end and an answer were missed) and is replaced.
+ *
+ * By default the destructive clear requires a quiet period (see
+ * hasRecentNativeCallActivity). An explicit leave passes
+ * `clearOnlyIfUnchangedSince` instead: the state observed when the leave began
+ * is exactly what the user asked to leave, so it may be cleared regardless of
+ * age — while state replaced mid-leave (a newer call) is preserved.
+ */
+async function syncNativeCallState(
+ nativeCall: NativeCallState,
+ options?: { clearOnlyIfUnchangedSince: NativeCallStateBeforeLeave }
+): Promise<void> {
+ const { state } = await invoke<GetActiveCallStateResponse>(
+ 'plugin:call-kit|get_active_call_state'
+ );
+ console.info('[callkit] native call state sync', { state });
+ if (!state) {
+ if (
+ nativeCall.snapshot() === null &&
+ nativeCall.bootstrapChannelId() === null
+ ) {
+ return;
+ }
+ const beforeLeave = options?.clearOnlyIfUnchangedSince;
+ if (beforeLeave) {
+ if (
+ nativeCall.snapshot() !== beforeLeave.snapshot ||
+ nativeCall.bootstrapChannelId() !== beforeLeave.bootstrapChannelId
+ ) {
+ console.info(
+ '[callkit] skipping stale-state clear; call state changed during leave'
+ );
+ return;
+ }
+ } else if (hasRecentNativeCallActivity()) {
+ // A call is likely still being established (native briefly reports no
+ // call before its LiveKit session exists); events will settle the state.
+ console.info(
+ '[callkit] skipping stale-state clear; call state changed recently'
+ );
+ return;
+ }
+ console.info(
+ '[callkit] clearing stale in-call state; native has no active call'
+ );
+ nativeCall.setBootstrapChannelId(null);
+ nativeCall.setParticipantIdentities([]);
+ nativeCall.setSnapshot(null);
+ refreshActiveCallQueriesAfterLeave();
+ return;
+ }
+ markNativeCallActivity();
+ nativeCall.setParticipantIdentities(state.participantIdentities ?? []);
+ const currentSnapshot = nativeCall.snapshot();
+ if (
+ currentSnapshot !== null &&
+ currentSnapshot.callId.toLowerCase() === state.callId.toLowerCase()
+ ) {
+ return;
+ }
+ nativeCall.setBootstrapChannelId(state.channelId);
+ nativeCall.setSnapshot({
+ channelId: state.channelId,
+ callId: state.callId,
+ connectionState: state.connectionState,
+ isAudioMuted: state.isAudioMuted,
+ isVideoMuted: state.isVideoMuted,
+ videoOverlayMode: state.videoOverlayMode,
+ });
+}
+
+/**
+ * Post-leave safety net: reconcile JS state with the plugin so a leave always
+ * lands in a consistent state, even when the native call was already gone and
+ * no disconnect event will ever arrive (e.g. state orphaned while the app was
+ * suspended). `stateBeforeLeave` is the call state observed when the leave
+ * began — clearing is scoped to exactly that state, bypassing the quiet-period
+ * gate without risking a concurrently-established call's state.
+ */
+export async function syncNativeCallStateAfterLeave(
+ nativeCall: NativeCallState,
+ stateBeforeLeave: NativeCallStateBeforeLeave
+): Promise<void> {
+ if (!isNativeIosCallKitEnabled()) return;
+ await syncNativeCallState(nativeCall, {
+ clearOnlyIfUnchangedSince: stateBeforeLeave,
});
}
@@ -722,6 +861,7 @@ export async function startNativeCallKitOutgoingCall(
channelTitle: args.channelTitle,
});
await invoke('plugin:call-kit|start_outgoing_call', args);
+ markNativeCallActivity();
nativeCall.setBootstrapChannelId(args.channelId);
}
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index c87fe1d784..401566c268 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -771,6 +771,7 @@ dependencies = [
"lru",
"maybe_send",
"postcard",
+ "predicate-index",
"serde",
"serde_json",
"sha2",
@@ -783,6 +784,7 @@ version = "0.1.0"
dependencies = [
"cache-core",
"maybe_send",
+ "predicate-index",
"thiserror 2.0.18",
"turso-opfs",
"turso_core",
@@ -4571,6 +4573,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+[[package]]
+name = "predicate-index"
+version = "0.1.0"
+dependencies = [
+ "chrono",
+ "serde",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "prettyplease"
version = "0.2.37"
diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift
index 85974cdfa8..d64f8c9437 100644
--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift
+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift
@@ -72,6 +72,9 @@ class CallKitPlugin: Plugin, @unchecked Sendable {
}
return self.getMediaSession()
},
+ existingMediaSession: { [weak self] in
+ self?.mediaSession
+ },
onVoipTokenUpdated: { [weak self] token in
print("[CallKit] Emitting voip-token-updated event tokenLength=\(token.count)")
self?.trigger("voip-token-updated", data: ["token": token])
diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift b/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
index 03d3d72cab..e4c06aefeb 100644
--- a/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
+++ b/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift
@@ -8,6 +8,7 @@ private let enableNativeLiveKitAnswer = true
/// PushKit + CallKit coordinator. Mutable state is main-queue only.
final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistryDelegate, @unchecked Sendable {
private let mediaSessionProvider: () -> NativeLiveKitCallSession
+ private let existingMediaSession: () -> NativeLiveKitCallSession?
private let onVoipTokenUpdated: (String) -> Void
private let onCallAnswered: (String, Bool) -> Void
private let onCallEnded: (String) -> Void
@@ -31,16 +32,40 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
init(
mediaSession: @escaping () -> NativeLiveKitCallSession,
+ existingMediaSession: @escaping () -> NativeLiveKitCallSession?,
onVoipTokenUpdated: @escaping (String) -> Void,
onCallAnswered: @escaping (String, Bool) -> Void,
onCallEnded: @escaping (String) -> Void
) {
self.mediaSessionProvider = mediaSession
+ self.existingMediaSession = existingMediaSession
self.onVoipTokenUpdated = onVoipTokenUpdated
self.onCallAnswered = onCallAnswered
self.onCallEnded = onCallEnded
}
+ /// UUID of the call the media session is currently running, independent of
+ /// this coordinator's own call pointers. Ending a call must key off the
+ /// session itself so a corrupted/cleared `activeCallUUID` can never orphan
+ /// a live LiveKit room (stuck drawer, call audio that cannot be hung up).
+ /// Main-queue only, like the rest of the coordinator's state: the plugin's
+ /// `mediaSession` property and the session's snapshot are main-confined.
+ private func mediaSessionCallUUID() -> UUID? {
+ guard let snapshot = existingMediaSession()?.currentSnapshot() else { return nil }
+ return UUID(uuidString: snapshot.callId)
+ }
+
+ private func isNativeMediaCall(_ uuid: UUID) -> Bool {
+ activeNativeMediaUUID == uuid || mediaSessionCallUUID() == uuid
+ }
+
+ /// Whether any native media is running, regardless of which call the
+ /// coordinator's pointer names. Cleanup and audio hand-off paths must reach
+ /// a live session even when the pointer was cleared by an earlier failure.
+ private func hasActiveNativeMedia() -> Bool {
+ activeNativeMediaUUID != nil || mediaSessionCallUUID() != nil
+ }
+
func load() {
print("[CallKit] Loading PushKit/CallKit coordinator")
let config = makeProviderConfiguration()
@@ -89,6 +114,24 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
let isAnsweringPendingIncomingCall = activeCallUUID == uuid
&& pendingCalls[uuid] != nil
&& !outgoingCallUUIDs.contains(uuid)
+
+ // JS can re-request the call that is already running (e.g. a webview
+ // reload raced the active-call snapshot and the join flow fetched a
+ // token for the same call). Requesting a duplicate CXStartCallAction
+ // would fail and its cleanup would orphan the live media session, so
+ // report success and resync the call pointers to the running call.
+ let sessionCallUUID = mediaSessionCallUUID()
+ if !isAnsweringPendingIncomingCall,
+ activeCallUUID == uuid || sessionCallUUID == uuid {
+ print("[CallKit] startOutgoingCall ignored; call already running uuid=\(uuid.uuidString) channelId=\(channelId)")
+ activeCallUUID = uuid
+ if sessionCallUUID == uuid {
+ activeNativeMediaUUID = uuid
+ }
+ completion(nil)
+ return
+ }
+
pendingCalls[uuid] = PendingCallInfo(
channelId: channelId,
channelName: displayTitle,
@@ -157,12 +200,23 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
}
func endActiveCall(completion: @escaping () -> Void) {
- guard let uuid = activeCallUUID else {
- print("[CallKit] endActiveCall requested with no active CallKit UUID")
+ // Fall back to the media session's own call so a desynced/cleared
+ // activeCallUUID cannot leave a live room (and its drawer) unreachable
+ // from the app's leave button.
+ let sessionCallUUID = mediaSessionCallUUID()
+ guard let uuid = activeCallUUID ?? sessionCallUUID else {
+ print("[CallKit] endActiveCall requested with no active CallKit UUID or media session")
completion()
return
}
+ // If the pointer and the session disagree, end the session's call too —
+ // the pointer alone must never strand a live room.
+ if let sessionCallUUID, sessionCallUUID != uuid {
+ print("[CallKit] endActiveCall also ending media session call uuid=\(sessionCallUUID.uuidString)")
+ requestEndCall(uuid: sessionCallUUID)
+ }
+
print("[CallKit] endActiveCall requesting CXEndCallAction uuid=\(uuid.uuidString)")
appendPendingEndCallCompletion(uuid: uuid, completion)
requestEndCall(uuid: uuid) { [weak self] error in
@@ -173,14 +227,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
self.onMain {
if error != nil {
print("[CallKit] CXEndCallAction failed; clearing local state uuid=\(uuid.uuidString)")
- let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid
- self.clearCallState(uuid: uuid)
- if shouldDisconnectNativeMedia {
- let mediaSession = self.mediaSessionProvider()
- Task {
- await mediaSession.disconnect()
- }
- }
+ self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)
return
}
@@ -188,15 +235,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
guard let self else { return }
guard self.pendingEndCallCompletions[uuid]?.isEmpty == false else { return }
print("[CallKit] Timed out waiting for CXEndCallAction provider callback; completing JS endActiveCall uuid=\(uuid.uuidString)")
- let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid
- self.completePendingEndCall(uuid: uuid)
- self.clearCallState(uuid: uuid)
- if shouldDisconnectNativeMedia {
- let mediaSession = self.mediaSessionProvider()
- Task {
- await mediaSession.disconnect()
- }
- }
+ self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)
}
}
}
@@ -208,28 +247,31 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
guard let self, error != nil else { return }
self.onMain {
print("[CallKit] requestEndCall failed; disconnecting media session uuid=\(uuid.uuidString)")
- let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid
- self.clearCallState(uuid: uuid)
- if shouldDisconnectNativeMedia {
- let mediaSession = self.mediaSessionProvider()
- Task {
- await mediaSession.disconnect()
- }
- }
+ self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)
+ }
+ }
+ }
+
+ private func clearCallStateAndDisconnectMediaIfNeeded(uuid: UUID) {
+ let shouldDisconnectNativeMedia = isNativeMediaCall(uuid)
+ clearCallState(uuid: uuid)
+ if shouldDisconnectNativeMedia {
+ let mediaSession = mediaSessionProvider()
+ Task {
+ await mediaSession.disconnect()
}
}
}
func handleApplicationWillTerminate() {
stopAllRingStatePolling()
- guard let uuid = activeCallUUID else {
+ guard let uuid = activeCallUUID ?? mediaSessionCallUUID() else {
print("[CallKit] Application terminating with no active CallKit call")
return
}
print("[CallKit] Application terminating with active CallKit call uuid=\(uuid.uuidString)")
- let shouldDisconnectNativeMedia = activeNativeMediaUUID == uuid
- if shouldDisconnectNativeMedia {
+ if hasActiveNativeMedia() {
mediaSessionProvider().disconnectForAppTermination()
}
provider.reportCall(with: uuid, endedAt: Date(), reason: .remoteEnded)
@@ -296,8 +338,10 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
return
}
- // Copy keys before mutating; Dictionary.Keys is a live view.
- for staleUUID in Array(pendingCalls.keys) where staleUUID != uuid {
+ // Copy keys before mutating; Dictionary.Keys is a live view. Never
+ // sweep the active call: only stale *ringing* calls may be failed.
+ for staleUUID in Array(pendingCalls.keys)
+ where staleUUID != uuid && staleUUID != activeCallUUID {
print("[CallKit] Marking stale pending call failed uuid=\(staleUUID.uuidString)")
provider.reportCall(with: staleUUID, endedAt: nil, reason: .failed)
pendingCalls.removeValue(forKey: staleUUID)
@@ -316,7 +360,17 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
pendingCallTokens.removeValue(forKey: uuid)
print("[CallKit] VoIP payload missing native connection credentials; lock-screen answer will not connect natively")
}
- activeCallUUID = uuid
+ // A ring must not displace an active call's UUID: every leave path keys
+ // off activeCallUUID, and the ring's later cleanup would nil it, leaving
+ // the active call impossible to end from the app. The ringing call
+ // becomes active only when it is answered.
+ if let activeCallUUID {
+ if activeCallUUID != uuid {
+ print("[CallKit] Incoming call while another call is active; keeping active uuid=\(activeCallUUID.uuidString) ringing uuid=\(uuid.uuidString)")
+ }
+ } else {
+ activeCallUUID = uuid
+ }
let update = CXCallUpdate()
update.remoteHandle = CXHandle(type: .generic, value: channelName ?? channelId)
@@ -355,7 +409,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
outgoingCallUUIDs.removeAll()
reportedConnectedOutgoingCallUUIDs.removeAll()
completeAllPendingEndCalls()
- if activeNativeMediaUUID != nil {
+ if hasActiveNativeMedia() {
activeNativeMediaUUID = nil
let mediaSession = mediaSessionProvider()
Task {
@@ -377,6 +431,11 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
activeCallUUID = uuid
activeNativeMediaUUID = uuid
+ // Consume the pending entries: they exist to hand the call info to this
+ // action. Leaving them in `pendingCalls` would let the stale-ring sweep
+ // in `didReceiveIncomingPushWith` fail this now-active outgoing call.
+ pendingCalls.removeValue(forKey: uuid)
+ pendingCallTokens.removeValue(forKey: uuid)
provider.reportOutgoingCall(with: uuid, startedConnectingAt: Date())
mediaSessionProvider().prepareForCallKitAudio()
action.fulfill()
@@ -384,9 +443,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
Task { @MainActor [weak self] in
guard let self else { return }
- guard self.canStartNativeMediaConnect(uuid: uuid),
- self.pendingCalls[uuid] != nil,
- self.pendingCallTokens[uuid] != nil else {
+ guard self.canStartNativeMediaConnect(uuid: uuid) else {
print("[CallKit] Skipping outgoing native LiveKit connect; call no longer active uuid=\(uuid.uuidString)")
return
}
@@ -429,7 +486,13 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
pendingAnsweredCall = (channelId: channelId, nativeMedia: shouldConnectNatively)
- // Keep activeCallUUID so JS can still request CXEndCallAction.
+ // The answered call is now the active call (a ring no longer claims
+ // activeCallUUID on push), so JS can request CXEndCallAction for it.
+ // Deliberately unconditional, unlike the ring path: answering displaces
+ // any previous active call — the media session switches to the answered
+ // call, and with "End & Accept" the old call's CXEndCallAction can
+ // arrive in either order relative to this answer.
+ activeCallUUID = answeredUUID
pendingCalls.removeValue(forKey: answeredUUID)
pendingCallTokens.removeValue(forKey: answeredUUID)
@@ -470,7 +533,10 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
print("[CallKit] CXEndCallAction received uuid=\(callId)")
onCallEnded(callId)
- if activeNativeMediaUUID == action.callUUID {
+ // Keyed off the session as well as activeNativeMediaUUID: if the
+ // pointer was cleared by an earlier failure, ending the call must still
+ // tear down the room it is running.
+ if isNativeMediaCall(action.callUUID) {
let mediaSession = mediaSessionProvider()
Task {
await mediaSession.disconnect()
@@ -484,7 +550,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
print("[CallKit] CXSetMutedCallAction received uuid=\(action.callUUID.uuidString) muted=\(action.isMuted)")
- if activeNativeMediaUUID == action.callUUID {
+ if isNativeMediaCall(action.callUUID) {
mediaSessionProvider().setAudioMuted(action.isMuted)
}
action.fulfill()
@@ -493,7 +559,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {
isCallKitAudioSessionActive = true
- guard activeNativeMediaUUID != nil else {
+ guard hasActiveNativeMedia() else {
print("[CallKit] AVAudioSession activated by CallKit; native media not active yet")
return
}
@@ -503,7 +569,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
isCallKitAudioSessionActive = false
- guard activeNativeMediaUUID != nil else {
+ guard hasActiveNativeMedia() else {
print("[CallKit] AVAudioSession deactivated by CallKit; no native media session active")
return
}
@@ -521,11 +587,15 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
stopRingStatePolling(uuid: uuid)
pendingCalls.removeValue(forKey: uuid)
pendingCallTokens.removeValue(forKey: uuid)
- if activeCallUUID == uuid { activeCallUUID = nil }
+ if activeCallUUID == uuid {
+ activeCallUUID = nil
+ // The pending answered call belongs to the active call; clearing an
+ // unrelated ring (e.g. a declined second call) must not drop it.
+ pendingAnsweredCall = nil
+ }
if activeNativeMediaUUID == uuid { activeNativeMediaUUID = nil }
outgoingCallUUIDs.remove(uuid)
reportedConnectedOutgoingCallUUIDs.remove(uuid)
- pendingAnsweredCall = nil
completePendingEndCall(uuid: uuid)
}
@@ -580,7 +650,9 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
stopRingStatePolling(uuid: uuid)
// A late in-flight response can land after the ring resolved locally
// (answered/declined/displaced) — pendingCalls is already empty then.
- guard pendingCalls[uuid] != nil, activeCallUUID == uuid else {
+ // A ring that arrived during an active call never owns activeCallUUID,
+ // so pendingCalls alone decides whether it is still ringing.
+ guard pendingCalls[uuid] != nil else {
print("[CallKit] Ignoring remote ring resolution; call no longer pending uuid=\(uuid.uuidString)")
return
}
@@ -594,7 +666,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr
}
private func activateNativeMediaAudioIfNeeded(reason: String) {
- guard activeNativeMediaUUID != nil else { return }
+ guard hasActiveNativeMedia() else { return }
guard isCallKitAudioSessionActive else {
print("[CallKit] Native media waiting for CallKit AVAudioSession activation reason=\(reason)")
return