Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calls): make leaving a call final and clean up stranded calls (#8500)
Peter Chinman70b847b81460
diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsxindex 7bcdb180ed..af3941ef84 100644--- a/apps/web/src/features/channel/Call/CallContext.tsx+++ b/apps/web/src/features/channel/Call/CallContext.tsx@@ -1669,7 +1669,7 @@ function createCallState() {unregister();};},- onJoined: (call) => {+ onJoined: (call, source) => {const answeringUserId = userId();if (answeringUserId && call.callId) {publishCallResolution({@@ -1682,13 +1682,16 @@ function createCallState() {analytics.track('call_action', {action: 'joined',channelId: call.channelId,+ callId: call.callId ?? undefined,+ trigger: source,});},- onLeft: (channelId) =>+ onLeft: (call, reason) =>analytics.track('call_action', {action: 'left',- channelId,- leaveReason: 'user_initiated',+ channelId: call.channelId,+ callId: call.callId ?? undefined,+ leaveReason: reason,}),reportError: (error) => console.error('call lifecycle failed', error),});diff --git a/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx b/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsxindex 7c1bf7b7b5..4e77a16111 100644--- a/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx+++ b/apps/web/src/features/channel/Call/ChannelCallAutoJoin.tsx@@ -58,7 +58,7 @@ export function ChannelCallAutoJoin(props: {}call- .joinCall()+ .joinCall('deep_link').catch((e) => console.error('Auto-join call failed', e)).finally(() => props.onHandled());});diff --git a/apps/web/src/features/channel/Call/call-lifecycle.ts b/apps/web/src/features/channel/Call/call-lifecycle.tsindex 88c9612868..a2d7d50f31 100644--- a/apps/web/src/features/channel/Call/call-lifecycle.ts+++ b/apps/web/src/features/channel/Call/call-lifecycle.ts@@ -20,9 +20,35 @@ import { LK_DISCONNECT_REASON } from './livekit-loader';export const JOIN_TIMEOUT_MS = 15_000;export const LEAVE_TIMEOUT_MS = 10_000;+/**+ * How many times a native session still reporting a call the user left is+ * ended before the lifecycle stops trying, so a native layer that never+ * reports the end cannot spin the leave loop.+ */+const MAX_ENDED_CALL_RELEASES = 2;const ALREADY_IN_CALL_MESSAGE ="You're already in another call. Leave your current call before joining a new one.";export type CallIdentity = { channelId: string; callId: string | null };+/** What started a join, recorded with the joined event. */+export type JoinSource =+ /** A Join control the user pressed. */+ | 'user'+ /** A `join_call` deep link: an answered ring or a notification tap. */+ | 'deep_link'+ /** A native session restored while its old leave was settling. */+ | 'restore'+ /** Recovery after the transport dropped. */+ | 'auto_rejoin';+/** Why a leave ran, recorded with the left event. */+export type LeaveReason =+ /** The user pressed Leave in the app. */+ | 'user_initiated'+ /** The native call ended: its End button, CallKit, or the server. */+ | 'native_ended'+ /** Cleanup for a join that native cancelled before it connected. */+ | 'join_cancelled'+ /** A native session still reporting a call the user already left. */+ | 'stale_native_session';function sameCall(first: CallIdentity | undefined, second: CallIdentity) {return (@@ -42,12 +68,16 @@ function deferred<T = void>() {}type Join = ReturnType<typeof deferred<void>> & {channelId: string;+ source: JoinSource;onJoin?: () => void;restoredCall?: CallIdentity;};type LeaveResult = { callEnded: boolean } | void;type Leave = ReturnType<typeof deferred<LeaveResult>> & {channelId: string;+ /** The call being left, captured when the leave was requested. */+ call: CallIdentity;+ reason: LeaveReason;startedAt: number;options?: CallSessionDisconnectOptions;skipServerLeave?: boolean;@@ -180,12 +210,28 @@ export function createCallLifecycle(options: {disconnected: (reason?: DisconnectReason) => void,nativeEnded: () => void) => Cleanup;- onJoined: (call: CallIdentity) => void;- onLeft: (channelId: string) => void;+ onJoined: (call: CallIdentity, source: JoinSource) => void;+ onLeft: (call: CallIdentity, reason: LeaveReason) => void;reportError: (error: unknown) => void;}) {let disposed = false;const pendingServerLeaves = new Set<Promise<unknown>>();+ // Calls this user left, by lowercase call id. A native session that still+ // reports one is a leftover to end, never a session to adopt or restore;+ // only an explicit join of the channel lets its call back in.+ const endedCalls = new Map<string, { channelId: string; releases: number }>();+ function markEnded(call: CallIdentity | undefined) {+ const key = call?.callId?.toLowerCase();+ if (!call || !key || endedCalls.has(key)) return;+ endedCalls.set(key, { channelId: call.channelId, releases: 0 });+ }+ function forgetEndedCalls(channelId: string) {+ for (const [key, ended] of endedCalls) {+ if (ended.channelId === channelId) endedCalls.delete(key);+ }+ }+ const endedCall = (call: CallIdentity) =>+ call.callId ? endedCalls.get(call.callId.toLowerCase()) : undefined;async function leaveServer(channelId: string) {const pending = options.leave(channelId);pendingServerLeaves.add(pending);@@ -330,7 +376,7 @@ export function createCallLifecycle(options: {try {const current = machine.getState();if (current.t === 'active' && sameCall(current.call, connected))- options.onJoined(connected);+ options.onJoined(connected, request.source);} catch (error) {options.reportError(error);}@@ -363,10 +409,7 @@ export function createCallLifecycle(options: {},() => {if (active)- fireAndForget(- leaveEndedNativeSession(call.channelId),- 'channel-call'- );+ fireAndForget(leaveEndedNativeCall(call), 'channel-call');});return () => {@@ -418,7 +461,7 @@ export function createCallLifecycle(options: {return;}try {- await join(attempt.channelId);+ await startJoin(attempt.channelId, 'auto_rejoin');} catch (error) {options.reportError(error);}@@ -469,10 +512,17 @@ export function createCallLifecycle(options: {else request.resolve(result);dispatch({ t: 'finish' });};- const timeout = setTimeout(- () => finish(new Error('Leaving call timed out')),- LEAVE_TIMEOUT_MS- );+ let serverLeave: Promise<LeaveResult> | undefined;+ const leaveServerOnce = () =>+ (serverLeave ??= leaveServer(request.channelId));+ const timeout = setTimeout(() => {+ // Media teardown hung, but the user still left: release the+ // membership now, so the server stops holding them in the call and+ // a later join waits for this leave instead of racing it.+ if (!request.skipServerLeave)+ fireAndForget(leaveServerOnce(), 'channel-call');+ finish(new Error('Leaving call timed out'));+ }, LEAVE_TIMEOUT_MS);async function disconnect() {// A hangup reaches the server before media teardown: the last// participant's RTC departure archives the call, and a later leave@@ -480,18 +530,18 @@ export function createCallLifecycle(options: {// to a restored session or rejoin, so its leave waits.const releasing =!request.skipServerLeave && request.options?.endNativeCall !== false- ? leaveServer(request.channelId)+ ? leaveServerOnce(): undefined;let result: LeaveResult = undefined;try {try {await options.disconnect(request.options);if (!active) return;- options.onLeft(request.channelId);+ options.onLeft(request.call, request.reason);} finally {if (releasing) result = await releasing;else if (active && !request.skipServerLeave)- result = await leaveServer(request.channelId);+ result = await leaveServerOnce();}finish(undefined, result);} catch (error) {@@ -513,7 +563,21 @@ export function createCallLifecycle(options: {},});- function join(channelId: string, onJoin?: () => void): Promise<void> {+ /** Joins at the user's request, which lets a call they left back in. */+ function join(+ channelId: string,+ onJoin?: () => void,+ source: JoinSource = 'user'+ ): Promise<void> {+ return startJoin(channelId, source, onJoin, true);+ }++ function startJoin(+ channelId: string,+ source: JoinSource,+ onJoin?: () => void,+ explicit = false+ ): Promise<void> {if (disposed) return Promise.reject(new Error('Call lifecycle disposed'));const state = machine.getState();if (state.t === 'joining')@@ -539,14 +603,41 @@ export function createCallLifecycle(options: {return Promise.reject(error);}}- const request: Join = { ...deferred(), channelId, onJoin };+ // Only an accepted join lets a left call back in: a refused one (still+ // leaving, joining elsewhere) must keep it out once the leave settles.+ if (explicit) forgetEndedCalls(channelId);+ const request: Join = { ...deferred(), channelId, source, onJoin };machine.dispatch({ t: 'join', request });return request.promise;}+ /** The call a leave of this channel ends, as far as the lifecycle knows. */+ function callInChannel(channelId: string): CallIdentity {+ const call = match(machine.getState())+ .with({ t: 'active' }, ({ call }) => call)+ .with({ t: 'retry-wait' }, { t: 'checking' }, ({ attempt }) => attempt)+ .with({ t: 'leaving' }, ({ request }) => request.call)+ .otherwise(() => options.currentCall());+ return {+ channelId,+ callId: call?.channelId === channelId ? call.callId : null,+ };+ }++ /** Leaves at the user's request: the call is over for this user. */function leave(channelId: string,leaveOptions?: CallSessionDisconnectOptions+ ): Promise<LeaveResult> {+ const call = callInChannel(channelId);+ markEnded(call);+ return requestLeave(call, 'user_initiated', leaveOptions);+ }++ function requestLeave(+ call: CallIdentity,+ reason: LeaveReason,+ leaveOptions?: CallSessionDisconnectOptions): Promise<LeaveResult> {if (disposed) return Promise.reject(new Error('Call lifecycle disposed'));const state = machine.getState();@@ -558,17 +649,20 @@ export function createCallLifecycle(options: {return state.request.promise;machine.dispatch({ t: 'finish' });}- return startLeave(channelId, leaveOptions);+ return startLeave(call, reason, leaveOptions);}function startLeave(- channelId: string,+ call: CallIdentity,+ reason: LeaveReason,leaveOptions?: CallSessionDisconnectOptions,skipServerLeave = false) {const request: Leave = {...deferred<LeaveResult>(),- channelId,+ channelId: call.channelId,+ call,+ reason,startedAt: Date.now(),options: leaveOptions,skipServerLeave,@@ -577,14 +671,27 @@ export function createCallLifecycle(options: {return request.promise;}- async function leaveEndedNativeSession(channelId: string) {+ async function leaveEndedNativeSession(+ channelId: string,+ reason: LeaveReason+ ) {try {- await leave(channelId, { endNativeCall: false });+ await requestLeave(callInChannel(channelId), reason, {+ endNativeCall: false,+ });} catch (error) {options.reportError(error);}}+ async function leaveEndedNativeCall(call: CallIdentity) {+ // Native ended this call (its End button, CallKit, or the server), so it+ // is over for this user: a snapshot that still reports it afterwards is a+ // leftover to end, not a session to restore.+ markEnded(call);+ await leaveEndedNativeSession(call.channelId, 'native_ended');+ }+async function releaseStaleNativeSession(call: CallIdentity,skipServerLeave = false@@ -597,7 +704,8 @@ export function createCallLifecycle(options: {}try {await startLeave(- call.channelId,+ call,+ 'stale_native_session',{endNativeCall: sameCall(current, call),},@@ -608,10 +716,38 @@ export function createCallLifecycle(options: {}}+ function releaseEndedNativeSession(call: CallIdentity) {+ const ended = endedCall(call);+ // A join or leave in flight owns the session, and a failed join's cleanup+ // must finish; the native binding re-reads the snapshot when they settle.+ if (!ended || machine.getState().t !== 'idle') return;+ if (ended.releases >= MAX_ENDED_CALL_RELEASES) return;+ ended.releases += 1;+ options.reportError(+ new Error(`Native call ${call.callId} still active after it ended`)+ );+ // The server membership is already gone, so only the native call ends.+ fireAndForget(endLeftoverNativeSession(call), 'channel-call');+ }++ async function endLeftoverNativeSession(call: CallIdentity) {+ try {+ await startLeave(+ call,+ 'stale_native_session',+ { endNativeCall: true },+ true+ );+ } catch (error) {+ options.reportError(error);+ }+ }+async function restoreAfterLeave(call: CallIdentity) {const request: Join = {...deferred(),channelId: call.channelId,+ source: 'restore',restoredCall: call,};machine.dispatch({ t: 'join', request });@@ -630,6 +766,10 @@ export function createCallLifecycle(options: {syncSession: (call: CallIdentity | undefined) => {if (disposed) return;if (call) {+ if (endedCall(call)) {+ releaseEndedNativeSession(call);+ return;+ }const state = machine.getState();if (state.t === 'leaving' &&@@ -650,7 +790,7 @@ export function createCallLifecycle(options: {// Requesting a token can register a server participant before media// connects. Clean up unless a new session supersedes this attempt.fireAndForget(- leaveEndedNativeSession(state.request.channelId),+ leaveEndedNativeSession(state.request.channelId, 'join_cancelled'),'channel-call');return;diff --git a/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.tsindex 80312c006b..b7f351186d 100644--- a/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts+++ b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts@@ -217,7 +217,7 @@ describe('shared call lifecycle', () => {expect(ports.onJoined).not.toHaveBeenCalled();connection.resolve();await promise;- expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call);+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call, 'user');expect(ports.watch).toHaveBeenCalledOnce();});@@ -238,7 +238,7 @@ describe('shared call lifecycle', () => {expect(ports.requestToken).not.toHaveBeenCalled();expect(ports.connect).not.toHaveBeenCalled();expect(lifecycle.getState()).toEqual({ t: 'active', call });- expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call);+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(call, 'user');expect(vi.getTimerCount()).toBe(0);});@@ -598,6 +598,32 @@ describe('shared call lifecycle', () => {});+ it('still leaves the server when media teardown outlasts the leave timeout', async () => {+ const { lifecycle, ports, join } = setup();+ await join();+ ports.disconnect.mockReturnValueOnce(new Promise(() => {}));+ const failed = expect(lifecycle.leave(call.channelId)).rejects.toThrow(+ 'timed out'+ );+ await vi.advanceTimersByTimeAsync(LEAVE_TIMEOUT_MS);+ await failed;+ expect(ports.leave).toHaveBeenCalledExactlyOnceWith(call.channelId);+ expect(lifecycle.getState().t).toBe('idle');+ });++ it('records why each leave ran and which call it left', async () => {+ const { lifecycle, ports, join, nativeEnd } = setup();+ await join();+ await lifecycle.leave(call.channelId);+ await join();+ nativeEnd();+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.onLeft.mock.calls).toEqual([+ [call, 'user_initiated'],+ [call, 'native_ended'],+ ]);+ });+it('times out a hung leave and permits a new join', async () => {const { lifecycle, ports, join } = setup();ports.disconnect.mockReturnValueOnce(new Promise(() => {}));diff --git a/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts b/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.tsindex 9c6fdca831..3e394a1b0a 100644--- a/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts+++ b/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts@@ -3,7 +3,12 @@ import { useCallKitSetup } from '../use-callkit';const bridge = vi.hoisted(() => ({watchers: new Map<string, (payload: unknown) => void>(),- pending: null as { channelId: string; nativeMedia: boolean } | null,+ pending: null as {+ channelId: string;+ nativeMedia: boolean;+ callId?: string;+ answeredAtMs?: number;+ } | null,cleanups: [] as (() => void)[],open: vi.fn(async () => {}),join: vi.fn(async () => {}),@@ -141,4 +146,50 @@ describe('native answered-call recovery', () => {expect(bridge.open).toHaveBeenCalledTimes(2);expect(bridge.pending).toBeNull();});++ it('handles two distinct answers in the same channel, but each only once', async () => {+ useCallKitSetup();+ await settle();+ const answered = bridge.watchers.get(+ 'plugin:call-kit|watch_call_answered'+ )!;+ const first = {+ channelId: 'channel-1',+ nativeMedia: false,+ callId: 'CALL-1',+ answeredAtMs: Date.now(),+ };+ answered(first);+ answered({ ...first });+ answered({ ...first, callId: 'CALL-2' });+ await settle();+ expect(bridge.join).toHaveBeenCalledTimes(2);+ });++ it('drops an answer replayed long after CallKit fulfilled it', async () => {+ useCallKitSetup();+ await settle();+ // Answered, then the webview stayed suspended past the replay window.+ bridge.pending = {+ channelId: 'channel-1',+ nativeMedia: false,+ callId: 'call-1',+ answeredAtMs: Date.now() - 61_000,+ };+ resume();+ await settle();+ expect(bridge.join).not.toHaveBeenCalled();+ expect(bridge.open).not.toHaveBeenCalled();+ expect(bridge.pending).toBeNull();++ bridge.pending = {+ channelId: 'channel-2',+ nativeMedia: false,+ callId: 'call-2',+ answeredAtMs: Date.now() - 5_000,+ };+ resume();+ await settle();+ expect(bridge.join).toHaveBeenCalledExactlyOnceWith('channel-2');+ });});diff --git a/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.ts b/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.tsindex 7795f35be4..d552b1e132 100644--- a/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.ts+++ b/apps/web/src/features/channel/Call/tests/native-call-lifecycle.test.ts@@ -46,6 +46,7 @@ function setup(initial: NativeCallSnapshot | null = first) {const native = createNativeCallState();native.setSnapshot(initial);const unwatch = vi.fn();+ let nativeEnded: () => void = () => {};const ports = {shouldRequestToken: vi.fn((_channelId: string) => true),requestToken: vi.fn(async () => ({@@ -73,7 +74,10 @@ function setup(initial: NativeCallSnapshot | null = first) {beginJoin: vi.fn(),rollbackJoin: vi.fn(),setError: vi.fn(),- watch: vi.fn(() => unwatch),+ watch: vi.fn((_call, _onDisconnect, onNativeEnd: () => void) => {+ nativeEnded = onNativeEnd;+ return unwatch;+ }),onJoined: vi.fn(),onLeft: vi.fn(),reportError: vi.fn(),@@ -85,7 +89,15 @@ function setup(initial: NativeCallSnapshot | null = first) {lifecycle.dispose();dispose();});- return { native, lifecycle, ports, unwatch, unbind, dispose };+ return {+ native,+ lifecycle,+ ports,+ unwatch,+ unbind,+ dispose,+ nativeEnd: () => nativeEnded(),+ };});}@@ -172,6 +184,89 @@ describe('native snapshot events and call ownership', () => {});+ it.each(['leave', 'native end'] as const)(+ 'never rejoins a call the user left by %s while native still reports it',+ async (exit) => {+ const { native, lifecycle, ports, nativeEnd } = setup();+ // Native keeps reporting the call it was asked to end.+ ports.disconnect.mockImplementation(async () => {});+ const pending = deferred();+ ports.leave.mockReturnValueOnce(pending.promise);+ const leaving =+ exit === 'leave' ? lifecycle.leave(first.channelId) : undefined;+ if (exit === 'native end') nativeEnd();+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState().t).toBe('leaving');+ // The incident: a fresh snapshot of the same call arrives mid-leave.+ native.setSnapshot({ ...first, callId: first.callId.toUpperCase() });+ pending.resolve();+ await leaving;+ await vi.advanceTimersByTimeAsync(1000);+ expect(ports.requestToken).not.toHaveBeenCalled();+ expect(ports.onJoined).not.toHaveBeenCalled();+ expect(lifecycle.getState().t).toBe('idle');+ // The leftover native call is ended, without a second server leave, and+ // a native layer that never reports the end can't loop the release.+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(ports.disconnect.mock.calls.slice(1)).toEqual([+ [{ endNativeCall: true }],+ [{ endNativeCall: true }],+ ]);+ expect(ports.onLeft).toHaveBeenLastCalledWith(+ identity(first),+ 'stale_native_session'+ );+ }+ );++ it('keeps a left call out after a join refused while the leave was in flight', async () => {+ const { lifecycle, ports } = setup();+ ports.disconnect.mockImplementation(async () => {});+ const pending = deferred();+ ports.leave.mockReturnValueOnce(pending.promise);+ const leaving = lifecycle.leave(first.channelId);+ await vi.advanceTimersByTimeAsync(0);+ await expect(lifecycle.join(first.channelId)).rejects.toThrow(+ 'still leaving'+ );+ pending.resolve();+ await leaving;+ await vi.advanceTimersByTimeAsync(0);+ expect(lifecycle.getState().t).toBe('idle');+ expect(ports.disconnect).toHaveBeenLastCalledWith({ endNativeCall: true });+ expect(ports.onJoined).not.toHaveBeenCalled();+ });++ it('ends a leftover native call once when native confirms the end', async () => {+ const { native, lifecycle, ports } = setup();+ ports.disconnect.mockImplementationOnce(async () => {});+ await lifecycle.leave(first.channelId);+ await vi.advanceTimersByTimeAsync(0);+ expect(ports.disconnect).toHaveBeenLastCalledWith({ endNativeCall: true });+ expect(native.snapshot()).toBeNull();+ expect(ports.disconnect).toHaveBeenCalledTimes(2);+ expect(ports.leave).toHaveBeenCalledOnce();+ expect(lifecycle.getState().t).toBe('idle');+ });++ it('lets a left call back in when the user joins its channel again', async () => {+ const { native, lifecycle, ports } = setup();+ await lifecycle.leave(first.channelId);+ const joining = lifecycle.join(first.channelId);+ await vi.advanceTimersByTimeAsync(300);+ await joining;+ native.setSnapshot(first);+ expect(lifecycle.getState()).toEqual({+ t: 'active',+ call: identity(first),+ });+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(+ identity(first),+ 'user'+ );+ expect(ports.disconnect).toHaveBeenCalledOnce();+ });+it('preserves a newer native call arriving before transport cleanup finishes', async () => {const { native, lifecycle, ports } = setup();const pending = deferred();@@ -672,7 +767,10 @@ describe('native snapshot events and call ownership', () => {t: 'active',call: identity(first),});- expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(identity(first));+ expect(ports.onJoined).toHaveBeenCalledExactlyOnceWith(+ identity(first),+ 'user'+ );expect(ports.disconnect).not.toHaveBeenCalled();expect(ports.leave).not.toHaveBeenCalled();}diff --git a/apps/web/src/features/channel/Call/use-call.ts b/apps/web/src/features/channel/Call/use-call.tsindex 7b27a6d39f..b7844e3ab5 100644--- a/apps/web/src/features/channel/Call/use-call.ts+++ b/apps/web/src/features/channel/Call/use-call.ts@@ -1,6 +1,7 @@import { onCleanup } from 'solid-js';import { useCallContext } from './CallContext';import type { CallSessionDisconnectOptions } from './CallSessionController';+import type { JoinSource } from './call-lifecycle';type UseCallOptions = {/** Select the call tab when Join is requested, including a refused join. */@@ -23,7 +24,8 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {}return {- joinCall: () => lifecycle.join(channelId(), options?.onJoin),+ joinCall: (source?: JoinSource) =>+ lifecycle.join(channelId(), options?.onJoin, source),leaveCall: (options?: CallSessionDisconnectOptions) =>lifecycle.leave(channelId(), options),isJoining: () => {diff --git a/apps/web/src/features/channel/Call/use-callkit.ts b/apps/web/src/features/channel/Call/use-callkit.tsindex e613de9f04..a885754114 100644--- a/apps/web/src/features/channel/Call/use-callkit.ts+++ b/apps/web/src/features/channel/Call/use-callkit.ts@@ -73,7 +73,13 @@ async function unregisterVoipForLogout(): Promise<void> {}type VoipTokenPayload = { token: string };-type CallAnsweredPayload = { channelId: string; nativeMedia?: boolean };+type CallAnsweredPayload = {+ channelId: string;+ nativeMedia?: boolean;+ callId?: string;+ /** When CallKit fulfilled the answer, epoch ms. */+ answeredAtMs?: number;+};type CallEndedPayload = { callId: string };type DrawerOpenedPayload = { channelId: string };type ParticipantIdentitiesPayload = { identities: string[] };@@ -104,8 +110,26 @@ type GetActiveCallStateResponse = {type GetPendingAnsweredCallResponse = {channelId: string | null;nativeMedia?: boolean | null;+ callId?: string | null;+ answeredAtMs?: number | null;};+/**+ * How old a CallKit answer can be when the webview handles it. Answers reach+ * JS late when the webview was suspended or cold-started; past this, the call+ * may already be over or left, and joining it would be unprompted.+ */+const ANSWERED_CALL_MAX_AGE_MS = 60_000;++/** One CallKit answer: its call when native names it, else its channel. */+function answeredCallIdentity(+ answer: Pick<CallAnsweredPayload, 'channelId' | 'nativeMedia' | 'callId'>+): string {+ return answer.callId+ ? `call:${answer.callId.toLowerCase()}`+ : `${answer.channelId}:${answer.nativeMedia ?? false}`;+}+type NativeCallChannelMetadata = {channelId: string;name?: string | null;@@ -352,10 +376,25 @@ export function useCallKitSetup() {}const handleCallAnswered = (- { channelId, nativeMedia }: CallAnsweredPayload,+ { channelId, nativeMedia, callId, answeredAtMs }: CallAnsweredPayload,source: 'channel' | 'pending' = 'channel') => {- const answeredCallKey = `${channelId}:${nativeMedia ?? false}`;+ const ageMs =+ answeredAtMs === undefined ? undefined : Date.now() - answeredAtMs;+ if (ageMs !== undefined && ageMs > ANSWERED_CALL_MAX_AGE_MS) {+ console.info('[callkit] ignoring stale answered call', {+ channelId,+ callId,+ ageMs,+ source,+ });+ return;+ }+ const answeredCallKey = answeredCallIdentity({+ channelId,+ nativeMedia,+ callId,+ });const now = Date.now();if (lastHandledAnsweredCall?.key === answeredCallKey &&@@ -393,20 +432,31 @@ export function useCallKitSetup() {invoke<GetPendingAnsweredCallResponse>('plugin:call-kit|get_pending_answered_call')- .then(({ channelId, nativeMedia }) => {+ .then(({ channelId, nativeMedia, callId, answeredAtMs }) => {console.info('[callkit] drained pending answered call', {channelId,nativeMedia,+ callId,});if (!channelId) return;if (- handled?.channelId === channelId &&- (handled.nativeMedia ?? false) === (nativeMedia ?? false)+ handled &&+ answeredCallIdentity(handled) ===+ answeredCallIdentity({+ channelId,+ nativeMedia: nativeMedia ?? false,+ callId: callId ?? undefined,+ })) {return;}handleCallAnswered(- { channelId, nativeMedia: nativeMedia ?? false },+ {+ channelId,+ nativeMedia: nativeMedia ?? false,+ callId: callId ?? undefined,+ answeredAtMs: answeredAtMs ?? undefined,+ },'pending');})diff --git a/apps/web/src/features/channel/Channel/ActiveCallMessage.tsx b/apps/web/src/features/channel/Channel/ActiveCallMessage.tsxindex 108c62e40f..d9a293b9f4 100644--- a/apps/web/src/features/channel/Channel/ActiveCallMessage.tsx+++ b/apps/web/src/features/channel/Channel/ActiveCallMessage.tsx@@ -1,3 +1,4 @@+import { analytics } from '@app/lib/analytics';import { getCallJoinTab } from '@channel/Call/call-tabs';import { useCall } from '@channel/Call/use-call';import { fireAndForget } from '@core/util/fireAndForget';@@ -39,6 +40,11 @@ export function ActiveCallMessage(props: { channelId: string }) {);async function handleJoin() {+ analytics.track('call_action', {+ action: 'join_clicked',+ channelId: props.channelId,+ isExistingCall: true,+ });try {await call.joinCall();} catch (error) {diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swiftindex 4c82f82d83..a534b13438 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift@@ -65,7 +65,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {name: AVAudioSession.routeChangeNotification,object: AVAudioSession.sharedInstance())- print("[CallKit] Audio route observing started \(describeCurrentRoute())")+ callKitLog("Audio route observing started \(describeCurrentRoute())")emitCurrentRoute()}@@ -114,7 +114,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {private func defaultToSpeakerIfBuiltInRouteOnMain(reason: String) -> Bool {guard preferredBuiltInSpeakerEnabled != false else { return false }guard !isCurrentExternalOutputRoute() else {- print("[CallKit] Skipping built-in speaker default because external route is active reason=\(reason) available=\(describeAvailableRoutes()) current=\(describeCurrentRoute())")+ callKitLog("Skipping built-in speaker default because external route is active reason=\(reason) available=\(describeAvailableRoutes()) current=\(describeCurrentRoute())")return false}let snapshot = currentSnapshotOnMain()@@ -122,7 +122,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {if snapshot.output == .speaker, isSpeakerForced {return true}- print("[CallKit] Defaulting built-in audio route to speaker reason=\(reason) output=\(snapshot.output.rawValue)")+ callKitLog("Defaulting built-in audio route to speaker reason=\(reason) output=\(snapshot.output.rawValue)")return setSpeakerEnabledOnMain(true, isUserSelection: false)}@@ -134,7 +134,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {preferredBuiltInSpeakerEnabled = enabled}isSpeakerForced = enabled- print("[CallKit] Queued audio route speaker preference enabled=\(enabled) userSelection=\(isUserSelection); current route is not ready \(describeCurrentRoute())")+ callKitLog("Queued audio route speaker preference enabled=\(enabled) userSelection=\(isUserSelection); current route is not ready \(describeCurrentRoute())")emitCurrentRouteOnMain()return false}@@ -145,12 +145,12 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {if isUserSelection {preferredBuiltInSpeakerEnabled = enabled}- print("[CallKit] Audio route speaker override enabled=\(enabled) userSelection=\(isUserSelection) \(describeCurrentRoute())")- print("[CallKit] Audio route available after speaker override \(describeAvailableRoutes())")+ callKitLog("Audio route speaker override enabled=\(enabled) userSelection=\(isUserSelection) \(describeCurrentRoute())")+ callKitLog("Audio route available after speaker override \(describeAvailableRoutes())")emitCurrentRouteOnMain()return true} catch {- print("[CallKit] Failed to set audio route speaker override enabled=\(enabled): \(error) \(describeCurrentRoute())")+ callKitLog("Failed to set audio route speaker override enabled=\(enabled): \(error) \(describeCurrentRoute())", level: .error)return false}}@@ -175,7 +175,7 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {private func emitCurrentRouteOnMain() {let snapshot = currentSnapshotOnMain()- print("[CallKit] Audio route policy \(describePolicyState()) snapshot=input:\(snapshot.input.rawValue) output:\(snapshot.output.rawValue) speakerForced:\(snapshot.isSpeakerForced) supportsSpeakerToggle:\(snapshot.supportsSpeakerToggle) current=\(describeCurrentRoute()) \(describeAvailableRoutes())")+ callKitLog("Audio route policy \(describePolicyState()) snapshot=input:\(snapshot.input.rawValue) output:\(snapshot.output.rawValue) speakerForced:\(snapshot.isSpeakerForced) supportsSpeakerToggle:\(snapshot.supportsSpeakerToggle) current=\(describeCurrentRoute()) \(describeAvailableRoutes())")routeChangedHandler?(snapshot)}@@ -217,23 +217,23 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {private func handleRouteChangeOnMain(_ notification: Notification) {let reason = routeChangeReason(from: notification)let previousRoute = notification.userInfo?[AVAudioSessionRouteChangePreviousRouteKey] as? AVAudioSessionRouteDescription- print("[CallKit] Audio route changed reason=\(reason) previous=\(previousRoute.map(describeRoute) ?? "nil") current=\(describeCurrentRoute())")- print("[CallKit] Audio route available reason=\(reason) \(describeAvailableRoutes())")+ callKitLog("Audio route changed reason=\(reason) previous=\(previousRoute.map(describeRoute) ?? "nil") current=\(describeCurrentRoute())")+ callKitLog("Audio route available reason=\(reason) \(describeAvailableRoutes())")if shouldReleaseSpeakerOverrideForExternalRoute(reason: reason) {- print("[CallKit] Releasing speaker override for external audio route reason=\(reason)")+ callKitLog("Releasing speaker override for external audio route reason=\(reason)")_ = setSpeakerEnabledOnMain(false, isUserSelection: false)return}if shouldApplyQueuedSpeakerOverride(reason: reason) {- print("[CallKit] Applying queued speaker override after route became available reason=\(reason)")+ callKitLog("Applying queued speaker override after route became available reason=\(reason)")_ = setSpeakerEnabledOnMain(true, isUserSelection: false)return}if shouldDefaultToSpeakerAfterRouteChange(reason: reason) {- print("[CallKit] Built-in speaker default is eligible after route change reason=\(reason)")+ callKitLog("Built-in speaker default is eligible after route change reason=\(reason)")}emitCurrentRouteOnMain()}@@ -350,8 +350,10 @@ final class CallAudioRouteController: NSObject, @unchecked Sendable {return "inputs=[\(inputs)] outputs=[\(outputs)]"}+ /// Port type only: port names ("<Name>'s AirPods") and UIDs (Bluetooth+ /// addresses) are personal data and must stay out of the persisted log.private func describePort(_ port: AVAudioSessionPortDescription) -> String {- "\(port.portType.rawValue):\(port.portName):uid=\(port.uid)"+ port.portType.rawValue}private func onMain(_ block: @escaping () -> Void) {diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitLog.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitLog.swiftnew file mode 100644index 0000000000..b13b0970d3--- /dev/null+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitLog.swift@@ -0,0 +1,14 @@+import Foundation+import os++private let callKitLogger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "com.macro.app", category: "CallKit")++/// Writes a `[CallKit]` line to the unified log. `print` output is discarded on+/// a device without an attached debugger; `.default` (notice) and `.error`+/// entries persist in the device log and appear in sysdiagnose and+/// `log collect`. The message is logged as public, so it must never contain+/// personal data: no participant identities (`macro|<email>`), display names,+/// channel titles, or device names. Use LiveKit SIDs and opaque ids instead.+func callKitLog(_ message: String, level: OSLogType = .default) {+ callKitLogger.log(level: level, "[CallKit] \(message, privacy: .public)")+}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitModels.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitModels.swiftindex 6f2d72b167..eb2aac189d 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitModels.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitModels.swift@@ -11,6 +11,16 @@ struct PendingCallInfo {let callerName: String?}+/// A call answered through CallKit, held until JS drains it. JS receives the+/// UUID as `callId` and `answeredAtMs` (epoch ms when CXAnswerCallAction was+/// fulfilled) so it can tell a fresh answer from a stale replay.+struct AnsweredCall {+ let callUUID: UUID+ let channelId: String+ let nativeMedia: Bool+ let answeredAtMs: Double+}+struct ActiveCallSnapshot {let channelId: Stringlet callId: Stringdiff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swiftindex d64f8c9437..e2508d33a5 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift@@ -57,14 +57,15 @@ class CallKitPlugin: Plugin, @unchecked Sendable {}override public func load(webview: WKWebView) {- print("[CallKit] Tauri CallKitPlugin loading")+ callKitLog("Tauri CallKitPlugin loading")callCoordinator = IncomingCallCoordinator(mediaSession: { [weak self] inguard let self else {- print("[CallKit] Media session requested after plugin deallocation; returning inert session")+ callKitLog("Media session requested after plugin deallocation; returning inert session")return NativeLiveKitCallSession(onSnapshotChanged: { _ in },requestSystemEndCall: { _ in },+ requestEndActiveCall: { completion in completion() },onDrawerOpened: { _ in },onParticipantIdentitiesChanged: { _ in },videoOverlay: CallVideoOverlayController()@@ -76,21 +77,32 @@ class CallKitPlugin: Plugin, @unchecked Sendable {self?.mediaSession},onVoipTokenUpdated: { [weak self] token in- print("[CallKit] Emitting voip-token-updated event tokenLength=\(token.count)")+ callKitLog("Emitting voip-token-updated event tokenLength=\(token.count)")self?.trigger("voip-token-updated", data: ["token": token])},- onCallAnswered: { [weak self] channelId, nativeMedia in- let eventPayload: JSObject = ["channelId": channelId, "nativeMedia": nativeMedia]- print("[CallKit] Triggering call answered event channelId=\(channelId) nativeMedia=\(nativeMedia)")+ onCallAnswered: { [weak self] answeredCall in+ let callId = answeredCall.callUUID.uuidString+ let eventPayload: JSObject = [+ "channelId": answeredCall.channelId,+ "nativeMedia": answeredCall.nativeMedia,+ "callId": callId,+ "answeredAtMs": answeredCall.answeredAtMs,+ ]+ callKitLog("Triggering call answered event channelId=\(answeredCall.channelId) callId=\(callId) nativeMedia=\(answeredCall.nativeMedia)")self?.trigger("call-answered", data: eventPayload)if let channel = self?.callAnsweredChannel {- let channelPayload: JsonObject = ["channelId": channelId, "nativeMedia": nativeMedia]+ let channelPayload: JsonObject = [+ "channelId": answeredCall.channelId,+ "nativeMedia": answeredCall.nativeMedia,+ "callId": callId,+ "answeredAtMs": answeredCall.answeredAtMs,+ ]channel.send(channelPayload)}},onCallEnded: { [weak self] callId inlet eventPayload: JSObject = ["callId": callId]- print("[CallKit] Triggering call ended event callId=\(callId)")+ callKitLog("Triggering call ended event callId=\(callId)")self?.trigger("call-ended", data: eventPayload)if let channel = self?.callEndedChannel {let channelPayload: JsonObject = ["callId": callId]@@ -101,7 +113,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {videoOverlay.attach(to: webview)callCoordinator.load()observeApplicationTermination()- print("[CallKit] Tauri CallKitPlugin loaded")+ callKitLog("Tauri CallKitPlugin loaded")}private func observeApplicationTermination() {@@ -113,7 +125,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {object: nil,queue: .main) { [weak self] _ in- print("[CallKit] UIApplication will terminate")+ callKitLog("UIApplication will terminate")self?.callCoordinator.handleApplicationWillTerminate()}}@@ -121,7 +133,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func watchCallAnswered(_ invoke: Invoke) throws {let args = try invoke.parseArgs(WatchCallAnsweredArgs.self)onMain { [weak self] in- print("[CallKit] JS registered call answered watcher")+ callKitLog("JS registered call answered watcher")self?.callAnsweredChannel = args.channelinvoke.resolve()}@@ -130,7 +142,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func watchCallEnded(_ invoke: Invoke) throws {let args = try invoke.parseArgs(WatchCallEndedArgs.self)onMain { [weak self] in- print("[CallKit] JS registered call ended watcher")+ callKitLog("JS registered call ended watcher")self?.callEndedChannel = args.channelinvoke.resolve()}@@ -139,7 +151,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func watchConnectionState(_ invoke: Invoke) throws {let args = try invoke.parseArgs(WatchConnectionStateArgs.self)onMain { [weak self] in- print("[CallKit] JS registered connection state watcher")+ callKitLog("JS registered connection state watcher")self?.connectionStateChannel = args.channelinvoke.resolve()}@@ -148,7 +160,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func watchDrawerOpened(_ invoke: Invoke) throws {let args = try invoke.parseArgs(WatchDrawerOpenedArgs.self)onMain { [weak self] in- print("[CallKit] JS registered drawer opened watcher")+ callKitLog("JS registered drawer opened watcher")self?.drawerOpenedChannel = args.channelinvoke.resolve()}@@ -157,7 +169,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func watchParticipantIdentities(_ invoke: Invoke) throws {let args = try invoke.parseArgs(WatchParticipantIdentitiesArgs.self)onMain { [weak self] in- print("[CallKit] JS registered participant identities watcher")+ callKitLog("JS registered participant identities watcher")self?.participantIdentitiesChannel = args.channelinvoke.resolve()}@@ -165,7 +177,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func getVoipToken(_ invoke: Invoke) {onMain { [weak self] in- print("[CallKit] JS requested cached VoIP token")+ callKitLog("JS requested cached VoIP token")invoke.resolve(["token": self?.callCoordinator.getVoipToken() as Any])}}@@ -173,10 +185,12 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func getPendingAnsweredCall(_ invoke: Invoke) {onMain { [weak self] inlet answeredCall = self?.callCoordinator.drainPendingAnsweredCall()- print("[CallKit] JS drained pending answered call channelId=\(answeredCall?.channelId ?? "nil") nativeMedia=\(answeredCall?.nativeMedia ?? false)")+ callKitLog("JS drained pending answered call channelId=\(answeredCall?.channelId ?? "nil") callId=\(answeredCall?.callUUID.uuidString ?? "nil") nativeMedia=\(answeredCall?.nativeMedia ?? false)")invoke.resolve(["channelId": answeredCall?.channelId as Any,"nativeMedia": answeredCall?.nativeMedia as Any,+ "callId": answeredCall?.callUUID.uuidString as Any,+ "answeredAtMs": answeredCall?.answeredAtMs as Any,])}}@@ -184,12 +198,12 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func getActiveCallState(_ invoke: Invoke) {onMain { [weak self] inguard let snapshot = self?.mediaSession?.currentSnapshot() else {- print("[CallKit] JS requested active call state: none")+ callKitLog("JS requested active call state: none")invoke.resolve(["state": NSNull()])return}- print("[CallKit] JS requested active call state: \(snapshot.connectionState) channelId=\(snapshot.channelId) callId=\(snapshot.callId)")+ callKitLog("JS requested active call state: \(snapshot.connectionState) channelId=\(snapshot.channelId) callId=\(snapshot.callId)")let participantIdentities = self?.mediaSession?.currentParticipantIdentities() ?? []invoke.resolve(["state": [@@ -208,11 +222,11 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func endActiveCall(_ invoke: Invoke) {onMain { [weak self] inguard let self else {- print("[CallKit] JS requested endActiveCall after plugin deallocation")+ callKitLog("JS requested endActiveCall after plugin deallocation")invoke.resolve()return}- print("[CallKit] JS requested endActiveCall")+ callKitLog("JS requested endActiveCall")self.callCoordinator.endActiveCall {invoke.resolve()}@@ -223,17 +237,17 @@ class CallKitPlugin: Plugin, @unchecked Sendable {let args = try invoke.parseArgs(StartOutgoingCallArgs.self)onMain { [weak self] inguard let self else {- print("[CallKit] JS requested startOutgoingCall after plugin deallocation")+ callKitLog("JS requested startOutgoingCall after plugin deallocation")invoke.reject("CallKit plugin is not available")return}guard let uuid = UUID(uuidString: args.callId) else {- print("[CallKit] JS requested startOutgoingCall with invalid callId=\(args.callId)")+ callKitLog("JS requested startOutgoingCall with invalid callId=\(args.callId)")invoke.reject("Invalid callId")return}- print("[CallKit] JS requested startOutgoingCall uuid=\(uuid.uuidString) channelId=\(args.channelId)")+ callKitLog("JS requested startOutgoingCall uuid=\(uuid.uuidString) channelId=\(args.channelId)")self.callCoordinator.startOutgoingCall(uuid: uuid,channelId: args.channelId,@@ -254,7 +268,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func setVideoEnabled(_ invoke: Invoke) throws {let args = try invoke.parseArgs(SetVideoEnabledArgs.self)onMain { [weak self] in- print("[CallKit] JS requested native video enabled=\(args.enabled)")+ callKitLog("JS requested native video enabled=\(args.enabled)")self?.mediaSession?.setVideoEnabled(args.enabled)invoke.resolve()}@@ -264,7 +278,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {let args = try invoke.parseArgs(SetVideoOverlayModeArgs.self)onMain { [weak self] inlet mode = CallVideoOverlayMode(rawValue: args.mode) ?? .minimized- print("[CallKit] JS requested native video overlay mode=\(mode.rawValue)")+ callKitLog("JS requested native video overlay mode=\(mode.rawValue)")self?.mediaSession?.setVideoOverlayMode(mode)invoke.resolve()}@@ -273,7 +287,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func setCallDrawerChannelTitle(_ invoke: Invoke) throws {let args = try invoke.parseArgs(SetCallDrawerChannelTitleArgs.self)onMain { [weak self] in- print("[CallKit] JS requested call drawer channelTitle=\(args.channelTitle ?? "nil")")+ callKitLog("JS requested call drawer channelTitle hasTitle=\(args.channelTitle != nil)")self?.videoOverlay.setChannelTitle(args.channelTitle)invoke.resolve()}@@ -302,7 +316,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func setParticipantDisplayName(_ invoke: Invoke) throws {let args = try invoke.parseArgs(SetParticipantDisplayNameArgs.self)onMain { [weak self] in- print("[CallKit] JS requested participant display name identity=\(args.identity) displayName=\(args.displayName ?? "nil")")+ callKitLog("JS requested participant display name hasDisplayName=\(args.displayName != nil)")self?.setParticipantDisplayName(identity: args.identity,displayName: args.displayName@@ -313,7 +327,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {@objc public func switchCamera(_ invoke: Invoke) {onMain { [weak self] in- print("[CallKit] JS requested native camera switch")+ callKitLog("JS requested native camera switch")self?.mediaSession?.switchCamera()invoke.resolve()}@@ -323,7 +337,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {let eventPayload: JSObjectlet channelPayload: JsonObjectif let snapshot {- print("[CallKit] Sending connection state channel message state=\(snapshot.connectionState) channelId=\(snapshot.channelId) callId=\(snapshot.callId)")+ callKitLog("Sending connection state channel message state=\(snapshot.connectionState) channelId=\(snapshot.channelId) callId=\(snapshot.callId)")if snapshot.connectionState == "connected",let uuid = UUID(uuidString: snapshot.callId) {callCoordinator.reportNativeCallConnected(uuid: uuid)@@ -345,7 +359,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {"videoOverlayMode": snapshot.videoOverlayMode,]} else {- print("[CallKit] Sending connection state channel message state=disconnected")+ callKitLog("Sending connection state channel message state=disconnected")eventPayload = ["state": "disconnected","channelId": NSNull(),@@ -371,7 +385,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {private func emitDrawerOpened(channelId: String) {let eventPayload: JSObject = ["channelId": channelId]- print("[CallKit] Triggering drawer opened event channelId=\(channelId)")+ callKitLog("Triggering drawer opened event channelId=\(channelId)")trigger("drawer-opened", data: eventPayload)if let channel = drawerOpenedChannel {let channelPayload: JsonObject = ["channelId": channelId]@@ -381,7 +395,7 @@ class CallKitPlugin: Plugin, @unchecked Sendable {private func emitParticipantIdentities(_ identities: [String]) {let eventPayload: JSObject = ["identities": identities]- print("[CallKit] Triggering participant identities event identities=\(identities)")+ callKitLog("Triggering participant identities event count=\(identities.count)")trigger("participant-identities", data: eventPayload)if let channel = participantIdentitiesChannel {let channelPayload: JsonObject = ["identities": identities]@@ -391,11 +405,11 @@ class CallKitPlugin: Plugin, @unchecked Sendable {private func getMediaSession() -> NativeLiveKitCallSession {if let mediaSession {- print("[CallKit] Reusing NativeLiveKitCallSession")+ callKitLog("Reusing NativeLiveKitCallSession")return mediaSession}- print("[CallKit] Creating NativeLiveKitCallSession")+ callKitLog("Creating NativeLiveKitCallSession")let mediaSession = NativeLiveKitCallSession(onSnapshotChanged: { [weak self] snapshot inself?.emitConnectionState(snapshot)@@ -403,6 +417,13 @@ class CallKitPlugin: Plugin, @unchecked Sendable {requestSystemEndCall: { [weak self] uuid inself?.callCoordinator.requestEndCall(uuid: uuid)},+ requestEndActiveCall: { [weak self] completion in+ guard let self else {+ completion()+ return+ }+ self.callCoordinator.endActiveCall(completion: completion)+ },onDrawerOpened: { [weak self] channelId inself?.emitDrawerOpened(channelId: channelId)},@@ -425,17 +446,17 @@ class CallKitPlugin: Plugin, @unchecked Sendable {let trimmedName = displayName?.trimmingCharacters(in: .whitespacesAndNewlines)if let trimmedName, !trimmedName.isEmpty {pendingParticipantDisplayNamesByIdentity[identity] = trimmedName- print("[CallKit] Cached participant display name until native session exists identity=\(identity) displayName=\(trimmedName)")+ callKitLog("Cached participant display name until native session exists count=\(pendingParticipantDisplayNamesByIdentity.count)")} else {pendingParticipantDisplayNamesByIdentity.removeValue(forKey: identity)- print("[CallKit] Cleared pending participant display name before native session exists identity=\(identity)")+ callKitLog("Cleared pending participant display name before native session exists count=\(pendingParticipantDisplayNamesByIdentity.count)")}}private func replayPendingParticipantDisplayNames(to mediaSession: NativeLiveKitCallSession) {guard !pendingParticipantDisplayNamesByIdentity.isEmpty else { return }- print("[CallKit] Replaying pending participant display names count=\(pendingParticipantDisplayNamesByIdentity.count)")+ callKitLog("Replaying pending participant display names count=\(pendingParticipantDisplayNamesByIdentity.count)")for (identity, displayName) in pendingParticipantDisplayNamesByIdentity {mediaSession.setParticipantDisplayName(identity: identity, displayName: displayName)}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swiftindex c913964fa3..4c78154a29 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swift@@ -16,11 +16,13 @@ protocol CallPictureInPictureManaging: AnyObject {func makeCallPictureInPictureController(sourceViewProvider: @escaping () -> UIView?,+ isCallActive: @escaping () -> Bool,onRestore: @escaping () -> Void) -> CallPictureInPictureManaging {if #available(iOS 15.0, *) {return AVKitCallPictureInPictureController(sourceViewProvider: sourceViewProvider,+ isCallActive: isCallActive,onRestore: onRestore)}@@ -38,32 +40,42 @@ private final class NoOpCallPictureInPictureController: CallPictureInPictureManaremoteTrack: VideoTrack?) {if localTrack != nil || remoteTrack != nil {- print("[CallKit] Picture in Picture unavailable before iOS 15")+ callKitLog("Picture in Picture unavailable before iOS 15")}}func stopAndReset() {}}+/// Picture in Picture exists only while a call is active: every prepare and+/// start path checks `isCallActive` (main-thread), so app lifecycle events+/// after a call ended can never bring back a PiP window with no call behind it.@available(iOS 15.0, *)private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPictureControllerDelegate, CallPictureInPictureManaging, @unchecked Sendable {private let sourceViewProvider: () -> UIView?+ private let isCallActive: () -> Boolprivate let onRestore: () -> Voidprivate let videoCallController = CallPiPVideoCallViewController()private weak var currentSourceView: UIView?private weak var currentLocalTrack: VideoTrack?private weak var currentRemoteTrack: VideoTrack?- private var currentLocalTitle: String?- private var currentRemoteTitle: String?private var pictureInPictureController: AVPictureInPictureController?+ /// Controllers replaced or stopped while their PiP was active or still+ /// starting. Held until AVKit reports they stopped or failed to start:+ /// dropping the only reference mid-transition can leave a system PiP+ /// window that nothing can stop.+ private var retiringControllers: [AVPictureInPictureController] = []+ private var isPictureInPictureStarting = falseprivate var didObserveAppLifecycle = falseinit(sourceViewProvider: @escaping () -> UIView?,+ isCallActive: @escaping () -> Bool,onRestore: @escaping () -> Void) {self.sourceViewProvider = sourceViewProvider+ self.isCallActive = isCallActiveself.onRestore = onRestoresuper.init()observeAppLifecycle()@@ -91,31 +103,29 @@ private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPilet normalizedLocalTitle = self.normalizedTitle(localTitle)let normalizedRemoteTitle = self.normalizedTitle(remoteTitle)- self.currentLocalTitle = normalizedLocalTitle- self.currentRemoteTitle = normalizedRemoteTitleself.videoCallController.setTitles(localTitle: normalizedLocalTitle,remoteTitle: normalizedRemoteTitle)- print("[CallKit] Picture in Picture setParticipants localTitle=\(normalizedLocalTitle ?? "nil") localTrack=\(localTrack == nil ? "nil" : "set") remoteTitle=\(normalizedRemoteTitle ?? "nil") remoteTrack=\(remoteTrack == nil ? "nil" : "set")")+ callKitLog("Picture in Picture setParticipants localTrack=\(localTrack == nil ? "nil" : "set") remoteTrack=\(remoteTrack == nil ? "nil" : "set")")if self.currentLocalTrack !== localTrack {self.currentLocalTrack = localTrackself.videoCallController.setLocalTrack(localTrack)- print("[CallKit] Picture in Picture local video track \(localTrack == nil ? "detached" : "attached")")+ callKitLog("Picture in Picture local video track \(localTrack == nil ? "detached" : "attached")")}if self.currentRemoteTrack !== remoteTrack {self.currentRemoteTrack = remoteTrackself.videoCallController.setRemoteTrack(remoteTrack)- print("[CallKit] Picture in Picture remote video track \(remoteTrack == nil ? "detached" : "attached")")+ callKitLog("Picture in Picture remote video track \(remoteTrack == nil ? "detached" : "attached")")}if localTrack == nil {- print("[CallKit] Picture in Picture local side using placeholder")+ callKitLog("Picture in Picture local side using placeholder")}if remoteTrack == nil {- print("[CallKit] Picture in Picture remote side using placeholder")+ callKitLog("Picture in Picture remote side using placeholder")}self.prepareControllerIfPossible()}@@ -124,16 +134,18 @@ private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPifunc stopAndReset() {DispatchQueue.main.async { [weak self] inguard let self else { return }- if self.pictureInPictureController?.isPictureInPictureActive == true {- print("[CallKit] Stopping Picture in Picture")- self.pictureInPictureController?.stopPictureInPicture()+ // Stop even when not yet active: a PiP that is still starting would+ // otherwise finish starting after the call ended.+ self.retireController(stop: true)+ // A controller replaced by a source-view change may still be on+ // screen; it stays tracked until AVKit reports it stopped.+ for controller in self.retiringControllers {+ controller.canStartPictureInPictureAutomaticallyFromInline = false+ controller.stopPictureInPicture()}self.currentLocalTrack = nilself.currentRemoteTrack = nil- self.currentLocalTitle = nil- self.currentRemoteTitle = nilself.currentSourceView = nil- self.pictureInPictureController = nilself.videoCallController.resetLocal(hasVideo: false)self.videoCallController.resetRemote(hasVideo: false)self.videoCallController.setTitles(localTitle: nil, remoteTitle: nil)@@ -155,24 +167,44 @@ private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPiname: UIApplication.didEnterBackgroundNotification,object: nil)- print("[CallKit] Picture in Picture observing app lifecycle")+ callKitLog("Picture in Picture observing app lifecycle")+ }++ private func retireController(stop: Bool) {+ guard let controller = pictureInPictureController else { return }+ pictureInPictureController = nil+ controller.canStartPictureInPictureAutomaticallyFromInline = false+ let isTransitioning = controller.isPictureInPictureActive || isPictureInPictureStarting+ if stop {+ callKitLog("Stopping Picture in Picture active=\(controller.isPictureInPictureActive) starting=\(isPictureInPictureStarting)")+ controller.stopPictureInPicture()+ }+ if isTransitioning {+ retiringControllers.append(controller)+ }+ }++ private func releaseRetiringController(_ controller: AVPictureInPictureController) {+ retiringControllers.removeAll { $0 === controller }}private func prepareControllerIfPossible() {+ guard isCallActive() else { return }guard AVPictureInPictureController.isPictureInPictureSupported() else {- print("[CallKit] Picture in Picture unsupported on this device")+ callKitLog("Picture in Picture unsupported on this device")return}guard let sourceView = sourceViewProvider() else {- print("[CallKit] Picture in Picture source view unavailable")+ callKitLog("Picture in Picture source view unavailable")return}if pictureInPictureController != nil, currentSourceView === sourceView {- print("[CallKit] Picture in Picture controller already prepared sourceView=\(type(of: sourceView)) hidden=\(sourceView.isHidden) window=\(sourceView.window != nil) possible=\(pictureInPictureController?.isPictureInPicturePossible ?? false)")+ callKitLog("Picture in Picture controller already prepared sourceView=\(type(of: sourceView)) hidden=\(sourceView.isHidden) window=\(sourceView.window != nil) possible=\(pictureInPictureController?.isPictureInPicturePossible ?? false)")return}+ retireController(stop: false)currentSourceView = sourceViewvideoCallController.loadViewIfNeeded()let contentSource = AVPictureInPictureController.ContentSource(@@ -183,34 +215,35 @@ private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPicontroller.canStartPictureInPictureAutomaticallyFromInline = truecontroller.delegate = selfpictureInPictureController = controller- print("[CallKit] Picture in Picture controller prepared sourceView=\(type(of: sourceView)) hidden=\(sourceView.isHidden) window=\(sourceView.window != nil) localTitle=\(currentLocalTitle ?? "nil") localTrack=\(currentLocalTrack != nil) remoteTitle=\(currentRemoteTitle ?? "nil") remoteTrack=\(currentRemoteTrack != nil) possible=\(controller.isPictureInPicturePossible)")+ callKitLog("Picture in Picture controller prepared sourceView=\(type(of: sourceView)) hidden=\(sourceView.isHidden) window=\(sourceView.window != nil) localTrack=\(currentLocalTrack != nil) remoteTrack=\(currentRemoteTrack != nil) possible=\(controller.isPictureInPicturePossible)")}@objc private func appWillResignActive() {DispatchQueue.main.async { [weak self] in- print("[CallKit] Picture in Picture app will resign active")self?.startPictureInPictureIfPossible(reason: "willResignActive")}}@objc private func appDidEnterBackground() {DispatchQueue.main.async { [weak self] in- print("[CallKit] Picture in Picture app did enter background")self?.startPictureInPictureIfPossible(reason: "didEnterBackground")}}private func startPictureInPictureIfPossible(reason: String) {+ guard isCallActive() else { return }+ callKitLog("Picture in Picture app lifecycle reason=\(reason)")prepareControllerIfPossible()guard let controller = pictureInPictureController else { return }guard !controller.isPictureInPictureActive else { return }guard controller.isPictureInPicturePossible else {- print("[CallKit] Picture in Picture not possible reason=\(reason) localTitle=\(currentLocalTitle ?? "nil") localTrack=\(currentLocalTrack != nil) remoteTitle=\(currentRemoteTitle ?? "nil") remoteTrack=\(currentRemoteTrack != nil)")+ callKitLog("Picture in Picture not possible reason=\(reason) localTrack=\(currentLocalTrack != nil) remoteTrack=\(currentRemoteTrack != nil)")return}- print("[CallKit] Starting Picture in Picture reason=\(reason) localTitle=\(currentLocalTitle ?? "nil") localTrack=\(currentLocalTrack != nil) remoteTitle=\(currentRemoteTitle ?? "nil") remoteTrack=\(currentRemoteTrack != nil)")+ callKitLog("Starting Picture in Picture reason=\(reason) localTrack=\(currentLocalTrack != nil) remoteTrack=\(currentRemoteTrack != nil)")+ isPictureInPictureStarting = truecontroller.startPictureInPicture()}@@ -220,29 +253,41 @@ private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPi}func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {- print("[CallKit] Picture in Picture will start")+ callKitLog("Picture in Picture will start")+ isPictureInPictureStarting = true}func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {- print("[CallKit] Picture in Picture did start")+ isPictureInPictureStarting = false+ guard isCallActive() else {+ callKitLog("Picture in Picture started with no active call; stopping it")+ pictureInPictureController.canStartPictureInPictureAutomaticallyFromInline = false+ pictureInPictureController.stopPictureInPicture()+ return+ }+ callKitLog("Picture in Picture did start")}func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController,failedToStartPictureInPictureWithError error: Error) {- print("[CallKit] Picture in Picture failed to start error=\(error)")+ callKitLog("Picture in Picture failed to start error=\(error)", level: .error)+ isPictureInPictureStarting = false+ releaseRetiringController(pictureInPictureController)}func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {- print("[CallKit] Picture in Picture did stop")+ callKitLog("Picture in Picture did stop")+ isPictureInPictureStarting = false+ releaseRetiringController(pictureInPictureController)}func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController,restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) {- print("[CallKit] Picture in Picture restore requested")+ callKitLog("Picture in Picture restore requested callActive=\(isCallActive())")onRestore()completionHandler(true)}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift b/apps/web/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swiftindex 556400c8fd..198feb0db6 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift@@ -110,6 +110,10 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uvar onSelectRemoteParticipant: ((String) -> Void)?var onOpenDrawerFromThumbnail: (() -> Void)?var onModeChanged: ((CallVideoOverlayMode) -> Void)?+ /// Whether a call is running behind the overlay. Read on main when a+ /// setter applies, so a late update queued before teardown can never+ /// present a drawer, thumbnail, or edge tab with no call to leave.+ var isCallActive: () -> Bool = { false }/// Everything the overlay renders, in one value. Setters mutate `desired`;/// the apply pass owns moving it into the view tree and records what it@@ -203,12 +207,16 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, U}}- func setMode(_ mode: CallVideoOverlayMode) {+ func setMode(_ requestedMode: CallVideoOverlayMode) {DispatchQueue.main.async { [weak self] inguard let self else { return }+ let mode = self.isCallActive() ? requestedMode : .hidden+ if mode != requestedMode {+ callKitLog("Native video overlay hiding instead of mode=\(requestedMode.rawValue); no active call")+ }self.desired.mode = modeself.scheduleApply()- print("[CallKit] Native video overlay mode=\(mode.rawValue)")+ callKitLog("Native video overlay mode=\(mode.rawValue)")self.onModeChanged?(mode)}}@@ -223,7 +231,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uself.desired.channelTitle = "Call"}self.scheduleApply()- print("[CallKit] Native video overlay channelTitle=\(self.desired.channelTitle)")+ callKitLog("Native video overlay channelTitle hasTitle=\(trimmedTitle?.isEmpty == false)")}}@@ -232,7 +240,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uguard let self else { return }self.desired.theme = theme ?? .fallbackself.scheduleApply()- print("[CallKit] Native video overlay theme updated")+ callKitLog("Native video overlay theme updated")}}@@ -247,17 +255,22 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Ufunc presentForActiveCallIfNeeded() {DispatchQueue.main.async { [weak self] inguard let self else { return }- guard self.desired.mode == .hidden, !self.didAutoPresent else { return }+ guard self.isCallActive(), self.desired.mode == .hidden, !self.didAutoPresent else { return }self.didAutoPresent = trueself.desired.mode = .expandedself.scheduleApply()- print("[CallKit] Native video overlay auto-presented for active call")+ callKitLog("Native video overlay auto-presented for active call")}}func setRemoteVideoParticipants(_ participants: [NativeVideoParticipant], primaryId: String?) {DispatchQueue.main.async { [weak self] inguard let self else { return }+ // Remote participants show the edge tab even while hidden.+ guard self.isCallActive() else {+ callKitLog("Native video overlay ignoring remote participants; no active call")+ return+ }self.desired.participants = participantsself.desired.primaryRemoteParticipantId = primaryIdif self.primaryRemoteParticipant != nil, self.desired.mode == .hidden, !self.didAutoPresent {@@ -271,6 +284,10 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Ufunc setLocalVideoTrack(_ track: VideoTrack?) {DispatchQueue.main.async { [weak self] inguard let self else { return }+ guard self.isCallActive() else {+ callKitLog("Native video overlay ignoring localTrack=\(track == nil ? "nil" : "set"); no active call")+ return+ }self.desired.localVideoTrack = trackself.desired.isLocalVideoEnabled = track != nilif track != nil, self.desired.mode == .hidden, !self.didAutoPresent {@@ -278,7 +295,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uself.desired.mode = .expanded}self.scheduleApply()- print("[CallKit] Native video overlay localTrack=\(track == nil ? "nil" : "set")")+ callKitLog("Native video overlay localTrack=\(track == nil ? "nil" : "set")")}}@@ -292,7 +309,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uself.desired.localParticipantTitle = "You"}self.scheduleApply()- print("[CallKit] Native video overlay localParticipantTitle=\(self.desired.localParticipantTitle)")+ callKitLog("Native video overlay localParticipantTitle hasTitle=\(trimmedTitle?.isEmpty == false)")}}@@ -301,7 +318,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uguard let self else { return }self.desired.isLocalVideoEnabled = enabledself.scheduleApply()- print("[CallKit] Native video overlay localVideoEnabled=\(enabled)")+ callKitLog("Native video overlay localVideoEnabled=\(enabled)")}}@@ -310,7 +327,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uguard let self else { return }self.desired.isAudioMuted = mutedself.scheduleApply()- print("[CallKit] Native video overlay audioMuted=\(muted)")+ callKitLog("Native video overlay audioMuted=\(muted)")}}@@ -319,7 +336,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uguard let self else { return }self.desired.audioRoute = routeself.scheduleApply()- print("[CallKit] Native video overlay audioRoute input=\(route.input.rawValue) output=\(route.output.rawValue) speakerForced=\(route.isSpeakerForced) supportsSpeakerToggle=\(route.supportsSpeakerToggle)")+ callKitLog("Native video overlay audioRoute input=\(route.input.rawValue) output=\(route.output.rawValue) speakerForced=\(route.isSpeakerForced) supportsSpeakerToggle=\(route.supportsSpeakerToggle)")}}@@ -332,7 +349,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uself.stripScrollView.invalidateSelection()self.didAutoPresent = falseself.scheduleApply()- print("[CallKit] Native video overlay reset")+ callKitLog("Native video overlay reset")}}@@ -363,7 +380,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uguard !isOverlayInteracting else {if deferredApplyStart == nil {deferredApplyStart = CACurrentMediaTime()- print("[CallKit] Native video overlay deferring structural apply while interacting \(interactionDebugDescription)")+ callKitLog("Native video overlay deferring structural apply while interacting \(interactionDebugDescription)")}applyRestyleOnly()scheduleDeferredFlush()@@ -371,7 +388,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, U}if let start = deferredApplyStart {deferredApplyStart = nil- print(String(format: "[CallKit] Native video overlay flushed deferred apply after %.2fs", CACurrentMediaTime() - start))+ callKitLog(String(format: "Native video overlay flushed deferred apply after %.2fs", CACurrentMediaTime() - start))}applyFullState()applied = desired@@ -406,7 +423,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, UlayoutFrames()bringOverlayToFrontIfNeeded()if participantsChanged {- print("[CallKit] Native video overlay applied remoteParticipants=\(desired.participants.count) primary=\(primaryRemoteParticipant?.id ?? "nil")")+ callKitLog("Native video overlay applied remoteParticipants=\(desired.participants.count) hasPrimary=\(primaryRemoteParticipant != nil)")}}@@ -469,7 +486,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, UrootView.frame = parent.boundsrootView.autoresizingMask = [.flexibleWidth, .flexibleHeight]parent.addSubview(rootView)- print("[CallKit] Attached native video overlay parent=\(type(of: parent)) frame=\(parent.bounds)")+ callKitLog("Attached native video overlay parent=\(type(of: parent)) frame=\(parent.bounds)")} else if rootView.frame != parent.bounds {rootView.frame = parent.bounds}@@ -485,7 +502,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, U"document.activeElement && document.activeElement.blur && document.activeElement.blur()",completionHandler: nil)- print("[CallKit] Native video overlay dismissed webview keyboard for drawer")+ callKitLog("Native video overlay dismissed webview keyboard for drawer")}/// Reordering the window's subviews while a touch is in flight destabilizes@@ -849,7 +866,7 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, Uprivate func selectDisplayedParticipant(_ id: String) {// A departure may have arrived while the displayed row was frozen.guard desired.participants.contains(where: { $0.id == id }) else { return }- print("[CallKit] Native video overlay remote tile selected id=\(id)")+ callKitLog("Native video overlay remote tile selected")onSelectRemoteParticipant?(id)}@@ -1213,34 +1230,34 @@ final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, U}@objc private func toggleMicrophone() {- print("[CallKit] Native video overlay microphone toggle tapped currentMuted=\(isAudioMuted)")+ callKitLog("Native video overlay microphone toggle tapped currentMuted=\(isAudioMuted)")onToggleMicrophone?()}@objc private func toggleSpeaker() {- print("[CallKit] Native video overlay speaker toggle tapped output=\(audioRoute.output.rawValue) speakerForced=\(audioRoute.isSpeakerForced) supportsSpeakerToggle=\(audioRoute.supportsSpeakerToggle)")+ callKitLog("Native video overlay speaker toggle tapped output=\(audioRoute.output.rawValue) speakerForced=\(audioRoute.isSpeakerForced) supportsSpeakerToggle=\(audioRoute.supportsSpeakerToggle)")guard audioRoute.supportsSpeakerToggle else { return }onToggleSpeaker?()}@objc private func toggleCamera() {- print("[CallKit] Native video overlay camera toggle tapped currentEnabled=\(isLocalVideoEnabled)")+ callKitLog("Native video overlay camera toggle tapped currentEnabled=\(isLocalVideoEnabled)")onToggleCamera?()}@objc private func switchCamera() {- print("[CallKit] Native video overlay camera switch tapped")+ callKitLog("Native video overlay camera switch tapped")onSwitchCamera?()}@objc private func unpinRemoteParticipant() {guard let pinnedRemoteParticipantId else { return }- print("[CallKit] Native video overlay unpin tapped id=\(pinnedRemoteParticipantId)")+ callKitLog("Native video overlay unpin tapped")onSelectRemoteParticipant?(pinnedRemoteParticipantId)}@objc private func endCall() {- print("[CallKit] Native video overlay end call tapped")+ callKitLog("Native video overlay end call tapped")onEndCall?()}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift b/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swiftindex bf6cf00e65..8c2a077ca1 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift@@ -10,7 +10,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate let mediaSessionProvider: () -> NativeLiveKitCallSessionprivate let existingMediaSession: () -> NativeLiveKitCallSession?private let onVoipTokenUpdated: (String) -> Void- private let onCallAnswered: (String, Bool) -> Void+ private let onCallAnswered: (AnsweredCall) -> Voidprivate let onCallEnded: (String) -> Voidprivate var provider: CXProvider!@@ -30,14 +30,14 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate var outgoingCallUUIDs: Set<UUID> = []private var reportedConnectedOutgoingCallUUIDs: Set<UUID> = []private var cachedVoipToken: String?- private var pendingAnsweredCall: (channelId: String, nativeMedia: Bool)?+ private var pendingAnsweredCall: AnsweredCall?private var pendingEndCallCompletions: [UUID: [() -> Void]] = [:]init(mediaSession: @escaping () -> NativeLiveKitCallSession,existingMediaSession: @escaping () -> NativeLiveKitCallSession?,onVoipTokenUpdated: @escaping (String) -> Void,- onCallAnswered: @escaping (String, Bool) -> Void,+ onCallAnswered: @escaping (AnsweredCall) -> Void,onCallEnded: @escaping (String) -> Void) {self.mediaSessionProvider = mediaSession@@ -70,7 +70,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}func load() {- print("[CallKit] Loading PushKit/CallKit coordinator")+ callKitLog("Loading PushKit/CallKit coordinator")let config = makeProviderConfiguration()providerConfiguration = config@@ -80,14 +80,14 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrregistry = PKPushRegistry(queue: .main)registry.delegate = selfregistry.desiredPushTypes = [.voIP]- print("[CallKit] PushKit registry configured for VoIP pushes")+ callKitLog("PushKit registry configured for VoIP pushes")}func getVoipToken() -> String? {cachedVoipToken}- func drainPendingAnsweredCall() -> (channelId: String, nativeMedia: Bool)? {+ func drainPendingAnsweredCall() -> AnsweredCall? {let answeredCall = pendingAnsweredCallpendingAnsweredCall = nilreturn answeredCall@@ -103,7 +103,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrcompletion: @escaping (Error?) -> Void) {if let activeCallUUID, activeCallUUID != uuid {- print("[CallKit] startOutgoingCall rejected; active call already exists activeUuid=\(activeCallUUID.uuidString) requestedUuid=\(uuid.uuidString)")+ callKitLog("startOutgoingCall rejected; active call already exists activeUuid=\(activeCallUUID.uuidString) requestedUuid=\(uuid.uuidString)")completion(NSError(domain: "CallKitPlugin",code: 1,@@ -126,7 +126,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrlet sessionCallUUID = mediaSessionCallUUID()if !isAnsweringPendingIncomingCall,activeCallUUID == uuid || sessionCallUUID == uuid {- print("[CallKit] startOutgoingCall ignored; call already running uuid=\(uuid.uuidString) channelId=\(channelId)")+ callKitLog("startOutgoingCall ignored; call already running uuid=\(uuid.uuidString) channelId=\(channelId)")activeCallUUID = uuidif sessionCallUUID == uuid {activeNativeMediaUUID = uuid@@ -150,16 +150,16 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistractivateNativeMediaAudioIfNeeded(reason: "JS answer prepared")let action = CXAnswerCallAction(call: uuid)let transaction = CXTransaction(action: action)- print("[CallKit] Requesting CXAnswerCallAction from JS uuid=\(uuid.uuidString) channelId=\(channelId) channelName=\(displayTitle ?? "nil")")+ callKitLog("Requesting CXAnswerCallAction from JS uuid=\(uuid.uuidString) channelId=\(channelId)")callController.request(transaction) { error inDispatchQueue.main.async {if let error {- print("[CallKit] JS CXAnswerCallAction request failed uuid=\(uuid.uuidString) error=\(error)")+ callKitLog("JS CXAnswerCallAction request failed uuid=\(uuid.uuidString) error=\(error)", level: .error)if self.activeNativeMediaUUID == uuid {self.activeNativeMediaUUID = nil}} else {- print("[CallKit] JS CXAnswerCallAction request accepted uuid=\(uuid.uuidString)")+ callKitLog("JS CXAnswerCallAction request accepted uuid=\(uuid.uuidString)")}completion(error)}@@ -180,14 +180,14 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrlet action = CXStartCallAction(call: uuid, handle: handle)action.isVideo = truelet transaction = CXTransaction(action: action)- print("[CallKit] Requesting CXStartCallAction uuid=\(uuid.uuidString) channelId=\(channelId) channelName=\(displayTitle ?? "nil")")+ callKitLog("Requesting CXStartCallAction uuid=\(uuid.uuidString) channelId=\(channelId)")callController.request(transaction) { [weak self] error inDispatchQueue.main.async {if let error {- print("[CallKit] CXStartCallAction request failed uuid=\(uuid.uuidString) error=\(error)")+ callKitLog("CXStartCallAction request failed uuid=\(uuid.uuidString) error=\(error)", level: .error)self?.clearCallState(uuid: uuid)} else {- print("[CallKit] CXStartCallAction request accepted uuid=\(uuid.uuidString)")+ callKitLog("CXStartCallAction request accepted uuid=\(uuid.uuidString)")}completion(error)}@@ -198,7 +198,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrguard activeNativeMediaUUID == uuid, outgoingCallUUIDs.contains(uuid) else { return }guard !reportedConnectedOutgoingCallUUIDs.contains(uuid) else { return }reportedConnectedOutgoingCallUUIDs.insert(uuid)- print("[CallKit] Reporting outgoing call connected uuid=\(uuid.uuidString)")+ callKitLog("Reporting outgoing call connected uuid=\(uuid.uuidString)")provider.reportOutgoingCall(with: uuid, connectedAt: Date())}@@ -208,7 +208,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr// 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")+ callKitLog("endActiveCall requested with no active CallKit UUID or media session")completion()return}@@ -216,11 +216,11 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr// 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)")+ callKitLog("endActiveCall also ending media session call uuid=\(sessionCallUUID.uuidString)")requestEndCall(uuid: sessionCallUUID)}- print("[CallKit] endActiveCall requesting CXEndCallAction uuid=\(uuid.uuidString)")+ callKitLog("endActiveCall requesting CXEndCallAction uuid=\(uuid.uuidString)")appendPendingEndCallCompletion(uuid: uuid, completion)requestEndCall(uuid: uuid) { [weak self] error inguard let self else {@@ -229,7 +229,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}self.onMain {if error != nil {- print("[CallKit] CXEndCallAction failed; clearing local state uuid=\(uuid.uuidString)")+ callKitLog("CXEndCallAction failed; clearing local state uuid=\(uuid.uuidString)", level: .error)self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)return}@@ -237,7 +237,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrDispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] inguard 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)")+ callKitLog("Timed out waiting for CXEndCallAction provider callback; completing JS endActiveCall uuid=\(uuid.uuidString)")self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)}}@@ -245,11 +245,11 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}func requestEndCall(uuid: UUID) {- print("[CallKit] requestEndCall uuid=\(uuid.uuidString)")+ callKitLog("requestEndCall uuid=\(uuid.uuidString)")requestEndCall(uuid: uuid) { [weak self] error inguard let self, error != nil else { return }self.onMain {- print("[CallKit] requestEndCall failed; disconnecting media session uuid=\(uuid.uuidString)")+ callKitLog("requestEndCall failed; disconnecting media session uuid=\(uuid.uuidString)", level: .error)self.clearCallStateAndDisconnectMediaIfNeeded(uuid: uuid)}}@@ -269,11 +269,11 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrfunc handleApplicationWillTerminate() {stopAllRingStatePolling()guard let uuid = activeCallUUID ?? mediaSessionCallUUID() else {- print("[CallKit] Application terminating with no active CallKit call")+ callKitLog("Application terminating with no active CallKit call")return}- print("[CallKit] Application terminating with active CallKit call uuid=\(uuid.uuidString)")+ callKitLog("Application terminating with active CallKit call uuid=\(uuid.uuidString)")if hasActiveNativeMedia() {mediaSessionProvider().disconnectForAppTermination()}@@ -285,7 +285,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrlet transaction = CXTransaction(action: CXEndCallAction(call: uuid))callController.request(transaction) { error inif let error {- print("[CallKit] CXEndCallAction request failed: \(error)")+ callKitLog("CXEndCallAction request failed: \(error)", level: .error)}completion(error)}@@ -299,7 +299,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrguard type == .voIP else { return }let token = pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined()cachedVoipToken = token- print("[CallKit] VoIP token updated byteLength=\(pushCredentials.token.count)")+ callKitLog("VoIP token updated byteLength=\(pushCredentials.token.count)")onVoipTokenUpdated(token)}@@ -323,7 +323,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrlet livekitToken = dict["livekitToken"] as? Stringlet ringStatusUrl = dict["ringStatusUrl"] as? Stringlet hasNativeCredentials = livekitServerUrl != nil && livekitToken != nil- print("[CallKit] Received VoIP push callId=\(callIdString) channelId=\(channelId) channelName=\(channelName ?? "nil") hasNativeCredentials=\(hasNativeCredentials)")+ callKitLog("Received VoIP push callId=\(callIdString) channelId=\(channelId) hasChannelName=\(channelName != nil) hasNativeCredentials=\(hasNativeCredentials)")guard let uuid = UUID(uuidString: callIdString) else {// PushKit requires every VoIP push to be reported to CallKit.@@ -331,7 +331,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr.compactMap { $0 as? String }.filter { $0 != "livekitServerUrl" && $0 != "livekitToken" }.sorted()- print("[CallKit] Invalid callId '\(callIdString)' in VoIP payload; keys=\(safePayloadKeys)")+ callKitLog("Invalid callId '\(callIdString)' in VoIP payload; keys=\(safePayloadKeys)")let fallbackUUID = UUID()applyProviderConfiguration(reason: "invalid incoming call report")provider.reportNewIncomingCall(with: fallbackUUID, update: CXCallUpdate()) { [weak self] _ in@@ -345,7 +345,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr// 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)")+ callKitLog("Marking stale pending call failed uuid=\(staleUUID.uuidString)")provider.reportCall(with: staleUUID, endedAt: nil, reason: .failed)pendingCalls.removeValue(forKey: staleUUID)pendingCallTokens.removeValue(forKey: staleUUID)@@ -362,7 +362,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrpendingCallTokens[uuid] = PendingCallToken(serverUrl: serverUrl, token: token)} else {pendingCallTokens.removeValue(forKey: uuid)- print("[CallKit] VoIP payload missing native connection credentials; lock-screen answer will not connect natively")+ callKitLog("VoIP payload missing native connection credentials; lock-screen answer will not connect natively")}if let ringStatusUrl {pendingRingStatusUrls[uuid] = ringStatusUrl@@ -375,7 +375,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr// 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)")+ callKitLog("Incoming call while another call is active; keeping active uuid=\(activeCallUUID.uuidString) ringing uuid=\(uuid.uuidString)")}} else {activeCallUUID = uuid@@ -393,13 +393,13 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrapplyProviderConfiguration(reason: "incoming call report")provider.reportNewIncomingCall(with: uuid, update: update) { [weak self] error inif error != nil {- print("[CallKit] reportNewIncomingCall failed uuid=\(uuid.uuidString) error=\(String(describing: error))")+ callKitLog("reportNewIncomingCall failed uuid=\(uuid.uuidString) error=\(String(describing: error))", level: .error)self?.pendingCalls.removeValue(forKey: uuid)self?.pendingCallTokens.removeValue(forKey: uuid)self?.pendingRingStatusUrls.removeValue(forKey: uuid)if self?.activeCallUUID == uuid { self?.activeCallUUID = nil }} else {- print("[CallKit] reportNewIncomingCall succeeded uuid=\(uuid.uuidString)")+ callKitLog("reportNewIncomingCall succeeded uuid=\(uuid.uuidString)")if let ringStatusUrl, let token = livekitToken {self?.startRingStatePolling(uuid: uuid, ringStatusUrl: ringStatusUrl, bearerToken: token)}@@ -409,7 +409,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}func providerDidReset(_ provider: CXProvider) {- print("[CallKit] CXProvider reset; clearing CallKit and media state")+ callKitLog("CXProvider reset; clearing CallKit and media state")stopAllRingStatePolling()pendingCalls.removeAll()pendingCallTokens.removeAll()@@ -431,10 +431,10 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrfunc provider(_ provider: CXProvider, perform action: CXStartCallAction) {let uuid = action.callUUID- print("[CallKit] CXStartCallAction received uuid=\(uuid.uuidString)")+ callKitLog("CXStartCallAction received uuid=\(uuid.uuidString)")guard let pendingCall = pendingCalls[uuid],let pendingToken = pendingCallTokens[uuid] else {- print("[CallKit] CXStartCallAction failed: no pending call/token uuid=\(uuid.uuidString)")+ callKitLog("CXStartCallAction failed: no pending call/token uuid=\(uuid.uuidString)", level: .error)action.fail()clearCallState(uuid: uuid)return@@ -451,17 +451,17 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprovider.reportOutgoingCall(with: uuid, startedConnectingAt: Date())mediaSessionProvider().prepareForCallKitAudio()action.fulfill()- print("[CallKit] Fulfilled CXStartCallAction uuid=\(uuid.uuidString)")+ callKitLog("Fulfilled CXStartCallAction uuid=\(uuid.uuidString)")Task { @MainActor [weak self] inguard let self else { return }guard self.canStartNativeMediaConnect(uuid: uuid) else {- print("[CallKit] Skipping outgoing native LiveKit connect; call no longer active uuid=\(uuid.uuidString)")+ callKitLog("Skipping outgoing native LiveKit connect; call no longer active uuid=\(uuid.uuidString)")return}let mediaSession = self.mediaSessionProvider()mediaSession.setChannelTitle(pendingCall.channelName)- print("[CallKit] Starting native LiveKit connect for outgoing call uuid=\(uuid.uuidString) channelId=\(pendingCall.channelId)")+ callKitLog("Starting native LiveKit connect for outgoing call uuid=\(uuid.uuidString) channelId=\(pendingCall.channelId)")mediaSession.connect(uuid: uuid,channelId: pendingCall.channelId,@@ -472,10 +472,10 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {- print("[CallKit] CXAnswerCallAction received uuid=\(action.callUUID.uuidString)")+ callKitLog("CXAnswerCallAction received uuid=\(action.callUUID.uuidString)")stopRingStatePolling(uuid: action.callUUID)guard let pendingCall = pendingCalls[action.callUUID] else {- print("[CallKit] Answer failed: no pending channel for uuid=\(action.callUUID.uuidString)")+ callKitLog("Answer failed: no pending channel for uuid=\(action.callUUID.uuidString)", level: .error)action.fail()return}@@ -486,18 +486,16 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrlet shouldConnectNatively = enableNativeLiveKitAnswer && pendingToken != nilif shouldConnectNatively {activeNativeMediaUUID = answeredUUID- print("[CallKit] Scheduling native LiveKit connect for answered call uuid=\(answeredUUID.uuidString) channelId=\(channelId)")+ callKitLog("Scheduling native LiveKit connect for answered call uuid=\(answeredUUID.uuidString) channelId=\(channelId)")let mediaSession = mediaSessionProvider()mediaSession.setChannelTitle(pendingCall.channelName)mediaSession.prepareForCallKitAudio()} else if pendingCallTokens[answeredUUID] != nil {- print("[CallKit] Native LiveKit answer disabled; JS-driven join required uuid=\(answeredUUID.uuidString)")+ callKitLog("Native LiveKit answer disabled; JS-driven join required uuid=\(answeredUUID.uuidString)")} else {- print("[CallKit] No cached LiveKit token for answered call \(answeredUUID.uuidString); JS-driven join required")+ callKitLog("No cached LiveKit token for answered call \(answeredUUID.uuidString); JS-driven join required")}- pendingAnsweredCall = (channelId: channelId, nativeMedia: shouldConnectNatively)-// 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@@ -509,23 +507,30 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrpendingCallTokens.removeValue(forKey: answeredUUID)pendingRingStatusUrls.removeValue(forKey: answeredUUID)- print("[CallKit] Fulfilling CXAnswerCallAction uuid=\(answeredUUID.uuidString)")+ callKitLog("Fulfilling CXAnswerCallAction uuid=\(answeredUUID.uuidString)")applyProviderConfiguration(reason: "answer action fulfillment")action.fulfill()- print("[CallKit] Fulfilled CXAnswerCallAction uuid=\(answeredUUID.uuidString)")+ let answeredCall = AnsweredCall(+ callUUID: answeredUUID,+ channelId: channelId,+ nativeMedia: shouldConnectNatively,+ answeredAtMs: Date().timeIntervalSince1970 * 1000+ )+ pendingAnsweredCall = answeredCall+ callKitLog("Fulfilled CXAnswerCallAction uuid=\(answeredUUID.uuidString) answeredAtMs=\(answeredCall.answeredAtMs)")if shouldConnectNatively, let pendingToken {Task { @MainActor [weak self] inguard let self else { return }- print("[CallKit] Native LiveKit connect task started uuid=\(answeredUUID.uuidString)")+ callKitLog("Native LiveKit connect task started uuid=\(answeredUUID.uuidString)")try? await Task.sleep(nanoseconds: 100_000_000)guard self.canStartNativeMediaConnect(uuid: answeredUUID) else {- print("[CallKit] Skipping answered native LiveKit connect; call no longer active uuid=\(answeredUUID.uuidString)")+ callKitLog("Skipping answered native LiveKit connect; call no longer active uuid=\(answeredUUID.uuidString)")return}let mediaSession = self.mediaSessionProvider()mediaSession.setChannelTitle(pendingCall.channelName)- print("[CallKit] Starting native LiveKit connect uuid=\(answeredUUID.uuidString) channelId=\(channelId); audio remains gated until CallKit activation")+ callKitLog("Starting native LiveKit connect uuid=\(answeredUUID.uuidString) channelId=\(channelId); audio remains gated until CallKit activation")mediaSession.connect(uuid: answeredUUID,channelId: channelId,@@ -536,14 +541,14 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}DispatchQueue.main.async { [weak self] in- print("[CallKit] Emitting call answered event after fulfill channelId=\(channelId) uuid=\(answeredUUID.uuidString) nativeMedia=\(shouldConnectNatively)")- self?.onCallAnswered(channelId, shouldConnectNatively)+ callKitLog("Emitting call answered event after fulfill channelId=\(channelId) uuid=\(answeredUUID.uuidString) nativeMedia=\(shouldConnectNatively)")+ self?.onCallAnswered(answeredCall)}}func provider(_ provider: CXProvider, perform action: CXEndCallAction) {let callId = action.callUUID.uuidString- print("[CallKit] CXEndCallAction received uuid=\(callId)")+ callKitLog("CXEndCallAction received uuid=\(callId)")// Ending a call that is still pending (never answered here, not an// outgoing call) is the user declining the incoming ring — e.g. the// lock-screen Decline button. Tell the backend before the state is@@ -564,56 +569,56 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr}action.fulfill()- print("[CallKit] Fulfilled CXEndCallAction uuid=\(callId)")+ callKitLog("Fulfilled CXEndCallAction uuid=\(callId)")clearCallState(uuid: action.callUUID)}func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {- print("[CallKit] CXSetMutedCallAction received uuid=\(action.callUUID.uuidString) muted=\(action.isMuted)")+ callKitLog("CXSetMutedCallAction received uuid=\(action.callUUID.uuidString) muted=\(action.isMuted)")if isNativeMediaCall(action.callUUID) {mediaSessionProvider().setAudioMuted(action.isMuted)}action.fulfill()- print("[CallKit] Fulfilled CXSetMutedCallAction uuid=\(action.callUUID.uuidString) muted=\(action.isMuted)")+ callKitLog("Fulfilled CXSetMutedCallAction uuid=\(action.callUUID.uuidString) muted=\(action.isMuted)")}func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {isCallKitAudioSessionActive = trueguard hasActiveNativeMedia() else {- print("[CallKit] AVAudioSession activated by CallKit; native media not active yet")+ callKitLog("AVAudioSession activated by CallKit; native media not active yet")return}- print("[CallKit] AVAudioSession activated by CallKit for native media")+ callKitLog("AVAudioSession activated by CallKit for native media")mediaSessionProvider().activateAudioEngine(reason: "provider didActivate", audioSession: audioSession)}func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {isCallKitAudioSessionActive = falseguard hasActiveNativeMedia() else {- print("[CallKit] AVAudioSession deactivated by CallKit; no native media session active")+ callKitLog("AVAudioSession deactivated by CallKit; no native media session active")return}- print("[CallKit] AVAudioSession deactivated by CallKit for native media")+ callKitLog("AVAudioSession deactivated by CallKit for native media")mediaSessionProvider().deactivateAudioEngine(audioSession: audioSession)}func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {let callUUID = (action as? CXCallAction)?.callUUID.uuidString ?? "nil"- print("[CallKit] CXProvider timed out performing action=\(type(of: action)) uuid=\(callUUID)")+ callKitLog("CXProvider timed out performing action=\(type(of: action)) uuid=\(callUUID)")}private func clearCallState(uuid: UUID) {- print("[CallKit] Clearing call state uuid=\(uuid.uuidString)")+ callKitLog("Clearing call state uuid=\(uuid.uuidString)")stopRingStatePolling(uuid: uuid)pendingCalls.removeValue(forKey: uuid)pendingCallTokens.removeValue(forKey: uuid)pendingRingStatusUrls.removeValue(forKey: uuid)- 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 activeCallUUID == uuid { activeCallUUID = nil }+ // Keyed by the answered call itself: JS replays the pending answer on+ // every foreground, so it must go when that call ends for any reason,+ // while clearing an unrelated ring (e.g. a declined second call) must+ // not drop it.+ if pendingAnsweredCall?.callUUID == uuid { pendingAnsweredCall = nil }if activeNativeMediaUUID == uuid { activeNativeMediaUUID = nil }outgoingCallUUIDs.remove(uuid)reportedConnectedOutgoingCallUUIDs.remove(uuid)@@ -643,7 +648,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate func startRingStatePolling(uuid: UUID, ringStatusUrl: String, bearerToken: String) {guard let url = URL(string: ringStatusUrl) else {- print("[CallKit] Invalid ringStatusUrl in VoIP payload uuid=\(uuid.uuidString)")+ callKitLog("Invalid ringStatusUrl in VoIP payload uuid=\(uuid.uuidString)")return}stopRingStatePolling(uuid: uuid)@@ -673,7 +678,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate func reportDecline(uuid: UUID) {guard let ringStatusUrl = pendingRingStatusUrls[uuid],let token = pendingCallTokens[uuid]?.token else {- print("[CallKit] Skipping decline report; no ring credential uuid=\(uuid.uuidString)")+ callKitLog("Skipping decline report; no ring credential uuid=\(uuid.uuidString)")return}RingDeclineReporter.report(uuid: uuid, ringStatusUrl: ringStatusUrl, bearerToken: token)@@ -686,7 +691,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistr// 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)")+ callKitLog("Ignoring remote ring resolution; call no longer pending uuid=\(uuid.uuidString)")return}let reason: CXCallEndedReason@@ -695,7 +700,7 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrcase .declined: reason = .declinedElsewherecase .ended: reason = .remoteEnded}- print("[CallKit] Ending ringing call from remote resolution uuid=\(uuid.uuidString) reason=\(reason.rawValue)")+ callKitLog("Ending ringing call from remote resolution uuid=\(uuid.uuidString) reason=\(reason.rawValue)")// reportCall(with:endedAt:reason:) does not trigger the// CXEndCallAction delegate, so notify JS and clear state here.provider.reportCall(with: uuid, endedAt: nil, reason: reason)@@ -706,10 +711,10 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate func activateNativeMediaAudioIfNeeded(reason: String) {guard hasActiveNativeMedia() else { return }guard isCallKitAudioSessionActive else {- print("[CallKit] Native media waiting for CallKit AVAudioSession activation reason=\(reason)")+ callKitLog("Native media waiting for CallKit AVAudioSession activation reason=\(reason)")return}- print("[CallKit] Applying existing CallKit AVAudioSession activation to native media reason=\(reason) \(describeCurrentAudioRoute())")+ callKitLog("Applying existing CallKit AVAudioSession activation to native media reason=\(reason) \(describeCurrentAudioRoute())")mediaSessionProvider().activateAudioEngine(reason: reason)}@@ -728,14 +733,14 @@ final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistrprivate func applyProviderConfiguration(reason: String) {let config = providerConfiguration ?? makeProviderConfiguration()providerConfiguration = config- print("[CallKit] Applying CXProvider configuration reason=\(reason)")+ callKitLog("Applying CXProvider configuration reason=\(reason)")provider.configuration = config}private func describeCurrentAudioRoute() -> String {let session = AVAudioSession.sharedInstance()- let inputs = session.currentRoute.inputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")- let outputs = session.currentRoute.outputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")+ let inputs = session.currentRoute.inputs.map { $0.portType.rawValue }.joined(separator: ",")+ let outputs = session.currentRoute.outputs.map { $0.portType.rawValue }.joined(separator: ",")return "audioRoute(inputs=[\(inputs)], outputs=[\(outputs)])"}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift b/apps/web/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swiftindex 9d1900681f..c75d2f8db6 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift@@ -13,6 +13,7 @@ import UIKitfinal class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendable {private let onSnapshotChanged: (ActiveCallSnapshot?) -> Voidprivate let requestSystemEndCall: (UUID) -> Void+ private let requestEndActiveCall: (@escaping () -> Void) -> Voidprivate let onDrawerOpened: (String) -> Voidprivate let onParticipantIdentitiesChanged: ([String]) -> Voidprivate let videoOverlay: CallVideoOverlayController@@ -20,13 +21,22 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablsourceViewProvider: { [weak self] inself?.videoOverlay.pictureInPictureSourceView()},+ isCallActive: { [weak self] in+ self?.activeCallUUID != nil+ },onRestore: { [weak self] inguard let self else { return }- self.setVideoOverlayMode(.expanded)- if let channelId = self.activeCall?.channelId {- print("[CallKit] Picture in Picture restoring channelId=\(channelId)")- self.onDrawerOpened(channelId)+ // Restoring into a drawer with no call behind it shows a Leave+ // button that can never end anything.+ guard let channelId = self.activeCall?.channelId else {+ callKitLog("Picture in Picture restored with no active call; stopping it and resetting the overlay")+ self.pictureInPicture.stopAndReset()+ self.videoOverlay.reset()+ return}+ self.setVideoOverlayMode(.expanded)+ callKitLog("Picture in Picture restoring channelId=\(channelId)")+ self.onDrawerOpened(channelId)})@@ -53,12 +63,14 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablinit(onSnapshotChanged: @escaping (ActiveCallSnapshot?) -> Void,requestSystemEndCall: @escaping (UUID) -> Void,+ requestEndActiveCall: @escaping (@escaping () -> Void) -> Void,onDrawerOpened: @escaping (String) -> Void,onParticipantIdentitiesChanged: @escaping ([String]) -> Void,videoOverlay: CallVideoOverlayController) {self.onSnapshotChanged = onSnapshotChangedself.requestSystemEndCall = requestSystemEndCall+ self.requestEndActiveCall = requestEndActiveCallself.onDrawerOpened = onDrawerOpenedself.onParticipantIdentitiesChanged = onParticipantIdentitiesChangedself.videoOverlay = videoOverlay@@ -85,13 +97,16 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablvideoOverlay.onSelectRemoteParticipant = { [weak self] participantId inself?.togglePinnedRemoteVideoParticipant(participantId)}+ videoOverlay.isCallActive = { [weak self] in+ self?.activeCallUUID != nil+ }videoOverlay.onOpenDrawerFromThumbnail = { [weak self] inguard let channelId = self?.activeCall?.channelId else { return }- print("[CallKit] Native video overlay opened from thumbnail channelId=\(channelId)")+ callKitLog("Native video overlay opened from thumbnail channelId=\(channelId)")self?.onDrawerOpened(channelId)}videoOverlay.onModeChanged = { [weak self] mode in- print("[CallKit] Picture in Picture refreshing source for overlay mode=\(mode.rawValue)")+ callKitLog("Picture in Picture refreshing source for overlay mode=\(mode.rawValue)")self?.updateVideoOverlayMode(mode.rawValue)self?.pictureInPicture.prepare()}@@ -112,7 +127,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet audioAvailabilityChanged = previousInputAvailable != inputAvailable|| previousOutputAvailable != outputAvailableguard routeChanged || audioAvailabilityChanged else {- print("[CallKit] Audio route emit did not change route or engine availability; skipping microphone restore")+ callKitLog("Audio route emit did not change route or engine availability; skipping microphone restore")return}@@ -126,14 +141,14 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}audioRouteController.startObserving()pictureInPicture.prepare()- print("[CallKit] NativeLiveKitCallSession initialized")+ callKitLog("NativeLiveKitCallSession initialized")}func prepareForCallKitAudio() {guard !didPrepareAudio else { return }didPrepareAudio = true- print("[CallKit] Prepared LiveKit audio for CallKit-controlled activation")+ callKitLog("Prepared LiveKit audio for CallKit-controlled activation")configureAudioSessionCategory(reason: "prepareForCallKitAudio")}@@ -147,9 +162,9 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl])do {try AudioManager.shared.setEngineAvailability(.none)- print("[CallKit] Configured LiveKit audio for CallKit engine gating")+ callKitLog("Configured LiveKit audio for CallKit engine gating")} catch {- print("[CallKit] Failed to gate LiveKit audio engine before CallKit activation: \(error)")+ callKitLog("Failed to gate LiveKit audio engine before CallKit activation: \(error)", level: .error)}}@@ -162,17 +177,17 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabloptions: [.allowBluetoothHFP, .mixWithOthers])try session.setPreferredIOBufferDuration(0.02)- print("[CallKit] Configured AVAudioSession category for voice call reason=\(reason) \(describeAudioSession())")+ callKitLog("Configured AVAudioSession category for voice call reason=\(reason) \(describeAudioSession())")audioRouteController.emitCurrentRoute()defaultBuiltInSpeakerRouteOnceIfNeeded(reason: "audioSessionCategoryConfigured:\(reason)")} catch {- print("[CallKit] Failed to set audio session category reason=\(reason): \(error) \(describeAudioSession())")+ callKitLog("Failed to set audio session category reason=\(reason): \(error) \(describeAudioSession())", level: .error)}}func activateAudioEngine(reason: String = "CallKit didActivate", audioSession: AVAudioSession? = nil) {guard !isActivatingAudioEngine else {- print("[CallKit] Ignoring nested LiveKit audio engine activation reason=\(reason)")+ callKitLog("Ignoring nested LiveKit audio engine activation reason=\(reason)")return}isActivatingAudioEngine = true@@ -180,21 +195,21 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablconfigureAudioSessionCategory(reason: reason)if !hasUsableAudioOutputRoute() {- print("[CallKit] Activating LiveKit audio engine with empty AVAudioSession route reason=\(reason) \(describeAudioSession())")+ callKitLog("Activating LiveKit audio engine with empty AVAudioSession route reason=\(reason) \(describeAudioSession())")}do {if let audioSession {LKRTCAudioSession.sharedInstance().audioSessionDidActivate(audioSession)- print("[CallKit] Notified LiveKit WebRTC audio session didActivate reason=\(reason)")+ callKitLog("Notified LiveKit WebRTC audio session didActivate reason=\(reason)")}let availability = callKitAudioEngineAvailability()- print("[CallKit] Enabling LiveKit audio engine after CallKit activation reason=\(reason) input=\(availability.isInputAvailable) output=\(availability.isOutputAvailable) \(describeAudioSession())")+ callKitLog("Enabling LiveKit audio engine after CallKit activation reason=\(reason) input=\(availability.isInputAvailable) output=\(availability.isOutputAvailable) \(describeAudioSession())")try AudioManager.shared.setEngineAvailability(availability)isCallKitAudioActive = true- print("[CallKit] CallKit activated AVAudioSession; LiveKit audio engine available reason=\(reason) input=\(AudioManager.shared.engineAvailability.isInputAvailable) output=\(AudioManager.shared.engineAvailability.isOutputAvailable) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ callKitLog("CallKit activated AVAudioSession; LiveKit audio engine available reason=\(reason) input=\(AudioManager.shared.engineAvailability.isInputAvailable) output=\(AudioManager.shared.engineAvailability.isOutputAvailable) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")restoreMicrophoneIfNeeded(reason: reason)} catch {- print("[CallKit] Failed to enable LiveKit audio engine after CallKit activation reason=\(reason): \(error) \(describeAudioSession())")+ callKitLog("Failed to enable LiveKit audio engine after CallKit activation reason=\(reason): \(error) \(describeAudioSession())", level: .error)}}@@ -203,13 +218,13 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabldo {if let audioSession {LKRTCAudioSession.sharedInstance().audioSessionDidDeactivate(audioSession)- print("[CallKit] Notified LiveKit WebRTC audio session didDeactivate")+ callKitLog("Notified LiveKit WebRTC audio session didDeactivate")}- print("[CallKit] Disabling LiveKit audio engine after CallKit deactivation \(describeAudioSession())")+ callKitLog("Disabling LiveKit audio engine after CallKit deactivation \(describeAudioSession())")try AudioManager.shared.setEngineAvailability(.none)- print("[CallKit] CallKit deactivated AVAudioSession; LiveKit audio engine unavailable input=\(AudioManager.shared.engineAvailability.isInputAvailable) output=\(AudioManager.shared.engineAvailability.isOutputAvailable) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ callKitLog("CallKit deactivated AVAudioSession; LiveKit audio engine unavailable input=\(AudioManager.shared.engineAvailability.isInputAvailable) output=\(AudioManager.shared.engineAvailability.isOutputAvailable) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")} catch {- print("[CallKit] Failed to disable LiveKit audio engine after CallKit deactivation: \(error) \(describeAudioSession())")+ callKitLog("Failed to disable LiveKit audio engine after CallKit deactivation: \(error) \(describeAudioSession())", level: .error)}}@@ -223,7 +238,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}func connect(uuid: UUID, channelId: String, serverUrl: String, token: String) {- print("[CallKit] Native LiveKit connect requested uuid=\(uuid.uuidString) channelId=\(channelId)")+ callKitLog("Native LiveKit connect requested uuid=\(uuid.uuidString) channelId=\(channelId)")let desiredAudioMuted = microphoneCoordinator.desiredMutedmicrophoneCoordinator.reset(desiredMuted: desiredAudioMuted)didApplyDefaultSpeakerRoute = false@@ -233,12 +248,12 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablprepareForCallKitAudio()audioRouteController.prepareForCall()- print("[CallKit] Creating LiveKit Room uuid=\(uuid.uuidString)")+ callKitLog("Creating LiveKit Room uuid=\(uuid.uuidString)")let newRoom = Room(delegate: self,roomOptions: RoomOptions(suspendLocalVideoTracksInBackground: false))- print("[CallKit] Created LiveKit Room uuid=\(uuid.uuidString)")+ callKitLog("Created LiveKit Room uuid=\(uuid.uuidString)")activeCallUUID = uuidactiveCall = ActiveCallSnapshot(@@ -265,20 +280,20 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablconnectTask = Task { [weak self, oldRoom, weak newRoom] inguard let self else { return }if let oldRoom {- print("[CallKit] Disconnecting previous LiveKit room before new connect uuid=\(uuid.uuidString)")+ callKitLog("Disconnecting previous LiveKit room before new connect uuid=\(uuid.uuidString)")await oldRoom.disconnect()- print("[CallKit] Previous LiveKit room disconnected uuid=\(uuid.uuidString)")+ callKitLog("Previous LiveKit room disconnected uuid=\(uuid.uuidString)")}guard let newRoom else { return }do {- print("[CallKit] Connecting LiveKit room uuid=\(uuid.uuidString)")+ callKitLog("Connecting LiveKit room uuid=\(uuid.uuidString)")try await newRoom.connect(url: serverUrl, token: token)let isCurrentRoom = await MainActor.run { () -> Bool inguard self.activeCallUUID == uuid, self.room === newRoom else { return false }- print("[CallKit] LiveKit room connected uuid=\(uuid.uuidString) roomSid=\(self.describeOptional(newRoom.sid)) remoteCount=\(newRoom.remoteParticipants.count)")- print("[CallKit] LiveKit local participant \(self.describeParticipant(newRoom.localParticipant))")+ callKitLog("LiveKit room connected uuid=\(uuid.uuidString) roomSid=\(self.describeOptional(newRoom.sid)) remoteCount=\(newRoom.remoteParticipants.count)")+ callKitLog("LiveKit local participant \(self.describeParticipant(newRoom.localParticipant))")for participant in newRoom.remoteParticipants.values {- print("[CallKit] LiveKit existing remote participant \(self.describeParticipant(participant))")+ callKitLog("LiveKit existing remote participant \(self.describeParticipant(participant))")}self.emitParticipantIdentities(from: newRoom)self.videoOverlay.setLocalParticipantTitle(self.displayTitle(newRoom.localParticipant))@@ -287,14 +302,23 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablreturn true}guard isCurrentRoom else {- print("[CallKit] Ignoring LiveKit connect completion for stale room uuid=\(uuid.uuidString)")+ // The room was replaced or the call ended while connecting.+ // Nothing else holds it, so leaving it connected would keep+ // this user in the call server-side and could publish the+ // microphone. disconnect() is idempotent if teardown already+ // reached it.+ callKitLog("Disconnecting LiveKit room whose connect completed after it went stale uuid=\(uuid.uuidString) roomSid=\(self.describeOptional(newRoom.sid)) state=\(self.describe(newRoom.connectionState))")+ await newRoom.disconnect()+ callKitLog("Stale LiveKit room disconnected uuid=\(uuid.uuidString)")return}} catch is CancellationError {- print("[CallKit] LiveKit connect task cancelled uuid=\(uuid.uuidString)")+ // Room.connect cleans the room up before rethrowing, so a+ // cancelled connect never leaves it connected.+ callKitLog("LiveKit connect task cancelled uuid=\(uuid.uuidString) state=\(self.describe(newRoom.connectionState))")return} catch {- print("[CallKit] Failed to connect LiveKit room: \(error)")+ callKitLog("Failed to connect LiveKit room uuid=\(uuid.uuidString): \(error)", level: .error)DispatchQueue.main.async { [weak self, weak newRoom] inguard let self, self.activeCallUUID == uuid, self.room === newRoom else { return }self.requestSystemEndCall(uuid)@@ -307,23 +331,23 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}func disconnect() async {- print("[CallKit] Native LiveKit disconnect requested")+ callKitLog("Native LiveKit disconnect requested")let toDisconnect: Room? = await MainActor.run {self.clearNativeCallState(deactivateAudio: true)}if let toDisconnect {await toDisconnect.disconnect()- print("[CallKit] Native LiveKit room disconnected")+ callKitLog("Native LiveKit room disconnected")} else {- print("[CallKit] Native LiveKit disconnect had no active room")+ callKitLog("Native LiveKit disconnect had no active room")}}func disconnectForAppTermination() {- print("[CallKit] Native LiveKit app termination disconnect requested")+ callKitLog("Native LiveKit app termination disconnect requested")let backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "CallKitLiveKitDisconnectOnTerminate") {- print("[CallKit] Native LiveKit app termination disconnect background task expired")+ callKitLog("Native LiveKit app termination disconnect background task expired")}Task { @MainActor [weak self] in@@ -337,9 +361,9 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet toDisconnect = self.clearNativeCallState(deactivateAudio: true)if let toDisconnect {await toDisconnect.disconnect()- print("[CallKit] Native LiveKit room disconnected for app termination")+ callKitLog("Native LiveKit room disconnected for app termination")} else {- print("[CallKit] Native LiveKit app termination disconnect had no active room")+ callKitLog("Native LiveKit app termination disconnect had no active room")}if backgroundTask != .invalid {@@ -351,7 +375,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc setAudioMuted(_ muted: Bool) {guard activeCallUUID != nil, room != nil else {let generation = microphoneCoordinator.setDesiredMuted(muted)- print("[CallKit] setAudioMuted queued; no active native room muted=\(muted) generation=\(generation)")+ callKitLog("setAudioMuted queued; no active native room muted=\(muted) generation=\(generation)")return}@@ -377,7 +401,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablparticipantDisplayNamesByIdentity.removeValue(forKey: normalizedIdentity)}- print("[CallKit] Native LiveKit participant display name set identity=\(trimmedIdentity) normalizedIdentity=\(normalizedIdentity) displayName=\(participantDisplayNamesByIdentity[normalizedIdentity] ?? "nil")")+ callKitLog("Native LiveKit participant display name updated hasDisplayName=\(normalizedName != nil) knownNames=\(participantDisplayNamesByIdentity.count)")if let room {videoOverlay.setLocalParticipantTitle(displayTitle(room.localParticipant))rebuildRemoteVideoLayout(from: room)@@ -390,7 +414,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc setVideoEnabled(_ enabled: Bool) {guard let room, let uuid = activeCallUUID else {- print("[CallKit] setVideoEnabled ignored; no active native room enabled=\(enabled)")+ callKitLog("setVideoEnabled ignored; no active native room enabled=\(enabled)")return}@@ -404,25 +428,30 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}do {- print("[CallKit] Setting native LiveKit camera enabled=\(enabled) uuid=\(uuid.uuidString)")+ callKitLog("Setting native LiveKit camera enabled=\(enabled) uuid=\(uuid.uuidString)")try await room.localParticipant.setCamera(enabled: enabled)if enabled {self.enableMultitaskingCameraAccessIfSupported(room: room, uuid: uuid)- await MainActor.run {- self.videoOverlay.setLocalVideoTrack(room.localParticipant.firstCameraVideoTrack)- self.rebuildRemoteVideoLayout(from: room)- }- self.setVideoOverlayMode(.expanded)- } else {- await MainActor.run {- self.videoOverlay.setLocalVideoTrack(nil)- self.rebuildRemoteVideoLayout(from: room)+ }+ // The call can end while the camera toggles; updating the overlay+ // afterwards would re-present the drawer with no call behind it.+ let isCurrentCall = await MainActor.run { () -> Bool in+ guard self.activeCallUUID == uuid, self.isCurrentRoom(room) else { return false }+ self.videoOverlay.setLocalVideoTrack(enabled ? room.localParticipant.firstCameraVideoTrack : nil)+ self.rebuildRemoteVideoLayout(from: room)+ if enabled {+ self.setVideoOverlayMode(.expanded)}+ self.updateVideoMuted(!enabled, overlayMode: enabled ? "expanded" : self.activeCall?.videoOverlayMode)+ return true+ }+ guard isCurrentCall else {+ callKitLog("Ignoring native LiveKit camera result; call no longer active enabled=\(enabled) uuid=\(uuid.uuidString)")+ return}- self.updateVideoMuted(!enabled, overlayMode: enabled ? "expanded" : self.activeCall?.videoOverlayMode)- print("[CallKit] Native LiveKit camera set enabled=\(enabled) uuid=\(uuid.uuidString)")+ callKitLog("Native LiveKit camera set enabled=\(enabled) uuid=\(uuid.uuidString)")} catch {- print("[CallKit] Failed to set native LiveKit camera enabled=\(enabled) uuid=\(uuid.uuidString): \(error)")+ callKitLog("Failed to set native LiveKit camera enabled=\(enabled) uuid=\(uuid.uuidString): \(error)", level: .error)self.updateVideoMuted(true, overlayMode: self.activeCall?.videoOverlayMode)}}@@ -434,37 +463,47 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablprivate func toggleVideoFromOverlay() {let enabled = activeCall?.isVideoMuted ?? true- print("[CallKit] Native video overlay requested camera enabled=\(enabled)")+ callKitLog("Native video overlay requested camera enabled=\(enabled)")setVideoEnabled(enabled)}private func toggleAudioFromOverlay() {let muted = !(activeCall?.isAudioMuted ?? false)- print("[CallKit] Native video overlay requested microphone muted=\(muted)")+ callKitLog("Native video overlay requested microphone muted=\(muted)")setAudioMuted(muted)}private func toggleSpeakerFromOverlay() {let currentOutput = audioRouteController.currentRouteSnapshot().outputlet enableSpeaker = currentOutput != .speaker- print("[CallKit] Native video overlay requested speaker enabled=\(enableSpeaker) currentOutput=\(currentOutput.rawValue)")+ callKitLog("Native video overlay requested speaker enabled=\(enableSpeaker) currentOutput=\(currentOutput.rawValue)")didApplyDefaultSpeakerRoute = trueaudioRouteController.setSpeakerEnabled(enableSpeaker)}+ /// Leave must always work, even when the drawer or PiP outlived the call.+ /// The coordinator's end path covers a desynced CallKit pointer, a failed+ /// CXEndCallAction request, and a provider callback that never arrives;+ /// its completion then tears down whatever native media or UI is left.private func endCallFromOverlay() {- guard let uuid = activeCallUUID else {- print("[CallKit] Native video overlay end call ignored; no active call")- return+ let endingUUID = activeCallUUID+ callKitLog("Native video overlay requesting call end uuid=\(endingUUID?.uuidString ?? "nil")")+ requestEndActiveCall { [weak self] in+ Task { @MainActor [weak self] in+ guard let self else { return }+ if let activeCallUUID = self.activeCallUUID, activeCallUUID != endingUUID {+ callKitLog("Skipping native teardown after overlay end; another call is active uuid=\(activeCallUUID.uuidString)")+ return+ }+ callKitLog("Native video overlay end completed; tearing down native call state uuid=\(endingUUID?.uuidString ?? "nil")")+ await self.disconnect()+ }}-- print("[CallKit] Native video overlay requesting CallKit end uuid=\(uuid.uuidString)")- requestSystemEndCall(uuid)}private func togglePinnedRemoteVideoParticipant(_ participantId: String) {pinnedRemoteVideoParticipantId = pinnedRemoteVideoParticipantId == participantId ? nil : participantId- print("[CallKit] Native video overlay pinned remote participant=\(pinnedRemoteVideoParticipantId ?? "nil")")+ callKitLog("Native video overlay pinned remote participant=\(pinnedRemoteVideoParticipantId != nil)")if let room {rebuildRemoteVideoLayout(from: room)}@@ -472,7 +511,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc switchCamera() {guard let room, let uuid = activeCallUUID else {- print("[CallKit] switchCamera ignored; no active native room")+ callKitLog("switchCamera ignored; no active native room")return}@@ -481,15 +520,15 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet track = room?.localParticipant.firstCameraVideoTrack as? LocalVideoTrack,let capturer = track.capturer as? CameraCapturerelse {- print("[CallKit] switchCamera ignored; no active local camera track uuid=\(uuid.uuidString)")+ callKitLog("switchCamera ignored; no active local camera track uuid=\(uuid.uuidString)")return}do {_ = try await capturer.switchCameraPosition()- print("[CallKit] Native LiveKit camera switched uuid=\(uuid.uuidString)")+ callKitLog("Native LiveKit camera switched uuid=\(uuid.uuidString)")} catch {- print("[CallKit] Failed to switch native LiveKit camera uuid=\(uuid.uuidString): \(error)")+ callKitLog("Failed to switch native LiveKit camera uuid=\(uuid.uuidString): \(error)", level: .error)}}}@@ -500,7 +539,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfrom oldConnectionState: ConnectionState) {let stateString = describe(connectionState)- print("[CallKit] LiveKit connection state changed \(describe(oldConnectionState)) -> \(stateString)")+ callKitLog("LiveKit connection state changed \(describe(oldConnectionState)) -> \(stateString) roomSid=\(describeOptional(room.sid))")DispatchQueue.main.async { [weak self, weak room] inguard let self, let room, self.room === room else { return }@@ -521,25 +560,25 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}func room(_ room: Room, didFailToConnectWithError error: LiveKitError?) {- print("[CallKit] LiveKit delegate didFailToConnect error=\(String(describing: error))")+ callKitLog("LiveKit delegate didFailToConnect error=\(String(describing: error))", level: .error)}func room(_ room: Room, didDisconnectWithError error: LiveKitError?) {- print("[CallKit] LiveKit delegate didDisconnect error=\(String(describing: error))")+ callKitLog("LiveKit delegate didDisconnect error=\(String(describing: error))")}func room(_ room: Room, didStartReconnectWithMode reconnectMode: ReconnectMode) {- print("[CallKit] LiveKit reconnect started mode=\(reconnectMode)")+ callKitLog("LiveKit reconnect started mode=\(reconnectMode)")}func room(_ room: Room, didCompleteReconnectWithMode reconnectMode: ReconnectMode) {- print("[CallKit] LiveKit reconnect completed mode=\(reconnectMode)")+ callKitLog("LiveKit reconnect completed mode=\(reconnectMode)")}func room(_ room: Room, participantDidConnect participant: RemoteParticipant) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room, self.room === room else { return }- print("[CallKit] LiveKit remote participant connected \(self.describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")+ callKitLog("LiveKit remote participant connected \(self.describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")self.emitParticipantIdentities(from: room)self.rebuildRemoteVideoLayout(from: room)}@@ -548,7 +587,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participantDidDisconnect participant: RemoteParticipant) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room, self.room === room else { return }- print("[CallKit] LiveKit remote participant disconnected \(self.describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")+ callKitLog("LiveKit remote participant disconnected \(self.describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")let id = self.participantId(participant)if self.pinnedRemoteVideoParticipantId == id {self.pinnedRemoteVideoParticipantId = nil@@ -567,7 +606,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl.map { self.participantId($0) }guard speakingIds != self.speakingRemoteParticipantIds else { return }self.speakingRemoteParticipantIds = speakingIds- print("[CallKit] LiveKit speaking participants updated participants=\(participants.map { self.describeParticipant($0) })")+ callKitLog("LiveKit speaking participants updated participants=\(participants.map { self.describeParticipant($0) })")self.rebuildRemoteVideoLayout(from: room)}}@@ -575,23 +614,23 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: Participant, didUpdateState state: ParticipantState) {DispatchQueue.main.async { [weak self] inguard let self else { return }- print("[CallKit] LiveKit participant state updated \(self.describeParticipant(participant)) state=\(state)")+ callKitLog("LiveKit participant state updated \(self.describeParticipant(participant)) state=\(state)")}}func room(_ room: Room, participant: Participant, didUpdateConnectionQuality quality: ConnectionQuality) {DispatchQueue.main.async { [weak self] inguard let self else { return }- print("[CallKit] LiveKit participant quality updated \(self.describeParticipant(participant)) quality=\(quality)")+ callKitLog("LiveKit participant quality updated \(self.describeParticipant(participant)) quality=\(quality)")}}func room(_ room: Room, participant: LocalParticipant, didPublishTrack publication: LocalTrackPublication) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit local track published \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit local track published \(self.describeParticipant(participant)) \(self.describe(publication))")guard self.isCurrentRoom(room) else {- print("[CallKit] Ignoring local track publish from stale room")+ callKitLog("Ignoring local track publish from stale room")return}if let track = publication.track as? VideoTrack, publication.source == .camera {@@ -606,9 +645,9 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: LocalParticipant, didUnpublishTrack publication: LocalTrackPublication) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit local track unpublished \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit local track unpublished \(self.describeParticipant(participant)) \(self.describe(publication))")guard self.isCurrentRoom(room) else {- print("[CallKit] Ignoring local track unpublish from stale room")+ callKitLog("Ignoring local track unpublish from stale room")return}if publication.source == .camera {@@ -622,14 +661,18 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: LocalParticipant, remoteDidSubscribeTrack publication: LocalTrackPublication) {DispatchQueue.main.async { [weak self] inguard let self else { return }- print("[CallKit] LiveKit remote subscribed to local track \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit remote subscribed to local track \(self.describeParticipant(participant)) \(self.describe(publication))")}}func room(_ room: Room, participant: RemoteParticipant, didPublishTrack publication: RemoteTrackPublication) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit remote track published \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit remote track published \(self.describeParticipant(participant)) \(self.describe(publication))")+ guard self.isCurrentRoom(room) else {+ callKitLog("Ignoring remote track publish from stale room")+ return+ }if publication.kind == .video {self.rebuildRemoteVideoLayout(from: room)}@@ -639,7 +682,13 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: RemoteParticipant, didSubscribeTrack publication: RemoteTrackPublication) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit remote track subscribed \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit remote track subscribed \(self.describeParticipant(participant)) \(self.describe(publication))")+ // A stale room's late subscription must not re-expand a drawer+ // whose call already ended.+ guard self.isCurrentRoom(room) else {+ callKitLog("Ignoring remote track subscribe from stale room")+ return+ }if publication.track is VideoTrack, self.isRemoteVideoSource(publication.source) {self.rebuildRemoteVideoLayout(from: room)self.setVideoOverlayMode(.expanded)@@ -650,7 +699,11 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: RemoteParticipant, didUnsubscribeTrack publication: RemoteTrackPublication) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit remote track unsubscribed \(self.describeParticipant(participant)) \(self.describe(publication))")+ callKitLog("LiveKit remote track unsubscribed \(self.describeParticipant(participant)) \(self.describe(publication))")+ guard self.isCurrentRoom(room) else {+ callKitLog("Ignoring remote track unsubscribe from stale room")+ return+ }if self.isRemoteVideoSource(publication.source) {self.rebuildRemoteVideoLayout(from: room)}@@ -660,7 +713,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablfunc room(_ room: Room, participant: RemoteParticipant, didFailToSubscribeTrackWithSid trackSid: Track.Sid, error: LiveKitError) {DispatchQueue.main.async { [weak self] inguard let self else { return }- print("[CallKit] LiveKit remote track subscribe failed \(self.describeParticipant(participant)) trackSid=\(trackSid) error=\(error)")+ callKitLog("LiveKit remote track subscribe failed \(self.describeParticipant(participant)) trackSid=\(trackSid) error=\(error)", level: .error)}}@@ -672,7 +725,11 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl) {DispatchQueue.main.async { [weak self, weak room] inguard let self, let room else { return }- print("[CallKit] LiveKit track mute updated \(self.describeParticipant(participant)) \(self.describe(trackPublication)) muted=\(isMuted)")+ callKitLog("LiveKit track mute updated \(self.describeParticipant(participant)) \(self.describe(trackPublication)) muted=\(isMuted)")+ guard self.isCurrentRoom(room) else {+ callKitLog("Ignoring track mute update from stale room")+ return+ }if participant is RemoteParticipant, trackPublication.kind == .video {self.rebuildRemoteVideoLayout(from: room)}@@ -696,7 +753,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablprivate func rebuildRemoteVideoLayout(from room: Room) {guard isCurrentRoom(room) else {- print("[CallKit] Ignoring remote video layout rebuild from stale room")+ callKitLog("Ignoring remote video layout rebuild from stale room")return}@@ -745,14 +802,14 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendabllastPublishedVideoParticipants = participantslastPublishedPrimaryParticipantId = primary?.idvideoOverlay.setRemoteVideoParticipants(participants, primaryId: primary?.id)- print("[CallKit] Rebuilt remote video layout participants=\(participants.map { "\($0.id):\($0.title)" }) primary=\(primary?.id ?? "nil") pinned=\(pinnedRemoteVideoParticipantId ?? "nil")")+ callKitLog("Rebuilt remote video layout participants=\(participants.count) withVideo=\(participants.filter { $0.track != nil }.count) hasPrimary=\(primary != nil) pinned=\(pinnedRemoteVideoParticipantId != nil)")}updatePictureInPicture(from: room, primary: primary)}private func updatePictureInPicture(from room: Room, primary: NativeVideoParticipant?) {let localTrack = room.localParticipant.firstCameraVideoTrack- print("[CallKit] Picture in Picture selected localTitle=\(displayTitle(room.localParticipant)) localTrack=\(localTrack != nil) primaryParticipant=\(primary?.id ?? "nil") remoteTitle=\(primary?.title ?? "nil") remoteTrack=\(primary?.track != nil)")+ callKitLog("Picture in Picture selected localTrack=\(localTrack != nil) hasPrimary=\(primary != nil) remoteTrack=\(primary?.track != nil)")pictureInPicture.setParticipants(localTitle: displayTitle(room.localParticipant),localTrack: localTrack,@@ -763,28 +820,28 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablprivate func enableMultitaskingCameraAccessIfSupported(room: Room, uuid: UUID?) {guard #available(iOS 16.0, *) else {- print("[CallKit] Multitasking camera access unavailable before iOS 16 uuid=\(uuid?.uuidString ?? "nil")")+ callKitLog("Multitasking camera access unavailable before iOS 16 uuid=\(uuid?.uuidString ?? "nil")")return}guardlet track = room.localParticipant.firstCameraVideoTrack as? LocalVideoTrack,let capturer = track.capturer as? CameraCapturerelse {- print("[CallKit] Multitasking camera access skipped; no local camera capturer uuid=\(uuid?.uuidString ?? "nil")")+ callKitLog("Multitasking camera access skipped; no local camera capturer uuid=\(uuid?.uuidString ?? "nil")")return}guard capturer.isMultitaskingAccessSupported else {- print("[CallKit] Multitasking camera access not supported uuid=\(uuid?.uuidString ?? "nil")")+ callKitLog("Multitasking camera access not supported uuid=\(uuid?.uuidString ?? "nil")")return}capturer.isMultitaskingAccessEnabled = true- print("[CallKit] Multitasking camera access enabled uuid=\(uuid?.uuidString ?? "nil") enabled=\(capturer.isMultitaskingAccessEnabled)")+ callKitLog("Multitasking camera access enabled uuid=\(uuid?.uuidString ?? "nil") enabled=\(capturer.isMultitaskingAccessEnabled)")}private func emitParticipantIdentities(from room: Room) {guard isCurrentRoom(room) else {- print("[CallKit] Ignoring participant identity emit from stale room")+ callKitLog("Ignoring participant identity emit from stale room")return}onParticipantIdentitiesChanged(participantIdentities(from: room))@@ -846,8 +903,10 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablidentity.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()}+ /// SID only: identities are `macro|<email>` and names are display names,+ /// neither of which may reach the persisted log.private func describeParticipant(_ participant: Participant) -> String {- "participantSid=\(describeOptional(participant.sid)) identity=\(describeOptional(participant.identity?.stringValue)) name=\(describeOptional(participant.name)) title=\(displayTitle(participant))"+ "participantSid=\(describeOptional(participant.sid)) agent=\(isAgentParticipant(participant))"}private func fallbackParticipantName(identity: String) -> String {@@ -865,34 +924,34 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet session = AVAudioSession.sharedInstance()switch session.recordPermission {case .granted:- print("[CallKit] Microphone permission granted uuid=\(uuid.uuidString)")+ callKitLog("Microphone permission granted uuid=\(uuid.uuidString)")if isCallKitAudioActive && !AudioManager.shared.engineAvailability.isInputAvailable {do {try AudioManager.shared.setEngineAvailability(.default)- print("[CallKit] Restored LiveKit input availability after microphone grant uuid=\(uuid.uuidString)")+ callKitLog("Restored LiveKit input availability after microphone grant uuid=\(uuid.uuidString)")} catch {- print("[CallKit] Failed to restore LiveKit input availability after microphone grant uuid=\(uuid.uuidString): \(error)")+ callKitLog("Failed to restore LiveKit input availability after microphone grant uuid=\(uuid.uuidString): \(error)", level: .error)}}return truecase .denied:setOutputOnlyAvailabilityIfNeeded(uuid: uuid)- print("[CallKit] Microphone permission denied uuid=\(uuid.uuidString); keeping native room connected muted")+ callKitLog("Microphone permission denied uuid=\(uuid.uuidString); keeping native room connected muted")return falsecase .undetermined:- print("[CallKit] Microphone permission undetermined uuid=\(uuid.uuidString); requesting permission")+ callKitLog("Microphone permission undetermined uuid=\(uuid.uuidString); requesting permission")let granted = await withCheckedContinuation { continuation insession.requestRecordPermission { granted incontinuation.resume(returning: granted)}}- print("[CallKit] Microphone permission request completed uuid=\(uuid.uuidString) granted=\(granted)")+ callKitLog("Microphone permission request completed uuid=\(uuid.uuidString) granted=\(granted)")if granted, isCallKitAudioActive {do {try AudioManager.shared.setEngineAvailability(.default)- print("[CallKit] Enabled LiveKit input availability after microphone permission request uuid=\(uuid.uuidString)")+ callKitLog("Enabled LiveKit input availability after microphone permission request uuid=\(uuid.uuidString)")} catch {- print("[CallKit] Failed to enable LiveKit input availability after microphone permission request uuid=\(uuid.uuidString): \(error)")+ callKitLog("Failed to enable LiveKit input availability after microphone permission request uuid=\(uuid.uuidString): \(error)", level: .error)}} else if !granted {setOutputOnlyAvailabilityIfNeeded(uuid: uuid)@@ -900,7 +959,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablreturn granted@unknown default:setOutputOnlyAvailabilityIfNeeded(uuid: uuid)- print("[CallKit] Microphone permission unknown uuid=\(uuid.uuidString); keeping native room connected muted")+ callKitLog("Microphone permission unknown uuid=\(uuid.uuidString); keeping native room connected muted")return false}}@@ -908,18 +967,18 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablprivate func ensureCameraPermission(uuid: UUID) async -> Bool {switch AVCaptureDevice.authorizationStatus(for: .video) {case .authorized:- print("[CallKit] Camera permission granted uuid=\(uuid.uuidString)")+ callKitLog("Camera permission granted uuid=\(uuid.uuidString)")return truecase .denied, .restricted:- print("[CallKit] Camera permission denied uuid=\(uuid.uuidString)")+ callKitLog("Camera permission denied uuid=\(uuid.uuidString)")return falsecase .notDetermined:- print("[CallKit] Camera permission undetermined uuid=\(uuid.uuidString); requesting permission")+ callKitLog("Camera permission undetermined uuid=\(uuid.uuidString); requesting permission")let granted = await AVCaptureDevice.requestAccess(for: .video)- print("[CallKit] Camera permission request completed uuid=\(uuid.uuidString) granted=\(granted)")+ callKitLog("Camera permission request completed uuid=\(uuid.uuidString) granted=\(granted)")return granted@unknown default:- print("[CallKit] Camera permission unknown uuid=\(uuid.uuidString)")+ callKitLog("Camera permission unknown uuid=\(uuid.uuidString)")return false}}@@ -944,7 +1003,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablguard activeCallUUID != nil else { return }guard !didApplyDefaultSpeakerRoute else { return }guard hasUsableAudioOutputRoute() else {- print("[CallKit] Skipping built-in speaker default because AVAudioSession route is not ready reason=\(reason) \(describeAudioSession())")+ callKitLog("Skipping built-in speaker default because AVAudioSession route is not ready reason=\(reason) \(describeAudioSession())")return}@@ -953,7 +1012,7 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablguard route.output != .speaker || !route.isSpeakerForced else {didApplyDefaultSpeakerRoute = true- print("[CallKit] Built-in speaker default already satisfied reason=\(reason)")+ callKitLog("Built-in speaker default already satisfied reason=\(reason)")return}if route.output != .unknown {@@ -963,21 +1022,21 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet didDefault = audioRouteController.defaultToSpeakerIfBuiltInRoute(reason: reason)didApplyDefaultSpeakerRoute = didDefaultif !didDefault {- print("[CallKit] Built-in speaker default did not apply; will retry on later route change reason=\(reason)")+ callKitLog("Built-in speaker default did not apply; will retry on later route change reason=\(reason)")}}private func setDesiredAudioMuted(_ muted: Bool, reason: String) {guard let room, let uuid = activeCallUUID else { return }let generation = microphoneCoordinator.setDesiredMuted(muted)- print("[CallKit] Native LiveKit desired microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) currentSnapshotMuted=\(activeCall?.isAudioMuted.description ?? "nil")")+ callKitLog("Native LiveKit desired microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) currentSnapshotMuted=\(activeCall?.isAudioMuted.description ?? "nil")")applyMicrophoneState(muted, room: room, uuid: uuid, generation: generation, reason: reason)}private func applyInitialMicrophoneState(room: Room, uuid: UUID, reason: String) {let muted = microphoneCoordinator.desiredMutedlet generation = microphoneCoordinator.generation- print("[CallKit] Applying initial LiveKit microphone state muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")+ callKitLog("Applying initial LiveKit microphone state muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")applyMicrophoneState(muted, room: room, uuid: uuid, generation: generation, reason: reason)}@@ -985,11 +1044,11 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablguard let room, let uuid = activeCallUUID else { return }guard activeCall?.connectionState == "connected" else { return }guard canEnableMicrophoneAudio() else {- print("[CallKit] Waiting to restore LiveKit microphone reason=\(reason) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ callKitLog("Waiting to restore LiveKit microphone reason=\(reason) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")return}guard let generation = microphoneCoordinator.beginRestoreIfNeeded() else {- print("[CallKit] Skipping LiveKit microphone restore reason=\(reason) desiredMuted=\(microphoneCoordinator.desiredMuted) lastKnownMuted=\(microphoneCoordinator.describeLastKnownMuted()) restoreInFlight=\(microphoneCoordinator.isRestoreInFlight) lastApplyFailed=\(microphoneCoordinator.lastApplyFailed)")+ callKitLog("Skipping LiveKit microphone restore reason=\(reason) desiredMuted=\(microphoneCoordinator.desiredMuted) lastKnownMuted=\(microphoneCoordinator.describeLastKnownMuted()) restoreInFlight=\(microphoneCoordinator.isRestoreInFlight) lastApplyFailed=\(microphoneCoordinator.lastApplyFailed)")return}@@ -1016,11 +1075,11 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabl}guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else {- print("[CallKit] Skipping LiveKit microphone unmute for stale desired state reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")+ callKitLog("Skipping LiveKit microphone unmute for stale desired state reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")return}guard self.canEnableMicrophoneAudio() else {- print("[CallKit] Deferring LiveKit microphone unmute until CallKit audio engine is ready reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ callKitLog("Deferring LiveKit microphone unmute until CallKit audio engine is ready reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")await self.markMicrophoneApplyDeferred(room: room, uuid: uuid, generation: generation)return}@@ -1031,23 +1090,23 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabllet microphoneWarning = enabled ? Task {try? await Task.sleep(nanoseconds: 5_000_000_000)if !Task.isCancelled {- print("[CallKit] Still waiting for LiveKit microphone enable reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ callKitLog("Still waiting for LiveKit microphone enable reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")}} : nildefer { microphoneWarning?.cancel() }- print("[CallKit] Applying native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ callKitLog("Applying native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")try await room.localParticipant.setMicrophone(enabled: enabled)guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else {- print("[CallKit] Native LiveKit microphone apply completed after desired state changed reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")+ callKitLog("Native LiveKit microphone apply completed after desired state changed reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted)")return}self.updateAudioMuted(muted, room: room, uuid: uuid, expectedGeneration: generation, applyFailed: false)- print("[CallKit] Native LiveKit microphone applied muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")+ callKitLog("Native LiveKit microphone applied muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")} catch is CancellationError {- print("[CallKit] LiveKit microphone apply cancelled reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")+ callKitLog("LiveKit microphone apply cancelled reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation)")} catch {- print("[CallKit] Failed to apply native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted): \(error)")+ callKitLog("Failed to apply native LiveKit microphone muted=\(muted) reason=\(reason) uuid=\(uuid.uuidString) generation=\(generation) desiredMuted=\(self.microphoneCoordinator.desiredMuted): \(error)", level: .error)guard self.isCurrentMicrophoneOperation(generation, room: room, uuid: uuid, desiredMuted: muted) else { return }self.updateAudioMuted(muted, room: room, uuid: uuid, expectedGeneration: generation, applyFailed: true)}@@ -1079,16 +1138,16 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendabltry AudioManager.shared.setEngineAvailability(AudioEngineAvailability(isInputAvailable: false, isOutputAvailable: true))- print("[CallKit] Set LiveKit audio engine to output-only uuid=\(uuid.uuidString) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ callKitLog("Set LiveKit audio engine to output-only uuid=\(uuid.uuidString) running=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")} catch {- print("[CallKit] Failed to set LiveKit audio engine to output-only uuid=\(uuid.uuidString): \(error) \(describeAudioSession())")+ callKitLog("Failed to set LiveKit audio engine to output-only uuid=\(uuid.uuidString): \(error) \(describeAudioSession())", level: .error)}}private func describeAudioSession() -> String {let session = AVAudioSession.sharedInstance()- let inputs = session.currentRoute.inputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")- let outputs = session.currentRoute.outputs.map { "\($0.portType.rawValue):\($0.portName)" }.joined(separator: ",")+ let inputs = session.currentRoute.inputs.map { $0.portType.rawValue }.joined(separator: ",")+ let outputs = session.currentRoute.outputs.map { $0.portType.rawValue }.joined(separator: ",")return "audioSession(category=\(session.category.rawValue), mode=\(session.mode.rawValue), activeSecondaryAudioSilenced=\(session.secondaryAudioShouldBeSilencedHint), recordPermission=\(describe(session.recordPermission)), sampleRate=\(session.sampleRate), ioBuffer=\(session.ioBufferDuration), inputs=[\(inputs)], outputs=[\(outputs)])"}@@ -1132,17 +1191,17 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked SendablactualMuted: isMuted,applyFailed: applyFailed) else {- print("[CallKit] Ignoring stale native microphone state update uuid=\(uuid.uuidString) generation=\(expectedGeneration) currentGeneration=\(self.microphoneCoordinator.generation) actualMuted=\(isMuted)")+ callKitLog("Ignoring stale native microphone state update uuid=\(uuid.uuidString) generation=\(expectedGeneration) currentGeneration=\(self.microphoneCoordinator.generation) actualMuted=\(isMuted)")return}let previousMuted = snapshot.isAudioMutedguard previousMuted != isMuted else {- print("[CallKit] Native LiveKit microphone state unchanged uuid=\(uuid.uuidString) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")+ callKitLog("Native LiveKit microphone state unchanged uuid=\(uuid.uuidString) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")return}snapshot.isAudioMuted = isMutedself.activeCall = snapshot- print("[CallKit] Native LiveKit microphone state updated uuid=\(uuid.uuidString) previousMuted=\(previousMuted) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")+ callKitLog("Native LiveKit microphone state updated uuid=\(uuid.uuidString) previousMuted=\(previousMuted) actualMuted=\(isMuted) desiredMuted=\(self.microphoneCoordinator.desiredMuted) generation=\(expectedGeneration)")self.videoOverlay.setAudioMuted(isMuted)self.emitSnapshot()}@@ -1202,15 +1261,15 @@ final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendablprivate func emitSnapshot() {if let activeCall {- print("[CallKit] Emitting native snapshot state=\(activeCall.connectionState) channelId=\(activeCall.channelId) callId=\(activeCall.callId)")+ callKitLog("Emitting native snapshot state=\(activeCall.connectionState) channelId=\(activeCall.channelId) callId=\(activeCall.callId)")} else {- print("[CallKit] Emitting native snapshot state=disconnected")+ callKitLog("Emitting native snapshot state=disconnected")}onSnapshotChanged(activeCall)}private func emitDisconnectedSnapshot(_ snapshot: ActiveCallSnapshot) {- print("[CallKit] Emitting native snapshot state=disconnected channelId=\(snapshot.channelId) callId=\(snapshot.callId)")+ callKitLog("Emitting native snapshot state=disconnected channelId=\(snapshot.channelId) callId=\(snapshot.callId)")onSnapshotChanged(snapshot)}}@@ -1272,36 +1331,36 @@ private final class CallKitAudioEngineLogger: AudioEngineObserver, @unchecked Sevar desiredMutedProvider: (() -> Bool?)?func engineDidCreate(_ engine: AVAudioEngine) -> Int {- print("[CallKit] LiveKit audio engine did create desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine did create desiredMuted=\(describeDesiredMuted())")return next?.engineDidCreate(engine) ?? 0}func engineWillEnable(_ engine: AVAudioEngine, isPlayoutEnabled: Bool, isRecordingEnabled: Bool) -> Int {- print("[CallKit] LiveKit audio engine will enable playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine will enable playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")let result = next?.engineWillEnable(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0- print("[CallKit] LiveKit audio engine will enable result=\(result)")+ callKitLog("LiveKit audio engine will enable result=\(result)")return result}func engineWillStart(_ engine: AVAudioEngine, isPlayoutEnabled: Bool, isRecordingEnabled: Bool) -> Int {- print("[CallKit] LiveKit audio engine will start playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine will start playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")let result = next?.engineWillStart(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0- print("[CallKit] LiveKit audio engine will start result=\(result)")+ callKitLog("LiveKit audio engine will start result=\(result)")return result}func engineDidStop(_ engine: AVAudioEngine, isPlayoutEnabled: Bool, isRecordingEnabled: Bool) -> Int {- print("[CallKit] LiveKit audio engine did stop playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine did stop playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")return next?.engineDidStop(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0}func engineDidDisable(_ engine: AVAudioEngine, isPlayoutEnabled: Bool, isRecordingEnabled: Bool) -> Int {- print("[CallKit] LiveKit audio engine did disable playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine did disable playout=\(isPlayoutEnabled) recording=\(isRecordingEnabled) desiredMuted=\(describeDesiredMuted())")return next?.engineDidDisable(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0}func engineWillRelease(_ engine: AVAudioEngine) -> Int {- print("[CallKit] LiveKit audio engine will release desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine will release desiredMuted=\(describeDesiredMuted())")return next?.engineWillRelease(engine) ?? 0}@@ -1312,7 +1371,7 @@ private final class CallKitAudioEngineLogger: AudioEngineObserver, @unchecked Seformat: AVAudioFormat,context: [AnyHashable: Any]) -> Int {- print("[CallKit] LiveKit audio engine will connect output format=\(format) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine will connect output format=\(format) desiredMuted=\(describeDesiredMuted())")return next?.engineWillConnectOutput(engine, src: src, dst: dst, format: format, context: context) ?? 0}@@ -1323,7 +1382,7 @@ private final class CallKitAudioEngineLogger: AudioEngineObserver, @unchecked Seformat: AVAudioFormat,context: [AnyHashable: Any]) -> Int {- print("[CallKit] LiveKit audio engine will connect input format=\(format) desiredMuted=\(describeDesiredMuted())")+ callKitLog("LiveKit audio engine will connect input format=\(format) desiredMuted=\(describeDesiredMuted())")return next?.engineWillConnectInput(engine, src: src, dst: dst, format: format, context: context) ?? 0}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/RingDeclineReporter.swift b/apps/web/tauri/callkit_plugin/ios/Sources/RingDeclineReporter.swiftindex c9975070cc..ea1469caa4 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/RingDeclineReporter.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/RingDeclineReporter.swift@@ -27,7 +27,7 @@ enum RingDeclineReporter {static func report(uuid: UUID, ringStatusUrl: String, bearerToken: String) {guard let url = declineUrl(fromRingStatusUrl: ringStatusUrl) else {- print("[CallKit] Invalid ringStatusUrl for decline uuid=\(uuid.uuidString)")+ callKitLog("Invalid ringStatusUrl for decline uuid=\(uuid.uuidString)")return}@@ -44,15 +44,15 @@ enum RingDeclineReporter {var request = URLRequest(url: url)request.httpMethod = "POST"request.setValue("Bearer \(bearerToken)", forHTTPHeaderField: "Authorization")- print("[CallKit] Reporting decline uuid=\(uuid.uuidString)")+ callKitLog("Reporting decline uuid=\(uuid.uuidString)")let task = session.dataTask(with: request) { _, response, error inif let error {- print("[CallKit] Decline report failed uuid=\(uuid.uuidString) error=\(error.localizedDescription)")+ callKitLog("Decline report failed uuid=\(uuid.uuidString) error=\(error.localizedDescription)", level: .error)} else if let http = response as? HTTPURLResponse, !(200 ..< 300).contains(http.statusCode) {// 404 means the call already ended or was replaced; nothing left to decline.- print("[CallKit] Decline report rejected uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")+ callKitLog("Decline report rejected uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")} else {- print("[CallKit] Decline reported uuid=\(uuid.uuidString)")+ callKitLog("Decline reported uuid=\(uuid.uuidString)")}DispatchQueue.main.async(execute: finish)}diff --git a/apps/web/tauri/callkit_plugin/ios/Sources/RingStatePoller.swift b/apps/web/tauri/callkit_plugin/ios/Sources/RingStatePoller.swiftindex 510e2d7b0f..cd2a1c7190 100644--- a/apps/web/tauri/callkit_plugin/ios/Sources/RingStatePoller.swift+++ b/apps/web/tauri/callkit_plugin/ios/Sources/RingStatePoller.swift@@ -55,7 +55,7 @@ final class RingStatePoller {func start() {guard deadline == nil, !isCancelled else { return }deadline = Date().addingTimeInterval(window)- print("[CallKit] Ring-status polling started uuid=\(uuid.uuidString)")+ callKitLog("Ring-status polling started uuid=\(uuid.uuidString)")scheduleTick()}@@ -66,14 +66,14 @@ final class RingStatePoller {pendingTick?.cancel()pendingTick = nilsession.invalidateAndCancel()- print("[CallKit] Ring-status polling cancelled uuid=\(uuid.uuidString)")+ callKitLog("Ring-status polling cancelled uuid=\(uuid.uuidString)")}private func scheduleTick() {guard !isCancelled, !isResolved else { return }guard let deadline, Date().addingTimeInterval(interval) <= deadline else {// Window expired: stop polling and leave the ring as-is.- print("[CallKit] Ring-status polling window expired uuid=\(uuid.uuidString)")+ callKitLog("Ring-status polling window expired uuid=\(uuid.uuidString)")return}let work = DispatchWorkItem { [weak self] in@@ -99,7 +99,7 @@ final class RingStatePoller {guard !isCancelled, !isResolved else { return }if let error {- print("[CallKit] Ring-status poll transient error uuid=\(uuid.uuidString) error=\(error.localizedDescription)")+ callKitLog("Ring-status poll transient error uuid=\(uuid.uuidString) error=\(error.localizedDescription)")scheduleTick()return}@@ -115,17 +115,17 @@ final class RingStatePoller {case 401, 403, 404:// Invalid token or a backend without the endpoint — retrying// cannot succeed; stop and leave the ring as-is.- print("[CallKit] Ring-status polling stopped uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")+ callKitLog("Ring-status polling stopped uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")returndefault:- print("[CallKit] Ring-status poll transient HTTP error uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")+ callKitLog("Ring-status poll transient HTTP error uuid=\(uuid.uuidString) httpStatus=\(http.statusCode)")scheduleTick()return}guard let data,let decoded = try? JSONDecoder().decode(StatusResponse.self, from: data) else {- print("[CallKit] Ring-status poll returned undecodable body uuid=\(uuid.uuidString)")+ callKitLog("Ring-status poll returned undecodable body uuid=\(uuid.uuidString)")scheduleTick()return}@@ -140,7 +140,8 @@ final class RingStatePoller {case "ringing":scheduleTick()default:- print("[CallKit] Ring-status poll returned unknown status '\(decoded.status)' uuid=\(uuid.uuidString)")+ // The status is unvalidated server text; never write it to the public log.+ callKitLog("Ring-status poll returned an unknown status uuid=\(uuid.uuidString)")scheduleTick()}}diff --git a/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/HarnessApp.swift b/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/HarnessApp.swiftindex 701ab332ac..db1658e0a5 100644--- a/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/HarnessApp.swift+++ b/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/HarnessApp.swift@@ -25,6 +25,7 @@ final class HarnessApp: UIResponder, UIApplicationDelegate {self.window = windowwindow.makeKeyAndVisible()overlay.attach(to: webview)+ overlay.isCallActive = { true }overlay.setMode(.expanded)overlay.onSelectRemoteParticipant = { [weak self] id inguard let self else { return }diff --git a/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/project.yml b/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/project.ymlindex 77aa09dd74..89f3268c61 100644--- a/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/project.yml+++ b/apps/web/tauri/callkit_plugin/ios/Tests/OverlayHarness/project.yml@@ -20,6 +20,7 @@ targets:- ../../Sources/CallVideoOverlayController.swift- ../../Sources/ParticipantStripScrollView.swift- ../../Sources/CallAudioRouteController.swift+ - ../../Sources/CallKitLog.swiftdependencies:- package: LiveKitsettings:diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 6e27fe56f3..63161f57b6 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -905,6 +905,10 @@ impl CallRtcClient for NoOpCallRtcClient {Ok(())}+ async fn list_rooms(&self) -> anyhow::Result<Vec<call::domain::models::RtcRoom>> {+ Ok(Vec::new())+ }+async fn generate_token<'a>(&self,_room_name: &str,diff --git a/crates/call/AGENTS.md b/crates/call/AGENTS.mdindex dff4064baa..7cf3c275f8 100644--- a/crates/call/AGENTS.md+++ b/crates/call/AGENTS.md@@ -14,7 +14,8 @@ in-call chat.- `src/domain/meetings.rs`: scheduled-meeting ↔ call association (used by`calendar_events`/`calendar_scheduling` meeting links).- `src/inbound/axum_router.rs`, `src/inbound/stale_call_sweeper.rs`: HTTP routes- and the sweeper that ends abandoned calls.+ and the sweeper that ends abandoned calls and deletes orphaned RTC rooms+ (`src/domain/service/orphan_rooms.rs`).- `src/outbound/livekit_rtc_client.rs`: LiveKit adapter.- `src/outbound/pg_call_repo.rs`, `src/outbound/pg_voice_repo.rs`: Postgres.- `src/outbound/ai_call_summarizer.rs`, `src/outbound/s3_recording_storage.rs`:@@ -53,6 +54,10 @@ in-call chat.a per-device signal.- The team-memory helper only compiles with the `ports` feature (#7912) — don'treintroduce an unconditional dependency on it.+- RTC tokens live 6h and can't be revoked, and LiveKit recreates a deleted room+ when one connects. Only a room named after an archived `call_records` row is+ orphaned (call ids are never reused); meeting preparations and get-or-create+ candidate rooms have no `calls` row yet and must be left alone.## Relateddiff --git a/crates/call/src/domain/models.rs b/crates/call/src/domain/models.rsindex d9ee6aaaf5..7f1e0a449f 100644--- a/crates/call/src/domain/models.rs+++ b/crates/call/src/domain/models.rs@@ -152,6 +152,15 @@ pub struct VerifiedRingToken {pub room: Option<String>,}+/// An RTC room that currently exists on the provider.+#[derive(Debug, Clone)]+pub struct RtcRoom {+ /// The room name; Macro names rooms after their call id.+ pub name: String,+ /// When the provider created the room.+ pub created_at: DateTime<Utc>,+}+/// Response for the leave/end call operation.#[derive(Debug, serde::Serialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rsindex bd9a517889..a0287f7892 100644--- a/crates/call/src/domain/ports.rs+++ b/crates/call/src/domain/ports.rs@@ -34,7 +34,8 @@ use super::models::{CallRecordTranscriptSegment, CallTokenResponse, CallTranscriptCustomSpeakerResult,CallWebhookEvent, EgressS3Config, EnrichedCallTranscript, GetBatchCallRecordPreviewRequest,GetBatchCallRecordPreviewResponse, GetCallRecordsRequest, LeaveCallResponse,- RingStatusResponse, TranscriptSegmentRequest, VerifiedRingToken, VoipPushPayloadRequest,+ RingStatusResponse, RtcRoom, TranscriptSegmentRequest, VerifiedRingToken,+ VoipPushPayloadRequest,};/// Repository port for persisting call state to the database.@@ -691,9 +692,12 @@ pub trait CallRtcClient: Send + Sync + 'static {/// Reserve an empty room for setup, expiring automatically without participants.fn prepare_room(&self, room_name: &str) -> impl Future<Output = anyhow::Result<()>> + Send;- /// Delete an RTC room.+ /// Delete an RTC room. Deleting a room that no longer exists succeeds.fn delete_room(&self, room_name: &str) -> impl Future<Output = anyhow::Result<()>> + Send;+ /// Every RTC room that currently exists.+ fn list_rooms(&self) -> impl Future<Output = anyhow::Result<Vec<RtcRoom>>> + Send;+/// Read connected identities and names without joining the room.fn list_meeting_participants(&self,@@ -885,6 +889,7 @@ pub trait CallService: Send + Sync + 'static {/// Backstop for missed `participant_left` webhooks: marks participants/// and guests no longer connected to their RTC room as left, and archives/// calls that leaves empty. One call's failure does not stop the rest.+ /// Then deletes RTC rooms that stale tokens recreated for archived calls.fn reconcile_stale_calls(&self) -> impl Future<Output = Result<(), CallError>> + Send;/// List all active calls in channels the user is an active member of,diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rsindex 037bcaded8..2055fc5066 100644--- a/crates/call/src/domain/service.rs+++ b/crates/call/src/domain/service.rs@@ -7,6 +7,7 @@ mod channel_startup;mod guest_chat;mod meeting_invites;mod meetings;+mod orphan_rooms;mod reconcile;use connection::domain::ports::ConnectionService;@@ -812,14 +813,16 @@ impl<.list_active_calls().await.map_err(|e| CallError::Internal(e.into()))?;- for call in calls {- self.reconcile_call(&call, now)+ for call in &calls {+ self.reconcile_call(call, now).await.inspect_err(|error| {tracing::warn!(call_id = %call.id, error = ?error, "failed to reconcile call")}).ok();}+ // A failed sweep is recorded on its span and retried next interval.+ self.sweep_orphan_rooms(&calls, now).await.ok();Ok(())}@@ -984,12 +987,16 @@ impl<channel_id: &Uuid,user_id: MacroUserIdStr<'_>,) -> Result<LeaveCallResponse, CallError> {- let call = self+ let Some(call) = self.repo.get_call_by_channel_id(channel_id).await.map_err(|e| CallError::Internal(e.into()))?- .ok_or_else(|| CallError::NotFound(channel_id.to_string()))?;+ else {+ // A stale token may still hold the user in the last call's room.+ self.leave_archived_channel_room(channel_id, user_id).await;+ return Err(CallError::NotFound(channel_id.to_string()));+ };// Remove participant from DB (idempotent — no-op if already removed by webhook).self.repo@@ -1099,11 +1106,18 @@ impl<.await?;}+ // Identities are `macro|<email>`: log which kind of participant this+ // is, never who.+ let participant_kind = match (&event.participant_identity, &event.guest_identity) {+ (Some(_), _) => "user",+ (None, Some(_)) => "guest",+ (None, None) => "none",+ };tracing::info!(event_type = %event.event,event_id = %event.id,room_name = ?event.room_name,- participant = ?event.participant_identity,+ participant_kind,"processing call webhook event");@@ -1143,13 +1157,22 @@ impl<}"participant_joined" => {if let (Some(room), Some(identity)) = (&event.room_name, &event.guest_identity) {- if let Some(call) = self+ match self.repo.get_call_by_room_name(room).await.map_err(|e| CallError::Internal(e.into()))?{- self.repo.reconcile_guest(&call.id, *identity, true).await?;+ Some(call) => {+ self.repo.reconcile_guest(&call.id, *identity, true).await?;+ }+ None => {+ self.evict_from_untracked_room(+ room,+ orphan_rooms::RoomParticipant::Guest(*identity),+ )+ .await?;+ }}return Ok(());}@@ -1169,7 +1192,12 @@ impl<.await.map_err(|e| CallError::Internal(e.into()))?else {- return Ok(());+ return self+ .evict_from_untracked_room(+ room_name,+ orphan_rooms::RoomParticipant::User(participant_identity.copied()),+ )+ .await;};// Reconcile: idempotent upsert (handles reconnect/race conditions).diff --git a/crates/call/src/domain/service/orphan_rooms.rs b/crates/call/src/domain/service/orphan_rooms.rsnew file mode 100644index 0000000000..983e5ab95b--- /dev/null+++ b/crates/call/src/domain/service/orphan_rooms.rs@@ -0,0 +1,251 @@+//! Tear down RTC rooms that outlived their call.+//!+//! RTC tokens stay valid for hours and cannot be revoked, and the provider+//! recreates a deleted room when a token for it connects. A client answering a+//! stale ring therefore lands in a room no call tracks. A room is orphaned only+//! when it is named after an archived call: call ids are never reused, so an+//! archived call's room can never host a live session again. Every other room+//! without an active call (meeting preparations, the get-or-create race's+//! candidate room, rooms this deployment did not create) is left alone.++use std::collections::HashSet;+use std::sync::Arc;++use chrono::{DateTime, Utc};+use filter_ast::Expr;+use item_filters::ast::call::CallLiteral;++use super::reconcile::RECONCILE_GRACE;+use super::*;+use crate::domain::meetings::GuestId;++/// A person connected to an RTC room.+pub(super) enum RoomParticipant<'a> {+ /// A Macro user.+ User(MacroUserIdStr<'a>),+ /// A non-account meeting guest.+ Guest(GuestId),+}++impl RoomParticipant<'_> {+ /// Names the kind of participant for logs without identifying them.+ fn kind(&self) -> &'static str {+ match self {+ Self::User(_) => "user",+ Self::Guest(_) => "guest",+ }+ }+}++impl<R, C, Cn, E, N, S, Sm, V, Vr, B> CallServiceImpl<R, C, Cn, E, N, S, Sm, V, Vr, B>+where+ R: CallRepository + Clone,+ C: CallRtcClient,+ Cn: ConnectionService,+ E: EntityAccessService,+ N: NotificationIngress,+ S: RecordingStorage,+ Sm: CallSummarizer + Clone,+ V: VoipPushSender,+ Vr: VoiceRepository + Clone,+ B: MacroEventBroker + Clone,+{+ /// The archived call a room without an active call belongs to.+ async fn archived_call_for_room(&self, room_name: &str) -> Result<Option<Uuid>, CallError> {+ let Ok(call_id) = Uuid::parse_str(room_name) else {+ return Ok(None);+ };+ let record = self+ .repo+ .get_call_record_by_call_id(&call_id)+ .await+ .map_err(|e| CallError::Internal(e.into()))?;+ Ok(record+ .filter(|record| !record.is_active && record.room_name.as_deref() == Some(room_name))+ .map(|record| record.call_id))+ }++ /// Handles a participant joining a room that has no active call: when the+ /// room belongs to an archived call, removes them and deletes the room.+ pub(super) async fn evict_from_untracked_room(+ &self,+ room_name: &str,+ participant: RoomParticipant<'_>,+ ) -> Result<(), CallError> {+ let participant_kind = participant.kind();+ let Some(call_id) = self.archived_call_for_room(room_name).await? else {+ tracing::warn!(+ room_name,+ call_record_exists = false,+ participant_kind,+ action = "ignored",+ "participant joined an RTC room that belongs to no call"+ );+ return Ok(());+ };+ let removed = match participant {+ RoomParticipant::User(user_id) => {+ self.rtc_client.remove_participant(room_name, user_id).await+ }+ RoomParticipant::Guest(guest_id) => {+ self.rtc_client.remove_guest(room_name, guest_id).await+ }+ };+ removed+ .inspect_err(|error| {+ tracing::error!(error = ?error, %call_id, "failed to remove participant from archived call room");+ })+ .ok();+ self.rtc_client+ .delete_room(room_name)+ .await+ .inspect_err(|error| {+ tracing::error!(error = ?error, %call_id, "failed to delete archived call room");+ })+ .ok();+ tracing::warn!(+ room_name,+ %call_id,+ call_record_exists = true,+ participant_kind,+ action = "evicted",+ "participant joined the RTC room of an archived call; removed it and deleted the room"+ );+ Ok(())+ }++ /// Deletes rooms of archived calls that a stale token recreated, once they+ /// are older than the reconcile grace period.+ #[tracing::instrument(+ name = "calls.sweep_orphan_rooms",+ err,+ skip_all,+ fields(+ rooms_listed = tracing::field::Empty,+ rooms_untracked = tracing::field::Empty,+ rooms_deleted = tracing::field::Empty,+ )+ )]+ pub(super) async fn sweep_orphan_rooms(+ &self,+ active_calls: &[Call],+ now: DateTime<Utc>,+ ) -> Result<(), CallError> {+ let rooms = self+ .rtc_client+ .list_rooms()+ .await+ .map_err(CallError::Internal)?;+ let active_rooms: HashSet<&str> = active_calls+ .iter()+ .map(|call| call.room_name.as_str())+ .collect();+ let mut untracked = 0_usize;+ let mut deleted = 0_usize;+ for room in &rooms {+ if active_rooms.contains(room.name.as_str()) || now - room.created_at < RECONCILE_GRACE+ {+ continue;+ }+ untracked += 1;+ let call_id = match self.archived_call_for_room(&room.name).await {+ Ok(Some(call_id)) => call_id,+ Ok(None) => continue,+ Err(error) => {+ tracing::warn!(error = ?error, room_name = room.name, "failed to look up the call of an untracked RTC room");+ continue;+ }+ };+ match self.rtc_client.delete_room(&room.name).await {+ Ok(()) => {+ deleted += 1;+ tracing::warn!(+ room_name = room.name,+ %call_id,+ call_record_exists = true,+ action = "deleted",+ "deleted an RTC room that outlived its archived call"+ );+ }+ Err(error) => {+ tracing::error!(error = ?error, %call_id, "failed to delete archived call room");+ }+ }+ }+ let span = tracing::Span::current();+ span.record("rooms_listed", rooms.len());+ span.record("rooms_untracked", untracked);+ span.record("rooms_deleted", deleted);+ Ok(())+ }++ /// Best-effort: removes a user whose leave found no active call from the+ /// room of the channel's latest call, when that call is archived and the+ /// user is still connected to it.+ pub(super) async fn leave_archived_channel_room(+ &self,+ channel_id: &Uuid,+ user_id: MacroUserIdStr<'_>,+ ) {+ let filter = Some(Arc::new(Expr::Literal(CallLiteral::ChannelId(*channel_id))));+ let latest = match self+ .repo+ .get_call_records_by_user(+ user_id.copied(),+ 1,+ &filter,+ CallRecordPage {+ by_start: true,+ after: None,+ },+ )+ .await+ {+ Ok(records) => records.into_iter().next(),+ Err(error) => {+ tracing::warn!(error = ?error, %channel_id, "failed to look up the channel's latest call");+ return;+ }+ };+ let Some((call_id, room_name)) = latest+ .filter(|record| !record.is_active)+ .and_then(|record| Some((record.call_id, record.room_name?)))+ else {+ return;+ };+ let connected = match self+ .rtc_client+ .list_participant_identities(&room_name)+ .await+ {+ Ok(connected) => connected.unwrap_or_default(),+ Err(error) => {+ tracing::warn!(error = ?error, %call_id, "failed to list archived call room participants");+ return;+ }+ };+ if !connected+ .iter()+ .any(|identity| identity == user_id.as_ref())+ {+ return;+ }+ match self+ .rtc_client+ .remove_participant(&room_name, user_id)+ .await+ {+ Ok(()) => tracing::warn!(+ room_name,+ %call_id,+ call_record_exists = true,+ participant_kind = "user",+ action = "removed",+ "leave found the user still connected to an archived call's RTC room"+ ),+ Err(error) => {+ tracing::error!(error = ?error, %call_id, "failed to remove participant from archived call room");+ }+ }+ }+}diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rsindex c7ff993f9a..95c89c148a 100644--- a/crates/call/src/domain/service/test.rs+++ b/crates/call/src/domain/service/test.rs@@ -31,12 +31,14 @@ mod guest_chat;mod meeting_invites;mod meeting_participants;mod meeting_startup;+mod orphan_rooms;use crate::domain::meetings::GuestId;use crate::domain::models::{ActiveCallSummary, AddParticipantError, ArchivedCall, Call, CallError, CallParticipant,CallRecord, CallRecordTranscriptSegment, CallWebhookEvent, DeletedCallRecordStorageKeys,- EditCallRecordRequest, EgressS3Config, RingStatus, VerifiedRingToken, VoipPushPayloadRequest,+ EditCallRecordRequest, EgressS3Config, RingStatus, RtcRoom, VerifiedRingToken,+ VoipPushPayloadRequest,};use crate::domain::ports::{CallRtcClient, CallService, CallSummarizer, MockCallRepository, MockCallRtcClient,@@ -122,6 +124,10 @@ impl CallRtcClient for MockRtcClient {Ok(())}+ async fn list_rooms(&self) -> anyhow::Result<Vec<RtcRoom>> {+ Ok(Vec::new())+ }+async fn generate_token<'a>(&self,room_name: &str,diff --git a/crates/call/src/domain/service/test/orphan_rooms.rs b/crates/call/src/domain/service/test/orphan_rooms.rsnew file mode 100644index 0000000000..d0753b6d1a--- /dev/null+++ b/crates/call/src/domain/service/test/orphan_rooms.rs@@ -0,0 +1,323 @@+use super::*;++const ORPHAN_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5c001);+const PREPARED_ROOM_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5c002);+const YOUNG_ORPHAN_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5c003);+const ORPHAN_CHANNEL_ID: Uuid = Uuid::from_u128(0x3f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7c01);+const ORPHAN_GUEST_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5c004);+const STALE_JOINER: &str = "[email protected]";++/// The archived record of a call whose room is named after its id.+fn archived_record(call_id: Uuid) -> CallRecord {+ let mut record = call_record_for_mutation();+ record.call_id = call_id;+ record.channel_id = Some(ORPHAN_CHANNEL_ID);+ record.room_name = Some(call_id.to_string());+ record+}++fn joined_webhook(+ room_name: &str,+ participant_identity: Option<&'static str>,+ guest_identity: Option<GuestId>,+) -> MockCallRtcClient {+ let event = CallWebhookEvent {+ guest_identity,+ event: "participant_joined".to_string(),+ id: "participant-joined-event-id".to_string(),+ room_name: Some(room_name.to_string()),+ participant_identity: participant_identity.map(|email| user(email).into_owned()),+ egress_id: None,+ file_url: None,+ created_at: 1_775_000_000,+ };+ let mut rtc_client = MockCallRtcClient::new();+ rtc_client+ .expect_receive_webhook()+ .times(1)+ .return_once(move |_, _| Ok(event));+ rtc_client+}++/// No active call owns the room; the record lookup by its id answers `record`.+fn untracked_room_repo(record: Option<CallRecord>) -> MockCallRepository {+ let mut repo = MockCallRepository::new();+ repo.expect_get_call_by_room_name()+ .times(1)+ .returning(|_| Box::pin(async { Ok(None) }));+ repo.expect_get_call_record_by_call_id()+ .times(1)+ .return_once(move |_| Box::pin(async move { Ok(record) }));+ repo+}++async fn process_join(repo: MockCallRepository, rtc_client: MockCallRtcClient) {+ build_webhook_service(repo, rtc_client, RecordingEventBroker::default())+ .process_webhook_event("webhook-body", "webhook-token")+ .await+ .expect("participant-joined webhook succeeds");+}++#[tokio::test]+async fn user_joining_an_archived_call_room_is_removed_and_the_room_deleted() {+ let room_name = ORPHAN_CALL_ID.to_string();+ let mut rtc_client = joined_webhook(&room_name, Some(STALE_JOINER), None);+ rtc_client+ .expect_remove_participant()+ .withf(|room_name, identity| {+ room_name == ORPHAN_CALL_ID.to_string()+ && identity.as_ref() == user(STALE_JOINER).as_ref()+ })+ .times(1)+ .returning(|_, _| Box::pin(async { Ok(()) }));+ rtc_client+ .expect_delete_room()+ .withf(|room_name| room_name == ORPHAN_CALL_ID.to_string())+ .times(1)+ .returning(|_| Box::pin(async { Ok(()) }));++ let mut repo = untracked_room_repo(Some(archived_record(ORPHAN_CALL_ID)));+ // The stale joiner never becomes a participant of the archived call.+ repo.expect_add_participant().never();++ process_join(repo, rtc_client).await;+}++#[tokio::test]+async fn guest_joining_an_archived_call_room_is_removed_and_the_room_deleted() {+ let room_name = ORPHAN_CALL_ID.to_string();+ let guest_id = GuestId::from_uuid(ORPHAN_GUEST_ID);+ let mut rtc_client = joined_webhook(&room_name, None, Some(guest_id));+ rtc_client+ .expect_remove_guest()+ .withf(move |room_name, guest| {+ room_name == ORPHAN_CALL_ID.to_string() && *guest == guest_id+ })+ .times(1)+ .returning(|_, _| Box::pin(async { Ok(()) }));+ rtc_client+ .expect_delete_room()+ .withf(|room_name| room_name == ORPHAN_CALL_ID.to_string())+ .times(1)+ .returning(|_| Box::pin(async { Ok(()) }));++ let mut repo = untracked_room_repo(Some(archived_record(ORPHAN_CALL_ID)));+ repo.expect_reconcile_guest().never();++ process_join(repo, rtc_client).await;+}++#[tokio::test]+async fn joins_to_rooms_without_an_archived_call_are_left_alone() {+ let mut active = archived_record(ORPHAN_CALL_ID);+ active.is_active = true;+ let mut renamed_room = archived_record(ORPHAN_CALL_ID);+ renamed_room.room_name = Some(ORPHAN_CHANNEL_ID.to_string());+ // A meeting preparation or the get-or-create race's candidate room has no+ // record; an active record or one bound to a different room is not orphaned.+ for record in [None, Some(active), Some(renamed_room)] {+ let mut rtc_client = joined_webhook(&ORPHAN_CALL_ID.to_string(), Some(STALE_JOINER), None);+ rtc_client.expect_remove_participant().never();+ rtc_client.expect_delete_room().never();++ process_join(untracked_room_repo(record), rtc_client).await;+ }+}++#[tokio::test]+async fn joins_to_rooms_not_named_after_a_call_are_left_alone() {+ let mut rtc_client = joined_webhook("not-a-call-room", Some(STALE_JOINER), None);+ rtc_client.expect_remove_participant().never();+ rtc_client.expect_delete_room().never();+ let mut repo = MockCallRepository::new();+ repo.expect_get_call_by_room_name()+ .times(1)+ .returning(|_| Box::pin(async { Ok(None) }));+ repo.expect_get_call_record_by_call_id().never();++ process_join(repo, rtc_client).await;+}++#[tokio::test]+async fn service_agents_joining_an_untracked_room_are_left_alone() {+ // Agent and egress identities parse to neither a user nor a guest.+ let mut rtc_client = joined_webhook(&ORPHAN_CALL_ID.to_string(), None, None);+ rtc_client.expect_remove_participant().never();+ rtc_client.expect_delete_room().never();+ let mut repo = MockCallRepository::new();+ repo.expect_get_call_by_room_name().never();+ repo.expect_get_call_record_by_call_id().never();++ process_join(repo, rtc_client).await;+}++const SWEPT_ACTIVE_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5c005);++fn rtc_room(name: String, minutes_old: i64) -> RtcRoom {+ RtcRoom {+ name,+ created_at: minutes_ago(minutes_old),+ }+}++#[tokio::test]+async fn sweep_deletes_only_archived_call_rooms_past_the_grace_period() {+ let active_room = SWEPT_ACTIVE_CALL_ID.to_string();+ let mut repo = MockCallRepository::new();+ repo.expect_list_active_calls().times(1).returning(|| {+ let call = Call {+ id: SWEPT_ACTIVE_CALL_ID,+ channel_id: None,+ room_name: SWEPT_ACTIVE_CALL_ID.to_string(),+ created_by: STARTED_EVENT_CREATOR.to_string(),+ created_at: minutes_ago(30),+ egress_id: None,+ };+ Box::pin(async move { Ok(vec![call]) })+ });+ // The active call is still occupied, so reconciliation keeps it.+ repo.expect_get_participants()+ .times(1)+ .returning(|_| Box::pin(async { Ok(Vec::new()) }));+ repo.expect_get_active_guests()+ .times(1)+ .returning(|_| Box::pin(async { Ok(Vec::new()) }));+ repo.expect_get_participant_count()+ .times(1)+ .returning(|_| Box::pin(async { Ok(1) }));+ repo.expect_get_call_record_by_call_id()+ .withf(|call_id| *call_id == ORPHAN_CALL_ID)+ .times(1)+ .returning(|_| Box::pin(async { Ok(Some(archived_record(ORPHAN_CALL_ID))) }));+ // An expired meeting preparation has no call record yet.+ repo.expect_get_call_record_by_call_id()+ .withf(|call_id| *call_id == PREPARED_ROOM_ID)+ .times(1)+ .returning(|_| Box::pin(async { Ok(None) }));++ let mut rtc_client = MockCallRtcClient::new();+ rtc_client+ .expect_list_participant_identities()+ .withf(|room_name| room_name == SWEPT_ACTIVE_CALL_ID.to_string())+ .times(1)+ .returning(|_| Box::pin(async { Ok(Some(vec!["agent-transcriber".to_string()])) }));+ rtc_client+ .expect_list_rooms()+ .times(1)+ .return_once(move || {+ let rooms = vec![+ rtc_room(active_room, 30),+ rtc_room(ORPHAN_CALL_ID.to_string(), 10),+ // Too new: the join webhook or the archival teardown may still act.+ rtc_room(YOUNG_ORPHAN_CALL_ID.to_string(), 0),+ rtc_room(PREPARED_ROOM_ID.to_string(), 10),+ rtc_room("not-a-call-room".to_string(), 10),+ ];+ Box::pin(async move { Ok(rooms) })+ });+ rtc_client+ .expect_delete_room()+ .withf(|room_name| room_name == ORPHAN_CALL_ID.to_string())+ .times(1)+ .returning(|_| Box::pin(async { Ok(()) }));++ build_webhook_service(repo, rtc_client, RecordingEventBroker::default())+ .reconcile_stale_calls()+ .await+ .expect("reconciliation succeeds");+}++#[tokio::test]+async fn failed_room_listing_does_not_fail_reconciliation() {+ let mut repo = MockCallRepository::new();+ repo.expect_list_active_calls()+ .times(1)+ .returning(|| Box::pin(async { Ok(Vec::new()) }));+ let mut rtc_client = MockCallRtcClient::new();+ rtc_client+ .expect_list_rooms()+ .times(1)+ .returning(|| Box::pin(async { Err(anyhow::anyhow!("RTC unavailable")) }));+ rtc_client.expect_delete_room().never();++ build_webhook_service(repo, rtc_client, RecordingEventBroker::default())+ .reconcile_stale_calls()+ .await+ .expect("a failed room sweep does not fail call reconciliation");+}++/// No active call in the channel; its latest call is `latest`.+fn leave_repo(latest: CallRecord) -> MockCallRepository {+ let mut repo = MockCallRepository::new();+ repo.expect_get_call_by_channel_id()+ .withf(|channel_id| *channel_id == ORPHAN_CHANNEL_ID)+ .times(1)+ .returning(|_| Box::pin(async { Ok(None) }));+ repo.expect_get_call_records_by_user()+ .withf(|user_id, limit, filter, page| {+ user_id.as_ref() == user(STALE_JOINER).as_ref()+ && *limit == 1+ && matches!(+ filter.as_deref(),+ Some(filter_ast::Expr::Literal(+ item_filters::ast::call::CallLiteral::ChannelId(channel_id)+ )) if *channel_id == ORPHAN_CHANNEL_ID+ )+ && page.by_start+ && page.after.is_none()+ })+ .times(1)+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(vec![latest]) }));+ repo.expect_remove_participant().never();+ repo+}++async fn leave(repo: MockCallRepository, rtc_client: MockCallRtcClient) {+ let result = build_webhook_service(repo, rtc_client, RecordingEventBroker::default())+ .leave_or_end_call(&ORPHAN_CHANNEL_ID, user(STALE_JOINER))+ .await;+ assert!(matches!(result, Err(CallError::NotFound(_))));+}++#[tokio::test]+async fn leave_without_an_active_call_removes_the_user_from_the_archived_room() {+ let mut rtc_client = MockCallRtcClient::new();+ rtc_client+ .expect_list_participant_identities()+ .withf(|room_name| room_name == ORPHAN_CALL_ID.to_string())+ .times(1)+ .returning(|_| Box::pin(async { Ok(Some(vec![user(STALE_JOINER).as_ref().to_string()])) }));+ rtc_client+ .expect_remove_participant()+ .withf(|room_name, identity| {+ room_name == ORPHAN_CALL_ID.to_string()+ && identity.as_ref() == user(STALE_JOINER).as_ref()+ })+ .times(1)+ .returning(|_, _| Box::pin(async { Ok(()) }));++ leave(leave_repo(archived_record(ORPHAN_CALL_ID)), rtc_client).await;+}++#[tokio::test]+async fn leave_without_an_active_call_leaves_rooms_the_user_is_not_in() {+ let mut rtc_client = MockCallRtcClient::new();+ rtc_client+ .expect_list_participant_identities()+ .times(1)+ .returning(|_| Box::pin(async { Ok(None) }));+ rtc_client.expect_remove_participant().never();++ leave(leave_repo(archived_record(ORPHAN_CALL_ID)), rtc_client).await;+}++#[tokio::test]+async fn leave_without_an_active_call_ignores_a_still_active_latest_call() {+ let mut latest = archived_record(ORPHAN_CALL_ID);+ latest.is_active = true;+ let mut rtc_client = MockCallRtcClient::new();+ rtc_client.expect_list_participant_identities().never();+ rtc_client.expect_remove_participant().never();++ leave(leave_repo(latest), rtc_client).await;+}diff --git a/crates/call/src/inbound/stale_call_sweeper.rs b/crates/call/src/inbound/stale_call_sweeper.rsindex 1f9f3b8f9d..caa41dda27 100644--- a/crates/call/src/inbound/stale_call_sweeper.rs+++ b/crates/call/src/inbound/stale_call_sweeper.rs@@ -1,4 +1,5 @@-//! Periodic call reconciliation for missed RTC leave webhooks.+//! Periodic call reconciliation for missed RTC leave webhooks, and cleanup of+//! RTC rooms that outlived their archived call.use std::sync::Arc;use std::time::Duration;diff --git a/crates/call/src/outbound/livekit_rtc_client.rs b/crates/call/src/outbound/livekit_rtc_client.rsindex 5a298f8234..c13fce0a62 100644--- a/crates/call/src/outbound/livekit_rtc_client.rs+++ b/crates/call/src/outbound/livekit_rtc_client.rs@@ -6,6 +6,7 @@#[cfg(test)]mod test;+use chrono::DateTime;use futures::future;use livekit_api::access_token::{AccessToken, TokenVerifier, VideoGrants};use livekit_api::services::agent_dispatch::AgentDispatchClient;@@ -23,7 +24,7 @@ use notification::domain::models::apple::VoipPushPayload;use crate::domain::meetings::GuestId;use crate::domain::models::{- CallError, CallWebhookEvent, EgressS3Config, VerifiedRingToken, VoipPushPayloadRequest,+ CallError, CallWebhookEvent, EgressS3Config, RtcRoom, VerifiedRingToken, VoipPushPayloadRequest,};use crate::domain::ports::CallRtcClient;@@ -153,8 +154,29 @@ impl CallRtcClient for LivekitRtcClient {#[tracing::instrument(err, skip(self))]async fn delete_room(&self, room_name: &str) -> anyhow::Result<()> {- self.room_client.delete_room(room_name).await?;- Ok(())+ ignore_not_found(self.room_client.delete_room(room_name).await)+ }++ #[tracing::instrument(err, skip(self))]+ async fn list_rooms(&self) -> anyhow::Result<Vec<RtcRoom>> {+ let rooms = self.room_client.list_rooms(Vec::new()).await?;+ Ok(rooms+ .into_iter()+ .filter_map(|room| {+ let Some(created_at) = DateTime::from_timestamp(room.creation_time, 0) else {+ tracing::warn!(+ room_name = room.name,+ creation_time = room.creation_time,+ "skipping RTC room with an unrepresentable creation time"+ );+ return None;+ };+ Some(RtcRoom {+ name: room.name,+ created_at,+ })+ })+ .collect())}#[tracing::instrument(err, skip(self))]@@ -204,7 +226,7 @@ impl CallRtcClient for LivekitRtcClient {#[tracing::instrument(err, skip(self))]async fn remove_guest(&self, room_name: &str, guest_id: GuestId) -> anyhow::Result<()> {- interpret_remove_participant_result(+ ignore_not_found(self.room_client.remove_participant(room_name, &guest_id.to_string()).await,@@ -274,7 +296,7 @@ impl CallRtcClient for LivekitRtcClient {room_name: &str,participant_identity: MacroUserIdStr<'_>,) -> anyhow::Result<()> {- interpret_remove_participant_result(+ ignore_not_found(self.room_client.remove_participant(room_name, participant_identity.as_ref()).await,@@ -425,7 +447,8 @@ impl CallRtcClient for LivekitRtcClient {}}-fn interpret_remove_participant_result(result: Result<(), ServiceError>) -> anyhow::Result<()> {+/// Treat a room or participant that is already gone as removed.+fn ignore_not_found(result: Result<(), ServiceError>) -> anyhow::Result<()> {match result {Ok(()) => Ok(()),Err(error) if is_not_found(&error) => Ok(()),diff --git a/crates/call/src/outbound/livekit_rtc_client/test.rs b/crates/call/src/outbound/livekit_rtc_client/test.rsindex 6ee688091d..b56add9b7d 100644--- a/crates/call/src/outbound/livekit_rtc_client/test.rs+++ b/crates/call/src/outbound/livekit_rtc_client/test.rs@@ -115,21 +115,20 @@ fn verify_access_token_rejects_garbage() {#[test]fn remove_participant_not_found_is_already_gone() {let error = twirp(TwirpErrorCode::NOT_FOUND, "participant does not exist");- interpret_remove_participant_result(Err(error))+ ignore_not_found(Err(error)).expect("leave must succeed when LiveKit already dropped the participant");}#[test]fn remove_participant_room_not_found_is_already_gone() {let error = twirp(TwirpErrorCode::NOT_FOUND, "requested room does not exist");- interpret_remove_participant_result(Err(error))- .expect("leave must succeed when the LiveKit room is already gone");+ ignore_not_found(Err(error)).expect("leave must succeed when the LiveKit room is already gone");}#[test]fn remove_participant_unavailable_still_fails() {let error = twirp(TwirpErrorCode::UNAVAILABLE, "overloaded");- let message = interpret_remove_participant_result(Err(error))+ let message = ignore_not_found(Err(error)).expect_err("transient LiveKit failures must still surface").to_string();assert_eq!(message, "twirp error: twirp error: unavailable: overloaded");diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.mdindex 89a61599c8..dc92c3e514 100644--- a/docs/agent-guide/calls.md+++ b/docs/agent-guide/calls.md@@ -71,6 +71,30 @@ does not pin someone, tapping pins the displayed person, and a participant wholeaves during a held touch cannot be selected. Exercise speaker changes anddepartures during row gestures on a physical iPhone as well as the simulator.+Leaving a native iOS call is final. The drawer's **Leave** and CallKit's end+button both end the CallKit call, its LiveKit room, the drawer and PiP, even+when the native session has already lost track of the call. PiP and the drawer appear only while a call is active, so+restoring a PiP left over from an ended call dismisses it instead of opening+an empty drawer. A call the user left is never rejoined automatically: a+native snapshot that still reports it is ended natively, and only tapping+Join in that channel lets the call back in. A CallKit answer handled more+than 60 seconds after it was fulfilled is dropped rather than joined. Verify+on a physical iPhone that Leave from the drawer, from the lock screen, and+right before backgrounding the app each end the call without a PiP or drawer+returning, and that tapping Join afterwards still rejoins a call that is+still running.++Native call logs go to the unified log (subsystem: the app's bundle id,+category `CallKit`) at notice level, so they survive on the device. Collect+them from a connected iPhone with+`sudo log collect --device-udid <udid> --start '<time>' --output calls.logarchive`+and read them with `log show --predicate 'category == "CallKit"' calls.logarchive`.+They never contain identities, names, or device names; participants appear+as LiveKit SIDs. The app's `call_action` analytics record `callId` on `joined`+and `left`, what started each join (`trigger`: `user`, `deep_link`, `restore`,+`auto_rejoin`), and why each leave ran (`leaveReason`: `user_initiated`,+`native_ended`, `join_cancelled`, `stale_native_session`).+If a recording fails to play, reload the page to obtain a fresh recording link,or use **Open or download recording**. The playback warning does not assumethat the failure is caused by an unsupported media format.