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
feat(ios): native swift livekit (#3750)
Peter Chinman7fb3861ff155
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex 51fe1ddc29..65ce3e0048 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -7,6 +7,7 @@ import { ROUTER_BASE } from '@app/constants/routerBase';import { PosthogProvider, usePosthog } from '@app/lib/analytics/posthog';import { setHotkeyRoot } from '@app/signal/hotkeyRoot';import { globalSplitManager } from '@app/signal/splitLayout';+import { CallKitSync } from '@channel/Call';import { CallProvider } from '@channel/Call/CallContext';import { CallStartedNotifier } from '@channel/Call/CallStartedNotifier';import { ChatAttachmentsInit } from '@core/component/AI/signal/globalAttachments';@@ -515,6 +516,7 @@ export function Root() {<MutationUndoProvider><ChannelsContextProvider><CallProvider>+ <CallKitSync /><CallStartedNotifier /><QuickAccessProvider><SearchProvider>diff --git a/js/app/packages/app/signal/splitLayout.ts b/js/app/packages/app/signal/splitLayout.tsindex 42d95610e4..a79d867ea7 100644--- a/js/app/packages/app/signal/splitLayout.ts+++ b/js/app/packages/app/signal/splitLayout.ts@@ -1,3 +1,4 @@+import { until } from '@solid-primitives/promise';import { createEffect, createRoot, createSignal } from 'solid-js';import type { SplitManager } from '../component/split-layout/layoutManager';@@ -7,6 +8,39 @@ import type { SplitManager } from '../component/split-layout/layoutManager';export const [globalSplitManager, setGlobalSplitManager] =createSignal<SplitManager>();+/**+ * Resolves once the global split manager is initialized. Safe to call from+ * outside a reactive context (e.g. async event handlers).+ */+export function whenSplitManagerReady(+ signal?: AbortSignal+): Promise<SplitManager> {+ const wait = until(globalSplitManager);+ if (!signal) return wait;+ const abortSignal = signal;++ return new Promise((resolve, reject) => {+ function onAbort() {+ wait.dispose();+ reject(+ abortSignal.reason ??+ new DOMException('Split manager readiness wait aborted', 'AbortError')+ );+ }++ wait+ .then(resolve, reject)+ .finally(() => abortSignal.removeEventListener('abort', onAbort));++ if (abortSignal.aborted) {+ onAbort();+ return;+ }++ abortSignal.addEventListener('abort', onAbort, { once: true });+ });+}+if (import.meta.env.DEV) {createRoot(() => {createEffect(() => {diff --git a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsxindex c2d242079d..4b5b84334f 100644--- a/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx+++ b/js/app/packages/block-channel/component/NewChannelBlockAdapter.tsx@@ -9,6 +9,8 @@ import {ChannelCallAutoJoin,ChannelCallButton,ChannelCallTab,+ getCallJoinTab,+ isNativeIosCallKitEnabled,useCall,useCallContextOptional,} from '@channel/Call';@@ -77,6 +79,27 @@ function CallTabLabel() {);}+const canUseInlineCallTab = () => {+ return !isNativeIosCallKitEnabled();+};++// Native iOS CallKit owns the call surface, so the embedded Call tab should+// never become the active channel tab on that platform.+const normalizeChannelTab = (tab: ChannelTabId) => {+ return tab === 'call' && canUseInlineCallTab() ? tab : DEFAULT_CHANNEL_TAB;+};++const initialChannelTab = (options: {+ wantsJoinCall: boolean;+ hasActiveCallHere: boolean;+}) => {+ return normalizeChannelTab(+ options.wantsJoinCall || options.hasActiveCallHere+ ? 'call'+ : DEFAULT_CHANNEL_TAB+ );+};+function NewTop(props: { channelId: string }) {const { activeTab, setActiveTab } = useChannelTab();const channelName = useChannelName(props.channelId);@@ -91,6 +114,7 @@ function NewTop(props: { channelId: string }) {// `activeTab` to `call` before the join request resolves).const showCallTab = () =>ENABLE_CALLS() &&+ canUseInlineCallTab() &&(call.isInThisChannel() ||call.isJoining() ||activeTab() === 'call' ||@@ -147,11 +171,12 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {isJoinCallRequested(searchParams[CHANNEL_URL_PARAMS.joinCall]));const callCtx = useCallContextOptional();- const hasActiveCallHere =- callCtx?.isInCall() && callCtx.activeChannelId() === channelId;+ const hasActiveCallHere = !!(+ callCtx?.isInCall() && callCtx.activeChannelId() === channelId+ );const [activeTab, setActiveTabInternal] = createSignal<ChannelTabId>(- wantsJoinCall || hasActiveCallHere ? 'call' : DEFAULT_CHANNEL_TAB+ initialChannelTab({ wantsJoinCall, hasActiveCallHere }));const [pendingJoinCall, setPendingJoinCall] = createSignal(wantsJoinCall);@@ -159,6 +184,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {const messagesChannelHandle: { current?: ChannelHandle } = {};const setActiveTab = (tab: ChannelTabId) => {+ tab = normalizeChannelTab(tab);if (tab !== 'messages') {messagesChannelHandle.current = undefined;}@@ -217,7 +243,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {createMethodRegistration(blockHandle, {goToLocationFromParams: async (params: ChannelTargetMessageParams) => {if (isOpenCallTabRequested(params[CHANNEL_URL_PARAMS.openCallTab])) {- setActiveTab('call');+ setActiveTab(getCallJoinTab());return;}@@ -233,7 +259,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {}if (isJoinCallRequested(params[CHANNEL_URL_PARAMS.joinCall])) {- setActiveTab('call');+ setActiveTab(getCallJoinTab());setPendingJoinCall(true);}},@@ -290,7 +316,7 @@ export function NewChannelBlockAdapter(props: BlockChannelProps) {<Match when={activeTab() === 'participants'}><ChannelParticipantsTab channelId={channelId} /></Match>- <Match when={activeTab() === 'call'}>+ <Match when={activeTab() === 'call' && canUseInlineCallTab()}><ChannelCallTabchannelId={channelId}pendingJoin={pendingJoinCall}diff --git a/js/app/packages/channel/Call/CallContext.tsx b/js/app/packages/channel/Call/CallContext.tsxindex 7db7630479..daa62839df 100644--- a/js/app/packages/channel/Call/CallContext.tsx+++ b/js/app/packages/channel/Call/CallContext.tsx@@ -9,10 +9,8 @@ import {type AudioCaptureOptions,ConnectionState,type LocalTrack,- type LocalTrackPublication,type RemoteParticipant,Room,- RoomEvent,Track,} from 'livekit-client';import {@@ -24,6 +22,16 @@ import {} from 'solid-js';import { createStore } from 'solid-js/store';import { CallAudioSink } from './CallAudioSink';+import {+ type CallSessionConnectMetadata,+ type CallSessionDisconnectOptions,+ createCallSessionController,+} from './CallSessionController';+import { createLivekitJsCallController } from './LivekitJsCallController';+import {+ type NativeCallConnectionState,+ useMaybeNativeCallState,+} from './native-call-state';export type CallParticipantInfo = {identity: string;@@ -187,6 +195,15 @@ async function applyNativeAudioProcessingToMicTrack(}}+// Swift exposes a transient `disconnecting` state that livekit-client lacks.+const NATIVE_TO_LIVEKIT_STATE = {+ disconnected: ConnectionState.Disconnected,+ connecting: ConnectionState.Connecting,+ connected: ConnectionState.Connected,+ reconnecting: ConnectionState.Reconnecting,+ disconnecting: ConnectionState.Disconnected,+} satisfies Record<NativeCallConnectionState, ConnectionState>;+type CallStoreState = {connectionState: ConnectionState;activeChannelId: string | null;@@ -318,10 +335,15 @@ export type CallState = {activeAudioOutputDeviceId: () => string | null;/** Currently active video input device ID */activeVideoInputDeviceId: () => string | null;- /** Connect to a call using a token response */- connect: (tokenResponse: CallTokenResponse) => Promise<void>;- /** Disconnect from the current call */- disconnect: () => Promise<void>;+ /** Whether joining this channel needs a fresh call token */+ shouldRequestSessionToken: (channelId: string) => boolean;+ /** Connect the active call session using the right platform controller */+ connectSession: (+ tokenResponse: CallTokenResponse,+ metadata?: CallSessionConnectMetadata+ ) => Promise<void>;+ /** Disconnect the active call session using the right platform controller */+ disconnectSession: (options?: CallSessionDisconnectOptions) => Promise<void>;/** Toggle local audio */toggleAudio: () => Promise<void>;/** Toggle local video */@@ -392,6 +414,7 @@ export function useCallContextOptional(): CallState | undefined {* and all readonly call state. Returns reactive state + mutation actions.*/function createCallState() {+ const nativeCall = useMaybeNativeCallState();const [room, setRoom] = createSignal<Room | null>(null);const [store, setStore] = createStore<CallStoreState>({...initialState,@@ -419,6 +442,8 @@ function createCallState() {return room() === targetRoom && mediaSetupVersion === setupVersion;}+ const currentNativeCallSnapshot = () => nativeCall?.snapshot() ?? null;+function currentMicrophoneCaptureOptions(deviceId?: string | null): AudioCaptureOptions {@@ -666,11 +691,6 @@ function createCallState() {setStore('trackVersion', (v) => v + 1);}- function syncParticipantMap(r: Room) {- setStore('remoteParticipants', new Map(r.remoteParticipants));- bumpTrackVersion();- }-function resetState() {// Preserve joinError across room teardown — LiveKit can emit Disconnected// when the network drops or reconnects; wiping joinError would hide the@@ -683,49 +703,7 @@ function createCallState() {});}- function attachRoomListeners(r: Room) {- r.on(RoomEvent.ConnectionStateChanged, (state: ConnectionState) => {- console.debug('[call] connection state changed', {- state,- room: store.activeChannelId,- call: store.activeCallId,- });- setStore('connectionState', state);- });-- r.on(RoomEvent.ParticipantConnected, () => syncParticipantMap(r));- r.on(RoomEvent.ParticipantDisconnected, () => syncParticipantMap(r));-- r.on(RoomEvent.TrackSubscribed, bumpTrackVersion);- r.on(RoomEvent.TrackUnsubscribed, bumpTrackVersion);- r.on(RoomEvent.TrackPublished, bumpTrackVersion);- r.on(RoomEvent.TrackUnpublished, bumpTrackVersion);- r.on(RoomEvent.TrackMuted, bumpTrackVersion);- r.on(RoomEvent.TrackUnmuted, bumpTrackVersion);- r.on(RoomEvent.LocalTrackPublished, bumpTrackVersion);-- r.on(RoomEvent.ActiveSpeakersChanged, () => {- setStore('speakerVersion', (v) => v + 1);- });-- r.on(RoomEvent.LocalTrackUnpublished, (pub: LocalTrackPublication) => {- if (pub.source === Track.Source.ScreenShare) {- setStore('isScreenSharing', false);- }- bumpTrackVersion();- });- r.on(RoomEvent.Disconnected, (reason?: unknown) => {- console.warn('[call] room disconnected', {- reason,- room: store.activeChannelId,- call: store.activeCallId,- });- resetState();- });- }-- function destroyRoom() {- cancelPendingMediaSetup();+ function destroyRoomProcessors() {const krisp = krispFilter();if (krisp) {krisp.destroy().catch((e) => {@@ -741,12 +719,6 @@ function createCallState() {});setBlurProcessor(null);}- const r = room();- if (r) {- r.removeAllListeners();- setRoom(null);- }- resetState();}// --- device enumeration ---@@ -870,6 +842,13 @@ function createCallState() {}async function switchVideoInput(deviceId: string) {+ if (currentNativeCallSnapshot()) {+ console.info(+ '[callkit] ignoring JS video input switch; native drawer controls camera'+ );+ return;+ }+const r = room();if (!r) return;try {@@ -896,79 +875,43 @@ function createCallState() {};navigator.mediaDevices?.addEventListener('devicechange', handleDeviceChange);- // --- mutations ---+ const currentConnectionState = () => {+ const native = currentNativeCallSnapshot();+ return native+ ? NATIVE_TO_LIVEKIT_STATE[native.connectionState]+ : store.connectionState;+ };- async function connect(tokenResponse: CallTokenResponse) {- const existingRoom = room();+ const currentActiveChannelId = () =>+ currentNativeCallSnapshot()?.channelId ??+ store.activeChannelId ??+ store.optimisticJoinChannelId;- if (- existingRoom &&- store.activeChannelId === tokenResponse.channelId &&- isActiveCallConnectionState(store.connectionState)- ) {- // A duplicate join can arrive while LiveKit is already connected or- // recovering its signaling connection. Do not call room.connect() again;- // that replaces the SDK's reconnection attempt and can wedge the peer- // connection until the user manually leaves/rejoins.- console.debug('[call] ignoring duplicate connect for active room', {- channelId: tokenResponse.channelId,- state: store.connectionState,- });- setStore('activeCallId', tokenResponse.callId);- setStore('optimisticJoinChannelId', null);- setStore('joinError', null);- return;- }+ const currentActiveCallId = () =>+ currentNativeCallSnapshot()?.callId ?? store.activeCallId;- // If switching channels, or if a previous disconnected room instance is- // still hanging around after a failed reconnect, tear it down and build a- // fresh Room. This gives retry/auto-rejoin the same clean slate as a manual- // leave + join.- if (existingRoom) {- await existingRoom.disconnect();- destroyRoom();- }+ const currentIsAudioMuted = () =>+ currentNativeCallSnapshot()?.isAudioMuted ?? store.isAudioMuted;- const targetRoom = new Room({- audioCaptureDefaults: currentMicrophoneCaptureOptions(),- });- attachRoomListeners(targetRoom);- setRoom(targetRoom);+ const currentIsVideoMuted = () =>+ currentNativeCallSnapshot()?.isVideoMuted ?? store.isVideoMuted;- setStore('activeChannelId', tokenResponse.channelId);- setStore('activeCallId', tokenResponse.callId);- setStore('isSharedWithTeam', true);+ const currentIsInCall = () =>+ isActiveCallConnectionState(currentConnectionState()) ||+ (currentNativeCallSnapshot() === null &&+ store.optimisticJoinChannelId !== null);- try {- await targetRoom.connect(tokenResponse.serverUrl, tokenResponse.token);- // Real connection established — optimistic flag no longer needed- setStore('optimisticJoinChannelId', null);- setStore('joinError', null);- } catch (e) {- console.error('failed to connect to LiveKit room', e);- destroyRoom();- throw e;- }+ const currentIsConnecting = () =>+ (currentNativeCallSnapshot() === null &&+ store.optimisticJoinChannelId !== null) ||+ currentConnectionState() === ConnectionState.Connecting ||+ currentConnectionState() === ConnectionState.Reconnecting ||+ currentConnectionState() === ConnectionState.SignalReconnecting;- // Sync participants that were already in the room when we connected.- setStore('remoteParticipants', new Map(targetRoom.remoteParticipants));- bumpTrackVersion();-- // Default to microphone on, video off as soon as the room is connected.- setStore('isAudioMuted', false);- setStore('isVideoMuted', true);-- // Treat the LiveKit connection itself as the join success boundary. Local- // media/device setup can be interrupted by OS-level flows (e.g. macOS- // screenshot) or slow permission/device APIs; if we await it here, the- // join mutation timeout can fire after the user is already in the room and- // run failed-join cleanup, which calls DELETE /call/:channel and kicks the- // user out. Run the non-critical setup in the background instead.- const setupVersion = nextMediaSetupVersion();- void finishLocalMediaSetup(targetRoom, setupVersion).catch((e) => {- console.error('failed to finish local call media setup', e);- });- }+ const currentJoinError = () =>+ currentNativeCallSnapshot() ? null : store.joinError;++ // --- mutations ---async function finishLocalMediaSetup(targetRoom: Room, setupVersion: number) {if (!isCurrentMediaSetup(targetRoom, setupVersion)) return;@@ -1004,17 +947,53 @@ function createCallState() {trackActiveDevices(targetRoom);}- async function disconnect() {- const r = room();- if (r) {- cancelPendingMediaSetup();- try {- await r.disconnect();- } finally {- destroyRoom();- }- }- }+ const livekitJs = createLivekitJsCallController({+ room,+ setRoom,+ state: () => ({+ activeChannelId: store.activeChannelId,+ activeCallId: store.activeCallId,+ connectionState: store.connectionState,+ }),+ currentMicrophoneCaptureOptions,+ isActiveConnectionState: isActiveCallConnectionState,+ cancelPendingMediaSetup,+ nextMediaSetupVersion,+ finishLocalMediaSetup,+ destroyProcessors: destroyRoomProcessors,+ resetState,+ setConnectionState: (state) => setStore('connectionState', state),+ setActiveCall: (channelId, callId) => {+ setStore('activeChannelId', channelId);+ setStore('activeCallId', callId);+ },+ setDuplicateConnectCallId: (callId) => {+ setStore('activeCallId', callId);+ setStore('optimisticJoinChannelId', null);+ setStore('joinError', null);+ },+ setInitialMediaState: () => {+ setStore('isAudioMuted', false);+ setStore('isVideoMuted', true);+ },+ setRemoteParticipants: (participants) => {+ setStore('remoteParticipants', participants);+ },+ setSharedWithTeam: (value) => setStore('isSharedWithTeam', value),+ clearOptimisticJoin: () => {+ setStore('optimisticJoinChannelId', null);+ setStore('joinError', null);+ },+ bumpTrackVersion,+ bumpSpeakerVersion: () => setStore('speakerVersion', (v) => v + 1),+ setScreenSharing: (value) => setStore('isScreenSharing', value),+ });++ const callSession = createCallSessionController({+ nativeCall,+ jsConnect: livekitJs.connect,+ jsDisconnect: livekitJs.disconnect,+ });async function toggleAudio() {const r = room();@@ -1040,6 +1019,13 @@ function createCallState() {}async function toggleVideo() {+ if (currentNativeCallSnapshot()) {+ console.info(+ '[callkit] ignoring JS video toggle; native drawer controls camera'+ );+ return;+ }+const r = room();if (!r) return;const newMuted = !store.isVideoMuted;@@ -1165,11 +1151,7 @@ function createCallState() {// --- cleanup ---const handleBeforeUnload = () => {- const r = room();- if (r) {- cancelPendingMediaSetup();- r.disconnect();- }+ livekitJs.disconnectBeforeUnload();};window.addEventListener('beforeunload', handleBeforeUnload);@@ -1179,12 +1161,7 @@ function createCallState() {'devicechange',handleDeviceChange);- cancelPendingMediaSetup();- const r = room();- if (r) {- r.disconnect();- r.removeAllListeners();- }+ livekitJs.dispose();});// --- public API ---@@ -1192,13 +1169,10 @@ function createCallState() {const state: CallState = {// readonly stateroom,- connectionState: () => store.connectionState,- isInCall: () =>- isActiveCallConnectionState(store.connectionState) ||- store.optimisticJoinChannelId !== null,- activeChannelId: () =>- store.activeChannelId ?? store.optimisticJoinChannelId,- activeCallId: () => store.activeCallId,+ connectionState: currentConnectionState,+ isInCall: currentIsInCall,+ activeChannelId: currentActiveChannelId,+ activeCallId: currentActiveCallId,remoteParticipants: () => store.remoteParticipants,trackVersion: () => store.trackVersion,isLocalSpeaking: () => {@@ -1211,8 +1185,8 @@ function createCallState() {store.speakerVersion;return participant.isSpeaking;},- isAudioMuted: () => store.isAudioMuted,- isVideoMuted: () => store.isVideoMuted,+ isAudioMuted: currentIsAudioMuted,+ isVideoMuted: currentIsVideoMuted,isScreenSharing: () => store.isScreenSharing,audioInputDevices: () => store.audioInputDevices,audioOutputDevices: () => store.audioOutputDevices,@@ -1220,15 +1194,12 @@ function createCallState() {activeAudioInputDeviceId: () => store.activeAudioInputDeviceId,activeAudioOutputDeviceId: () => store.activeAudioOutputDeviceId,activeVideoInputDeviceId: () => store.activeVideoInputDeviceId,- isConnecting: () =>- store.optimisticJoinChannelId !== null ||- store.connectionState === ConnectionState.Connecting ||- store.connectionState === ConnectionState.Reconnecting ||- store.connectionState === ConnectionState.SignalReconnecting,+ isConnecting: currentIsConnecting,// mutations- connect,- disconnect,+ shouldRequestSessionToken: callSession.shouldRequestToken,+ connectSession: callSession.connectWithToken,+ disconnectSession: callSession.disconnect,toggleAudio,toggleVideo,toggleScreenShare,@@ -1241,16 +1212,15 @@ function createCallState() {toggleNoiseSuppression,beginOptimisticJoin,rollbackOptimisticJoin,- joinError: () => store.joinError,+ joinError: currentJoinError,setJoinError,callPageChannelId: () => store.callPageChannelId,syncCallPageTab,isCallPage: () => {store.callPageChannelId;- store.activeChannelId;- store.optimisticJoinChannelId;+ currentActiveChannelId();const page = store.callPageChannelId;- const active = store.activeChannelId ?? store.optimisticJoinChannelId;+ const active = currentActiveChannelId();return page !== null && active !== null && page === active;},backgroundEffect: () => store.backgroundEffect,diff --git a/js/app/packages/channel/Call/CallControls/CallControls.tsx b/js/app/packages/channel/Call/CallControls/CallControls.tsxindex 29b91e124e..ef638c1998 100644--- a/js/app/packages/channel/Call/CallControls/CallControls.tsx+++ b/js/app/packages/channel/Call/CallControls/CallControls.tsx@@ -1,4 +1,5 @@import { type Accessor, Show } from 'solid-js';+import { useMaybeNativeCallState } from '../native-call-state';import { CallControlsDefaultAndPanelRow } from './CallControlsDefaultAndPanelRow';import { CallControlsPanelSmallRow } from './CallControlsPanelSmallRow';@@ -23,8 +24,10 @@ function readWhen(when: boolean | Accessor<boolean> | undefined): boolean {* the inline pill row.*/export function CallControls(props: CallControlsProps) {+ const nativeCall = useMaybeNativeCallState();+return (- <Show when={() => readWhen(props.when)}>+ <Show when={() => readWhen(props.when) && !nativeCall?.snapshot()}><Showwhen={props.variant === 'panel-small'}fallback={<CallControlsDefaultAndPanelRow onLeave={props.onLeave} />}diff --git a/js/app/packages/channel/Call/CallSessionController.ts b/js/app/packages/channel/Call/CallSessionController.tsnew file mode 100644index 0000000000..4cc5aa95fe--- /dev/null+++ b/js/app/packages/channel/Call/CallSessionController.ts@@ -0,0 +1,115 @@+import type { CallTokenResponse } from '@service-call/client';+import type { NativeCallState } from './native-call-state';+import {+ endCallKitCall,+ isNativeIosCallKitEnabled,+ startNativeCallKitOutgoingCall,+} from './use-callkit';++type CallSessionControllerOptions = {+ nativeCall: NativeCallState | undefined;+ jsConnect: (tokenResponse: CallTokenResponse) => Promise<void>;+ jsDisconnect: () => Promise<void>;+};++export type CallSessionConnectMetadata = {+ channelTitle?: string | null;+};++export type CallSessionDisconnectOptions = {+ endNativeCall?: boolean;+};++export type CallSessionController = {+ shouldRequestToken: (channelId: string) => boolean;+ connectWithToken: (+ tokenResponse: CallTokenResponse,+ metadata?: CallSessionConnectMetadata+ ) => Promise<void>;+ disconnect: (options?: CallSessionDisconnectOptions) => Promise<void>;+};++export function createCallSessionController(+ options: CallSessionControllerOptions+): CallSessionController {+ if (isNativeIosCallKitEnabled()) {+ if (!options.nativeCall) {+ throw new Error(+ 'Native call state is required for iOS CallKit call sessions'+ );+ }+ return createNativeCallKitSessionController({+ nativeCall: options.nativeCall,+ jsDisconnect: options.jsDisconnect,+ });+ }++ return createJsLivekitSessionController({+ jsConnect: options.jsConnect,+ jsDisconnect: options.jsDisconnect,+ });+}++function createJsLivekitSessionController(options: {+ jsConnect: (tokenResponse: CallTokenResponse) => Promise<void>;+ jsDisconnect: () => Promise<void>;+}): CallSessionController {+ return {+ shouldRequestToken: () => true,+ connectWithToken: (tokenResponse) => options.jsConnect(tokenResponse),+ disconnect: () => options.jsDisconnect(),+ };+}++function createNativeCallKitSessionController(options: {+ nativeCall: NativeCallState;+ jsDisconnect: () => Promise<void>;+}): CallSessionController {+ return {+ shouldRequestToken: (channelId) => {+ const native = options.nativeCall.snapshot();+ const shouldSkip =+ native !== null &&+ native.channelId === channelId &&+ native.connectionState !== 'disconnected' &&+ native.connectionState !== 'disconnecting';++ if (shouldSkip) {+ console.info(+ '[callkit] native call snapshot matched; skipping JS connect',+ {+ channelId,+ callId: native.callId,+ connectionState: native.connectionState,+ }+ );+ }++ return !shouldSkip;+ },+ connectWithToken: (tokenResponse, metadata) => {+ const channelTitle = metadata?.channelTitle ?? null;+ return startNativeCallKitOutgoingCall(+ {+ channelId: tokenResponse.channelId,+ callId: tokenResponse.callId,+ channelTitle,+ callerName: channelTitle,+ serverUrl: tokenResponse.serverUrl,+ token: tokenResponse.token,+ },+ options.nativeCall+ );+ },+ disconnect: async (disconnectOptions) => {+ if (disconnectOptions?.endNativeCall !== false) {+ try {+ await endCallKitCall();+ } catch (e) {+ console.error('callkit: failed to dismiss call sheet', e);+ }+ }+ await options.jsDisconnect();+ },+ };+}diff --git a/js/app/packages/channel/Call/ChannelCallAutoJoin.tsx b/js/app/packages/channel/Call/ChannelCallAutoJoin.tsxindex 917ca84b2a..5dada3631f 100644--- a/js/app/packages/channel/Call/ChannelCallAutoJoin.tsx+++ b/js/app/packages/channel/Call/ChannelCallAutoJoin.tsx@@ -1,7 +1,7 @@import { useChannelTab } from '@channel/Channel/ChannelTabContext';-import { DEFAULT_CHANNEL_TAB } from '@channel/Channel/channel-tabs';import { ENABLE_CALLS } from '@core/constant/featureFlags';import { type Accessor, createEffect, untrack } from 'solid-js';+import { getCallJoinTab, getCallLeaveTab } from './call-tabs';import { useCall } from './use-call';/**@@ -22,8 +22,8 @@ export function ChannelCallAutoJoin(props: {// CallOverlay (or a disconnect) returns the user to the default tab// even when the join was triggered here instead of via the button.const call = useCall(() => props.channelId, {- onJoin: () => setActiveTab('call'),- onLeave: () => setActiveTab(DEFAULT_CHANNEL_TAB),+ onJoin: () => setActiveTab(getCallJoinTab()),+ onLeave: () => setActiveTab(getCallLeaveTab()),});createEffect(() => {@@ -43,7 +43,7 @@ export function ChannelCallAutoJoin(props: {}if (call.isInThisChannel()) {- setActiveTab('call');+ setActiveTab(getCallJoinTab());props.onHandled();return;}diff --git a/js/app/packages/channel/Call/ChannelCallButton.tsx b/js/app/packages/channel/Call/ChannelCallButton.tsxindex 375afa8293..4437683d57 100644--- a/js/app/packages/channel/Call/ChannelCallButton.tsx+++ b/js/app/packages/channel/Call/ChannelCallButton.tsx@@ -1,16 +1,16 @@import { useChannelTab } from '@channel/Channel/ChannelTabContext';-import { DEFAULT_CHANNEL_TAB } from '@channel/Channel/channel-tabs';import PhoneIcon from '@icon/wide-call.svg';import { useActiveCallQuery } from '@queries/call/call';import { Button, cn } from '@ui';import { Show } from 'solid-js';+import { getCallJoinTab, getCallLeaveTab } from './call-tabs';import { useCall } from './use-call';export function ChannelCallButton(props: { channelId: string }) {const { setActiveTab } = useChannelTab();const call = useCall(() => props.channelId, {- onJoin: () => setActiveTab('call'),- onLeave: () => setActiveTab(DEFAULT_CHANNEL_TAB),+ onJoin: () => setActiveTab(getCallJoinTab()),+ onLeave: () => setActiveTab(getCallLeaveTab()),});const activeCallQuery = useActiveCallQuery(() => props.channelId);diff --git a/js/app/packages/channel/Call/ChannelCallTab.tsx b/js/app/packages/channel/Call/ChannelCallTab.tsxindex b07f1ae9a9..ed7bad1cdc 100644--- a/js/app/packages/channel/Call/ChannelCallTab.tsx+++ b/js/app/packages/channel/Call/ChannelCallTab.tsx@@ -1,5 +1,4 @@import { useChannelTab } from '@channel/Channel/ChannelTabContext';-import { DEFAULT_CHANNEL_TAB } from '@channel/Channel/channel-tabs';import { UserGroup } from '@core/component/UserGroup';import { tryMacroId, useDisplayNameParts } from '@core/user';import PhoneIcon from '@icon/wide-call.svg';@@ -7,6 +6,7 @@ import { useActiveCallQuery, useCallRecordQuery } from '@queries/call/call';import { Button } from '@ui';import { type Accessor, createMemo, Match, Show, Switch } from 'solid-js';import { CallOverlay } from './CallOverlay';+import { getCallJoinTab, getCallLeaveTab } from './call-tabs';import { useCall } from './use-call';function ParticipantFirstName(props: { id: string }) {@@ -104,8 +104,8 @@ export function ChannelCallTab(props: {// overlay (or disconnect) switches back to Messages — not only when// the join was initiated from the header button.const call = useCall(() => props.channelId, {- onJoin: () => setActiveTab('call'),- onLeave: () => setActiveTab(DEFAULT_CHANNEL_TAB),+ onJoin: () => setActiveTab(getCallJoinTab()),+ onLeave: () => setActiveTab(getCallLeaveTab()),});const handleRetry = async () => {diff --git a/js/app/packages/channel/Call/LivekitJsCallController.ts b/js/app/packages/channel/Call/LivekitJsCallController.tsnew file mode 100644index 0000000000..d5e0d8efad--- /dev/null+++ b/js/app/packages/channel/Call/LivekitJsCallController.ts@@ -0,0 +1,204 @@+import type { CallTokenResponse } from '@service-call/client';+import {+ type AudioCaptureOptions,+ type ConnectionState,+ type LocalTrackPublication,+ type RemoteParticipant,+ Room,+ RoomEvent,+ Track,+} from 'livekit-client';++type LivekitJsCallControllerState = {+ activeChannelId: string | null;+ activeCallId: string | null;+ connectionState: ConnectionState;+};++type LivekitJsCallControllerOptions = {+ room: () => Room | null;+ setRoom: (room: Room | null) => void;+ state: () => LivekitJsCallControllerState;+ currentMicrophoneCaptureOptions: () => AudioCaptureOptions;+ isActiveConnectionState: (state: ConnectionState) => boolean;+ cancelPendingMediaSetup: () => void;+ nextMediaSetupVersion: () => number;+ finishLocalMediaSetup: (room: Room, setupVersion: number) => Promise<void>;+ destroyProcessors: () => void;+ resetState: () => void;+ setConnectionState: (state: ConnectionState) => void;+ setActiveCall: (channelId: string, callId: string) => void;+ setDuplicateConnectCallId: (callId: string) => void;+ setInitialMediaState: () => void;+ setRemoteParticipants: (participants: Map<string, RemoteParticipant>) => void;+ setSharedWithTeam: (value: boolean) => void;+ clearOptimisticJoin: () => void;+ bumpTrackVersion: () => void;+ bumpSpeakerVersion: () => void;+ setScreenSharing: (value: boolean) => void;+};++export function createLivekitJsCallController(+ options: LivekitJsCallControllerOptions+) {+ function syncParticipantMap(room: Room) {+ options.setRemoteParticipants(new Map(room.remoteParticipants));+ options.bumpTrackVersion();+ }++ function attachRoomListeners(room: Room) {+ room.on(RoomEvent.ConnectionStateChanged, (state: ConnectionState) => {+ const snapshot = options.state();+ console.debug('[call] connection state changed', {+ state,+ room: snapshot.activeChannelId,+ call: snapshot.activeCallId,+ });+ options.setConnectionState(state);+ });++ room.on(RoomEvent.ParticipantConnected, () => syncParticipantMap(room));+ room.on(RoomEvent.ParticipantDisconnected, () => syncParticipantMap(room));++ room.on(RoomEvent.TrackSubscribed, options.bumpTrackVersion);+ room.on(RoomEvent.TrackUnsubscribed, options.bumpTrackVersion);+ room.on(RoomEvent.TrackPublished, options.bumpTrackVersion);+ room.on(RoomEvent.TrackUnpublished, options.bumpTrackVersion);+ room.on(RoomEvent.TrackMuted, options.bumpTrackVersion);+ room.on(RoomEvent.TrackUnmuted, options.bumpTrackVersion);+ room.on(RoomEvent.LocalTrackPublished, options.bumpTrackVersion);++ room.on(RoomEvent.ActiveSpeakersChanged, options.bumpSpeakerVersion);++ room.on(RoomEvent.LocalTrackUnpublished, (pub: LocalTrackPublication) => {+ if (pub.source === Track.Source.ScreenShare) {+ options.setScreenSharing(false);+ }+ options.bumpTrackVersion();+ });++ room.on(RoomEvent.Disconnected, (reason?: unknown) => {+ const snapshot = options.state();+ console.warn('[call] room disconnected', {+ reason,+ room: snapshot.activeChannelId,+ call: snapshot.activeCallId,+ });+ options.resetState();+ });+ }++ function destroyRoom() {+ options.cancelPendingMediaSetup();+ options.destroyProcessors();++ const room = options.room();+ if (room) {+ room.removeAllListeners();+ options.setRoom(null);+ }++ options.resetState();+ }++ async function connect(tokenResponse: CallTokenResponse) {+ const existingRoom = options.room();+ const state = options.state();++ if (+ existingRoom &&+ state.activeChannelId === tokenResponse.channelId &&+ options.isActiveConnectionState(state.connectionState)+ ) {+ // A duplicate join can arrive while LiveKit is already connected or+ // recovering its signaling connection. Do not call room.connect() again;+ // that replaces the SDK's reconnection attempt and can wedge the peer+ // connection until the user manually leaves/rejoins.+ console.debug('[call] ignoring duplicate connect for active room', {+ channelId: tokenResponse.channelId,+ state: state.connectionState,+ });+ options.setDuplicateConnectCallId(tokenResponse.callId);+ return;+ }++ // If switching channels, or if a previous disconnected room instance is+ // still hanging around after a failed reconnect, tear it down and build a+ // fresh Room. This gives retry/auto-rejoin the same clean slate as a manual+ // leave + join.+ if (existingRoom) {+ await existingRoom.disconnect();+ destroyRoom();+ }++ const targetRoom = new Room({+ audioCaptureDefaults: options.currentMicrophoneCaptureOptions(),+ });+ attachRoomListeners(targetRoom);+ options.setRoom(targetRoom);+ options.setActiveCall(tokenResponse.channelId, tokenResponse.callId);+ options.setSharedWithTeam(true);++ try {+ await targetRoom.connect(tokenResponse.serverUrl, tokenResponse.token);+ options.clearOptimisticJoin();+ } catch (e) {+ console.error('failed to connect to LiveKit room', e);+ destroyRoom();+ throw e;+ }++ // Sync participants that were already in the room when we connected.+ syncParticipantMap(targetRoom);++ // Default to microphone on, video off as soon as the room is connected.+ options.setInitialMediaState();++ // Treat the LiveKit connection itself as the join success boundary. Local+ // media/device setup can be interrupted by OS-level flows (e.g. macOS+ // screenshot) or slow permission/device APIs; if we await it here, the+ // join mutation timeout can fire after the user is already in the room and+ // run failed-join cleanup, which calls DELETE /call/:channel and kicks the+ // user out. Run the non-critical setup in the background instead.+ const setupVersion = options.nextMediaSetupVersion();+ void options.finishLocalMediaSetup(targetRoom, setupVersion).catch((e) => {+ console.error('failed to finish local call media setup', e);+ });+ }++ async function disconnect() {+ const room = options.room();+ if (!room) return;++ options.cancelPendingMediaSetup();+ try {+ await room.disconnect();+ } finally {+ destroyRoom();+ }+ }++ function disconnectBeforeUnload() {+ const room = options.room();+ if (!room) return;++ options.cancelPendingMediaSetup();+ room.disconnect();+ }++ function dispose() {+ options.cancelPendingMediaSetup();+ const room = options.room();+ if (!room) return;++ room.disconnect();+ room.removeAllListeners();+ }++ return {+ connect,+ disconnect,+ disconnectBeforeUnload,+ dispose,+ };+}diff --git a/js/app/packages/channel/Call/call-tabs.ts b/js/app/packages/channel/Call/call-tabs.tsnew file mode 100644index 0000000000..f698154639--- /dev/null+++ b/js/app/packages/channel/Call/call-tabs.ts@@ -0,0 +1,13 @@+import {+ type ChannelTabId,+ DEFAULT_CHANNEL_TAB,+} from '@channel/Channel/channel-tabs';+import { isNativeIosCallKitEnabled } from './use-callkit';++export function getCallJoinTab(): ChannelTabId {+ return isNativeIosCallKitEnabled() ? DEFAULT_CHANNEL_TAB : 'call';+}++export function getCallLeaveTab(): ChannelTabId {+ return DEFAULT_CHANNEL_TAB;+}diff --git a/js/app/packages/channel/Call/callkit-drawer-theme.ts b/js/app/packages/channel/Call/callkit-drawer-theme.tsnew file mode 100644index 0000000000..b7f5d9ba9f--- /dev/null+++ b/js/app/packages/channel/Call/callkit-drawer-theme.ts@@ -0,0 +1,190 @@+import { ENABLE_CALLKIT } from '@core/constant/featureFlags';+import { isPlatform, isTauri } from '@core/util/platform';+import { invoke } from '@tauri-apps/api/core';+import { themeReactive } from '@theme/signals/themeReactive';+import Color from 'colorjs.io';+import { type Accessor, createMemo } from 'solid-js';++export type RgbaColor = {+ red: number;+ green: number;+ blue: number;+ alpha: number;+};++export type CallKitDrawerTheme = {+ drawerBackground: RgbaColor;+ text: RgbaColor;+ messageBackground: RgbaColor;+ overlayBackground: RgbaColor;+ edgeMuted: RgbaColor;+ edge: RgbaColor;+ inkMuted: RgbaColor;+ failure: RgbaColor;+ failureInk: RgbaColor;+ success: RgbaColor;+};++export function createCallKitDrawerTheme(): Accessor<CallKitDrawerTheme> {+ return createMemo(currentCallKitTheme, undefined, {+ equals: (a, b) => callKitDrawerThemeKey(a) === callKitDrawerThemeKey(b),+ });+}++export async function setNativeCallKitDrawerTheme(+ theme: CallKitDrawerTheme+): Promise<void> {+ if (!ENABLE_CALLKIT || !isTauri() || !isPlatform('ios')) return;+ await invoke('plugin:call-kit|set_call_drawer_theme', {+ drawerBackground: theme.drawerBackground,+ text: theme.text,+ messageBackground: theme.messageBackground,+ overlayBackground: theme.overlayBackground,+ edgeMuted: theme.edgeMuted,+ edge: theme.edge,+ inkMuted: theme.inkMuted,+ failure: theme.failure,+ failureInk: theme.failureInk,+ success: theme.success,+ }).catch((err) =>+ console.error('[callkit] failed to set native drawer theme', err)+ );+}++function currentCallKitTheme(): CallKitDrawerTheme {+ const b0 = currentThemeToken('b0');+ const c0 = currentThemeToken('c0');+ const b1 = currentThemeToken('b1');+ const b2 = currentThemeToken('b2');+ const b3 = currentThemeToken('b3');+ const b4 = currentThemeToken('b4');+ const c1 = currentThemeToken('c1');+ const message = {+ l: (b1.l + b2.l) / 2,+ c: (b1.c + b2.c) / 2,+ h: (b1.h + b2.h) / 2,+ };+ const failure = { l: 0.637, c: 0.237, h: 25.331 };+ const success = { l: 0.696, c: 0.17, h: 162.48 };++ return {+ drawerBackground: oklchToRgba(b0, { red: 0, green: 0, blue: 0, alpha: 1 }),+ text: oklchToRgba(c0, { red: 1, green: 1, blue: 1, alpha: 1 }),+ messageBackground: oklchToRgba(message, {+ red: 0.08,+ green: 0.08,+ blue: 0.08,+ alpha: 1,+ }),+ overlayBackground: oklchToRgba(+ b1,+ {+ red: 0,+ green: 0,+ blue: 0,+ alpha: 0.46,+ },+ 0.8+ ),+ edgeMuted: oklchToRgba(b3, {+ red: 0.18,+ green: 0.18,+ blue: 0.18,+ alpha: 1,+ }),+ edge: oklchToRgba(b4, {+ red: 0.36,+ green: 0.36,+ blue: 0.36,+ alpha: 1,+ }),+ inkMuted: oklchToRgba(c1, {+ red: 0.6,+ green: 0.6,+ blue: 0.6,+ alpha: 1,+ }),+ failure: oklchToRgba(failure, {+ red: 0.95,+ green: 0.1,+ blue: 0.1,+ alpha: 1,+ }),+ failureInk: oklchToRgba(+ { l: c1.l, c: failure.c, h: failure.h },+ {+ red: 1,+ green: 1,+ blue: 1,+ alpha: 1,+ }+ ),+ success: oklchToRgba(success, {+ red: 0.1,+ green: 0.7,+ blue: 0.4,+ alpha: 1,+ }),+ };+}++function currentThemeToken(+ token: 'b0' | 'b1' | 'b2' | 'b3' | 'b4' | 'c0' | 'c1'+) {+ return {+ l: themeReactive[token].l[0](),+ c: themeReactive[token].c[0](),+ h: themeReactive[token].h[0](),+ };+}++function oklchToRgba(+ token: { l: number; c: number; h: number },+ fallback: RgbaColor,+ alpha?: number+): RgbaColor {+ try {+ const srgb = new Color('oklch', [token.l, token.c, token.h]).to('srgb');+ return {+ red: clampColorChannel(srgb.coords[0]),+ green: clampColorChannel(srgb.coords[1]),+ blue: clampColorChannel(srgb.coords[2]),+ alpha: clampColorChannel(alpha ?? srgb.alpha ?? 1),+ };+ } catch (err) {+ console.error('[callkit] failed to resolve theme color', {+ token,+ err,+ });+ return fallback;+ }+}++function callKitDrawerThemeKey(theme: CallKitDrawerTheme): string {+ return [+ colorKeyPart(theme.drawerBackground),+ colorKeyPart(theme.text),+ colorKeyPart(theme.messageBackground),+ colorKeyPart(theme.overlayBackground),+ colorKeyPart(theme.edgeMuted),+ colorKeyPart(theme.edge),+ colorKeyPart(theme.inkMuted),+ colorKeyPart(theme.failure),+ colorKeyPart(theme.failureInk),+ colorKeyPart(theme.success),+ ].join(':');+}++function colorKeyPart(color: RgbaColor): string {+ return [+ color.red.toFixed(4),+ color.green.toFixed(4),+ color.blue.toFixed(4),+ color.alpha.toFixed(4),+ ].join(',');+}++function clampColorChannel(value: number): number {+ if (!Number.isFinite(value)) return 0;+ return Math.max(0, Math.min(1, value));+}diff --git a/js/app/packages/channel/Call/index.ts b/js/app/packages/channel/Call/index.tsindex f9361a26bd..5fb6dd6263 100644--- a/js/app/packages/channel/Call/index.ts+++ b/js/app/packages/channel/Call/index.ts@@ -16,6 +16,7 @@ export { CallStartedNotifier } from './CallStartedNotifier';export { ChannelCallAutoJoin } from './ChannelCallAutoJoin';export { ChannelCallButton } from './ChannelCallButton';export { ChannelCallTab } from './ChannelCallTab';+export { getCallJoinTab, getCallLeaveTab } from './call-tabs';export type {InCallPanelControls,InCallPanelMember,@@ -35,6 +36,11 @@ export {useInCallPanel,} from './InCallPanel';export { joinChannelCall } from './join-channel-call';+export { NativeCallProvider } from './native-call-state';export { openChannelCallTab } from './open-channel-call-tab';export { useCall } from './use-call';-export { useCallKitSetup } from './use-callkit';+export {+ CallKitSync,+ isNativeIosCallKitEnabled,+ useCallKitSetup,+} from './use-callkit';diff --git a/js/app/packages/channel/Call/native-call-state.ts b/js/app/packages/channel/Call/native-call-state.tsnew file mode 100644index 0000000000..cb03b8e0b1--- /dev/null+++ b/js/app/packages/channel/Call/native-call-state.ts@@ -0,0 +1,96 @@+import {+ type Accessor,+ createComponent,+ createContext,+ createSignal,+ type ParentProps,+ type Setter,+ useContext,+} from 'solid-js';+import {+ type CallKitDrawerTheme,+ createCallKitDrawerTheme,+} from './callkit-drawer-theme';++export type NativeCallConnectionState =+ | 'disconnected'+ | 'connecting'+ | 'connected'+ | 'reconnecting'+ | 'disconnecting';++// Keep this narrow: CallContext reads these fields directly for native iOS calls.+export type NativeCallSnapshot = {+ channelId: string;+ callId: string;+ connectionState: NativeCallConnectionState;+ isAudioMuted: boolean;+ isVideoMuted: boolean;+ videoOverlayMode: 'hidden' | 'expanded' | 'minimized';+};++export type NativeCallState = {+ snapshot: Accessor<NativeCallSnapshot | null>;+ setSnapshot: Setter<NativeCallSnapshot | null>;+ bootstrapChannelId: Accessor<string | null>;+ setBootstrapChannelId: Setter<string | null>;+ participantIdentities: Accessor<string[]>;+ setParticipantIdentities: Setter<string[]>;+ activeChannelId: Accessor<string | null>;+ drawerTheme: Accessor<CallKitDrawerTheme>;+};++const NativeCallContext = createContext<NativeCallState>();++function createNativeCallState(): NativeCallState {+ const [snapshot, setSnapshot] = createSignal<NativeCallSnapshot | null>(null);+ // Tracks the channel from early native CallKit events before the full native+ // media snapshot is available. snapshot remains authoritative once set.+ const [bootstrapChannelId, setBootstrapChannelId] = createSignal<+ string | null+ >(null);+ const [participantIdentities, setParticipantIdentities] = createSignal<+ string[]+ >([]);+ const drawerTheme = createCallKitDrawerTheme();++ return {+ snapshot,+ setSnapshot,+ bootstrapChannelId,+ setBootstrapChannelId,+ participantIdentities,+ setParticipantIdentities,+ activeChannelId: () => snapshot()?.channelId ?? bootstrapChannelId(),+ drawerTheme,+ };+}++export function NativeCallProvider(props: ParentProps) {+ const existing = useContext(NativeCallContext);+ if (existing) return props.children;++ const state = createNativeCallState();+ return createComponent(NativeCallContext.Provider, {+ get value() {+ return state;+ },+ get children() {+ return props.children;+ },+ });+}++export function useNativeCallState(): NativeCallState {+ const ctx = useContext(NativeCallContext);+ if (!ctx) {+ throw new Error(+ 'useNativeCallState must be used within <NativeCallProvider />'+ );+ }+ return ctx;+}++export function useMaybeNativeCallState(): NativeCallState | undefined {+ return useContext(NativeCallContext);+}diff --git a/js/app/packages/channel/Call/open-channel-call-tab.ts b/js/app/packages/channel/Call/open-channel-call-tab.tsindex 7c20a621a6..77987146dc 100644--- a/js/app/packages/channel/Call/open-channel-call-tab.ts+++ b/js/app/packages/channel/Call/open-channel-call-tab.ts@@ -1,5 +1,7 @@import { globalSplitManager } from '@app/signal/splitLayout';import { URL_PARAMS } from '@channel/Channel/link';+import { ENABLE_CALLKIT } from '@core/constant/featureFlags';+import { isPlatform, isTauri } from '@core/util/platform';/*** Focuses the channel split (opens if needed) and switches to the Call tab@@ -21,6 +23,9 @@ export async function openChannelCallTab(channelId: string): Promise<void> {const orchestrator = manager.getOrchestrator();const handle = await orchestrator.getBlockHandle(channelId, 'channel');+ if (ENABLE_CALLKIT && isTauri() && isPlatform('ios')) {+ return;+ }await handle?.goToLocationFromParams({[URL_PARAMS.openCallTab]: 'true',});diff --git a/js/app/packages/channel/Call/use-call.ts b/js/app/packages/channel/Call/use-call.tsindex 5e38032a68..7ef268ce0d 100644--- a/js/app/packages/channel/Call/use-call.ts+++ b/js/app/packages/channel/Call/use-call.ts@@ -1,3 +1,4 @@+import { useChannelsContext } from '@core/context/channels';import { throwOnErr } from '@core/util/result';import {invalidateActiveCallQueries,@@ -8,7 +9,7 @@ import { useMutation } from '@tanstack/solid-query';import { DisconnectReason, RoomEvent } from 'livekit-client';import { createEffect, createSignal, onCleanup } from 'solid-js';import { useCallContext } from './CallContext';-import { endCallKitCall, registerCallKitCallEndedHandler } from './use-callkit';+import { registerCallKitCallEndedHandler } from './use-callkit';type UseCallOptions = {/** Called after successfully joining a call. */@@ -56,13 +57,14 @@ let leaveInFlight = false;/*** Hook that orchestrates joining/leaving calls by combining- * the API mutations with the LiveKit room connection.+ * the API mutations with the platform call session controller.** Join is implemented as a single TanStack mutation so optimistic UI, timeout,* rollback, and server cleanup stay in onMutate / onError / onSuccess.*/export function useCall(channelId: () => string, options?: UseCallOptions) {const callCtx = useCallContext();+ const channelsCtx = useChannelsContext();const leaveMutation = useLeaveCallMutation();// Track the disconnect listener so we can swap it when the room changes.@@ -155,6 +157,11 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {};const doConnect = async () => {+ if (!callCtx.shouldRequestSessionToken(id)) {+ callCtx.rollbackOptimisticJoin();+ return;+ }+// Call the join API directly so a timed-out join attempt cannot leave// `useJoinCallMutation` stuck pending and block the next retry.const [tokenResponse] = await Promise.all([@@ -162,7 +169,11 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {new Promise<void>((resolve) => setTimeout(resolve, 300)),]);if (cancelled) return;- await callCtx.connect(tokenResponse);++ await callCtx.connectSession(tokenResponse, {+ channelTitle:+ channelsCtx.channelsById()[tokenResponse.channelId]?.name ?? null,+ });};const timeout = new Promise<never>((_, reject) =>@@ -199,7 +210,7 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {);void (async () => {try {- await callCtx.disconnect();+ await callCtx.disconnectSession({ endNativeCall: false });} catch (e) {console.error('join error recovery: disconnect failed', e);}@@ -251,20 +262,9 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {cleanupDisconnectListener?.();cleanupDisconnectListener = null;clearAutoRejoinTimer();- // Dismiss the native CallKit call sheet if the user left from within the app.- // When the leave is initiated by CXEndCallAction, the native sheet is already- // ending, so avoid sending a second native end request back to CallKit.- // Isolated try/catch so a CallKit dismissal failure never skips disconnect.try {- if (leaveOptions?.endNativeCall !== false) {- try {- await endCallKitCall();- } catch (e) {- console.error('callkit: failed to dismiss call sheet', e);- }- }try {- await callCtx.disconnect();+ await callCtx.disconnectSession(leaveOptions);options?.onLeave?.();} finally {await leaveMutation.mutateAsync(id);diff --git a/js/app/packages/channel/Call/use-callkit-theme-sync.ts b/js/app/packages/channel/Call/use-callkit-theme-sync.tsnew file mode 100644index 0000000000..70deae0582--- /dev/null+++ b/js/app/packages/channel/Call/use-callkit-theme-sync.ts@@ -0,0 +1,15 @@+import { createEffect } from 'solid-js';+import { setNativeCallKitDrawerTheme } from './callkit-drawer-theme';+import { useNativeCallState } from './native-call-state';++export function useCallKitThemeSync() {+ const nativeCall = useNativeCallState();++ createEffect(() => {+ setNativeCallKitDrawerTheme(nativeCall.drawerTheme()).catch((err) =>+ console.error('[callkit] failed to sync native drawer theme', err)+ );+ });++ return null;+}diff --git a/js/app/packages/channel/Call/use-callkit.ts b/js/app/packages/channel/Call/use-callkit.tsindex 1330dd9428..8de263c202 100644--- a/js/app/packages/channel/Call/use-callkit.ts+++ b/js/app/packages/channel/Call/use-callkit.ts@@ -1,21 +1,107 @@+import { whenSplitManagerReady } from '@app/signal/splitLayout';import { ENABLE_CALLKIT } from '@core/constant/featureFlags';+import { useChannelsContext } from '@core/context/channels';import { isPlatform, isTauri } from '@core/util/platform';+import { useUserNamesQuery } from '@queries/auth';+import type { UserName } from '@service-auth/generated/schemas/userName';import { notificationServiceClient } from '@service-notification/client';import type { DeviceType } from '@service-notification/generated/schemas/deviceType';-import { invoke } from '@tauri-apps/api/core';-import { listen } from '@tauri-apps/api/event';-import { onCleanup, onMount } from 'solid-js';+import { raceTimeout } from '@solid-primitives/promise';+import { addPluginListener, Channel, invoke } from '@tauri-apps/api/core';+import { createEffect, createMemo, on, onCleanup, onMount } from 'solid-js';import { joinChannelCall } from './join-channel-call';+import {+ type NativeCallSnapshot,+ type NativeCallState,+ useNativeCallState,+} from './native-call-state';+import { openChannelCallTab } from './open-channel-call-tab';+import { useCallKitThemeSync } from './use-callkit-theme-sync';// The 'iosvoip' variant exists in the backend but the generated schema has not been// regenerated to include it yet. Cast until a regeneration picks it up.const DEVICE_TYPE_IOS_VOIP = 'iosvoip' as DeviceType;type VoipTokenPayload = { token: string };-type CallAnsweredPayload = { channelId: string };+type CallAnsweredPayload = { channelId: string; nativeMedia?: boolean };type CallEndedPayload = { callId: string };+type DrawerOpenedPayload = { channelId: string };+type ParticipantIdentitiesPayload = { identities: string[] };type CallEndedHandler = (payload: CallEndedPayload) => void | Promise<void>;+type StartOutgoingCallArgs = {+ channelId: string;+ callId: string;+ channelTitle?: string | null;+ callerName?: string | null;+ serverUrl: string;+ token: string;+};++type ConnectionStatePayload = {+ state: NativeCallSnapshot['connectionState'];+ channelId: NativeCallSnapshot['channelId'] | null;+ callId: NativeCallSnapshot['callId'] | null;+ isAudioMuted?: NativeCallSnapshot['isAudioMuted'];+ isVideoMuted?: NativeCallSnapshot['isVideoMuted'];+ videoOverlayMode?: NativeCallSnapshot['videoOverlayMode'];+};++type GetActiveCallStateResponse = {+ state: (NativeCallSnapshot & { participantIdentities?: string[] }) | null;+};++type GetPendingAnsweredCallResponse = {+ channelId: string | null;+ nativeMedia?: boolean | null;+};++type NativeCallChannelMetadata = {+ channelId: string;+ name?: string | null;+};++type NativeCallChannelTitleSyncValue =+ | { channelId: string; channelTitle: string }+ | null+ | undefined;++type NativeParticipantDisplayNames =+ | { isPending: true }+ | {+ isPending: false;+ displayNames: Record<string, string>;+ fetchedNameCount: number;+ errors: unknown[];+ };++function applyConnectionState(+ nativeCall: NativeCallState,+ payload: ConnectionStatePayload+) {+ console.info('[callkit] connection state channel message', payload);+ if (+ !payload.channelId ||+ !payload.callId ||+ payload.state === 'disconnected'+ ) {+ nativeCall.setBootstrapChannelId(null);+ nativeCall.setParticipantIdentities([]);+ nativeCall.setSnapshot(null);+ return;+ }+ const snapshot: NativeCallSnapshot = {+ channelId: payload.channelId,+ callId: payload.callId,+ connectionState: payload.state,+ isAudioMuted: payload.isAudioMuted ?? false,+ isVideoMuted: payload.isVideoMuted ?? true,+ videoOverlayMode: payload.videoOverlayMode ?? 'hidden',+ };+ nativeCall.setBootstrapChannelId(snapshot.channelId);+ nativeCall.setSnapshot(snapshot);+}+const callEndedHandlers: CallEndedHandler[] = [];/**@@ -41,6 +127,50 @@ function getActiveCallEndedHandler(): CallEndedHandler | undefined {return callEndedHandlers[callEndedHandlers.length - 1];}+export function isNativeIosCallKitEnabled(): boolean {+ return ENABLE_CALLKIT && isTauri() && isPlatform('ios');+}++// Fresh CallKit launches can receive answer events before the router tree mounts.+const SPLIT_MANAGER_READY_TIMEOUT_MS = 15_000;+const DUPLICATE_ANSWERED_CALL_WINDOW_MS = 2_000;++async function joinChannelCallWhenReady(+ channelId: string,+ nativeMedia = false+): Promise<void> {+ console.info('[callkit] waiting for split manager before joining', {+ channelId,+ nativeMedia,+ });+ const splitManagerAbortController = new AbortController();+ try {+ await raceTimeout(+ whenSplitManagerReady(splitManagerAbortController.signal),+ SPLIT_MANAGER_READY_TIMEOUT_MS,+ true+ );+ } catch {+ splitManagerAbortController.abort();+ console.error(+ `[callkit] split manager not ready within ${SPLIT_MANAGER_READY_TIMEOUT_MS}ms; ending CallKit call`+ );+ await endCallKitCall();+ return;+ }+ console.info('[callkit] split manager ready; joining channel call', {+ channelId,+ nativeMedia,+ });+ if (nativeMedia) {+ console.info('[callkit] opening channel call tab for native media', {+ channelId,+ });+ return openChannelCallTab(channelId);+ }+ return joinChannelCall(channelId);+}+/*** Sets up CallKit / PushKit integration for iOS.*@@ -51,56 +181,82 @@ function getActiveCallEndedHandler(): CallEndedHandler | undefined {* Must be mounted once at app startup on iOS (no-op on all other platforms).*/export function useCallKitSetup() {+ if (!isNativeIosCallKitEnabled()) return;++ const nativeCall = useNativeCallState();+onMount(() => {- if (!ENABLE_CALLKIT || !isTauri() || !isPlatform('ios')) return;+ console.info('[callkit] setting up iOS CallKit integration');let cleaned = false;- const unlistens: Array<() => void> = [];+ let lastHandledAnsweredCall:+ | { key: string; handledAtMs: number }+ | undefined;+ const unregisters: Array<() => Promise<void>> = [];+ const channelWatchers: Array<Channel<unknown>> = [];onCleanup(() => {cleaned = true;- unlistens.forEach((u) => u());+ unregisters.forEach((u) =>+ u().catch((err) =>+ console.error('[callkit] failed to unregister listener', err)+ )+ );+ unregisters.length = 0;+ channelWatchers.length = 0;});- // If cleanup runs before a listen() promise resolves, the unlisten arrives- // too late to be caught by the forEach above — call it immediately instead.- function track(p: Promise<() => void>) {- p.then((u) => {- if (cleaned) u();- else unlistens.push(u);+ function trackListener(+ promise: Promise<{ unregister: () => Promise<void> }>,+ label: string+ ) {+ promise+ .then((l) => {+ if (cleaned) {+ l.unregister().catch((err) =>+ console.error(`[callkit] failed to unregister ${label}`, err)+ );+ return;+ }+ unregisters.push(() => l.unregister());+ })+ .catch((err) =>+ console.error(`[callkit] failed to register ${label}`, err)+ );+ }++ function registerChannelWatcher<T>(+ command: string,+ label: string,+ handler: (payload: T) => void+ ) {+ const channel = new Channel<T>((payload) => {+ if (cleaned) return;+ handler(payload);});+ channelWatchers.push(channel as Channel<unknown>);+ invoke(`plugin:call-kit|${command}`, { channel })+ .then(() => console.info(`[callkit] ${label} watcher registered`))+ .catch((err) =>+ console.error(`[callkit] failed to register ${label} watcher`, err)+ );}- track(- listen<VoipTokenPayload>(- 'plugin:call-kit:voip-token-updated',- async (event) => {- const { token } = event.payload;+ trackListener(+ addPluginListener<VoipTokenPayload>(+ 'call-kit',+ 'voip-token-updated',+ async ({ token }) => {+ console.info('[callkit] received VoIP token update', {+ tokenLength: token.length,+ });await notificationServiceClient.registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP }).catch((err) =>- console.error('callkit: failed to register VoIP token', err)+ console.error('[callkit] failed to register VoIP token', err));}- )- );-- track(- listen<CallAnsweredPayload>('plugin:call-kit:call-answered', (event) => {- const { channelId } = event.payload;- joinChannelCall(channelId).catch((err) =>- console.error('callkit: failed to join channel call', err)- );- })- );-- track(- listen<CallEndedPayload>('plugin:call-kit:call-ended', (event) => {- const handler = getActiveCallEndedHandler();- if (!handler) return;- Promise.resolve(handler(event.payload)).catch((err) =>- console.error('callkit: failed to handle ended call', err)- );- })+ ),+ 'voip-token-updated');// Drain any VoIP token that arrived from PushKit before the listener above@@ -108,16 +264,382 @@ export function useCallKitSetup() {invoke<{ token: string | null }>('plugin:call-kit|get_voip_token').then(({ token }) => {if (!token) return;+ console.info('[callkit] registering cached VoIP token', {+ tokenLength: token.length,+ });return notificationServiceClient.registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP }).catch((err) =>- console.error('callkit: failed to register cached VoIP token', err)+ console.error('[callkit] failed to register cached VoIP token', err));})- .catch((err) => console.error('callkit: get_voip_token failed', err));+ .catch((err) => console.error('[callkit] get_voip_token failed', err));++ const handleCallAnswered = (+ { channelId, nativeMedia }: CallAnsweredPayload,+ source: 'channel' | 'pending' = 'channel'+ ) => {+ const answeredCallKey = `${channelId}:${nativeMedia ?? false}`;+ const now = Date.now();+ if (+ lastHandledAnsweredCall?.key === answeredCallKey &&+ now - lastHandledAnsweredCall.handledAtMs <+ DUPLICATE_ANSWERED_CALL_WINDOW_MS+ ) {+ return;+ }+ lastHandledAnsweredCall = { key: answeredCallKey, handledAtMs: now };++ console.info('[callkit] call answered event', {+ channelId,+ nativeMedia,+ source,+ });+ nativeCall.setBootstrapChannelId(channelId);+ joinChannelCallWhenReady(channelId, nativeMedia).catch((err) =>+ console.error('[callkit] joinChannelCallWhenReady failed', err)+ );+ };++ registerChannelWatcher<CallAnsweredPayload>(+ 'watch_call_answered',+ 'call answered',+ (payload) => handleCallAnswered(payload, 'channel')+ );++ const drainPendingAnsweredCall = () => {+ invoke<GetPendingAnsweredCallResponse>(+ 'plugin:call-kit|get_pending_answered_call'+ )+ .then(({ channelId, nativeMedia }) => {+ console.info('[callkit] drained pending answered call', {+ channelId,+ nativeMedia,+ });+ if (!channelId) return;+ handleCallAnswered(+ { channelId, nativeMedia: nativeMedia ?? false },+ 'pending'+ );+ })+ .catch((err) =>+ console.error('[callkit] get_pending_answered_call failed', err)+ );+ };++ drainPendingAnsweredCall();++ registerChannelWatcher<CallEndedPayload>(+ 'watch_call_ended',+ 'call ended',+ (payload) => {+ console.info('[callkit] call ended event', payload);+ lastHandledAnsweredCall = undefined;+ nativeCall.setBootstrapChannelId(null);+ nativeCall.setParticipantIdentities([]);+ const handler = getActiveCallEndedHandler();+ if (!handler) return;+ Promise.resolve(handler(payload)).catch((err) =>+ console.error('[callkit] failed to handle ended call', err)+ );+ }+ );++ registerChannelWatcher<ConnectionStatePayload>(+ 'watch_connection_state',+ 'connection state',+ (payload) => applyConnectionState(nativeCall, payload)+ );++ registerChannelWatcher<ParticipantIdentitiesPayload>(+ 'watch_participant_identities',+ 'participant identities',+ ({ identities }) => {+ console.info('[callkit] participant identities event', {+ identities,+ });+ nativeCall.setParticipantIdentities(identities);+ }+ );++ registerChannelWatcher<DrawerOpenedPayload>(+ 'watch_drawer_opened',+ 'drawer opened',+ ({ channelId }) => {+ console.info('[callkit] drawer opened event', {+ channelId,+ });+ nativeCall.setBootstrapChannelId(channelId);+ joinChannelCallWhenReady(channelId, true).catch((err) =>+ console.error(+ '[callkit] joinChannelCallWhenReady (drawer opened) failed',+ err+ )+ );+ }+ );++ // Do not let a stale startup drain overwrite live listener state.+ invoke<GetActiveCallStateResponse>('plugin:call-kit|get_active_call_state')+ .then(({ state }) => {+ console.info('[callkit] initial active call state', { state });+ if (!state) return;+ nativeCall.setParticipantIdentities(state.participantIdentities ?? []);+ if (nativeCall.snapshot() !== null) return;+ nativeCall.setBootstrapChannelId(state.channelId);+ nativeCall.setSnapshot({+ channelId: state.channelId,+ callId: state.callId,+ connectionState: state.connectionState,+ isAudioMuted: state.isAudioMuted,+ isVideoMuted: state.isVideoMuted,+ videoOverlayMode: state.videoOverlayMode,+ });+ })+ .catch((err) =>+ console.error('[callkit] get_active_call_state failed', err)+ );});}+function useCallKitNativeMetadataSync() {+ const nativeCall = useNativeCallState();+ const channelsCtx = useChannelsContext();++ const channelMetadata = createMemo((): NativeCallChannelMetadata | null => {+ const channelId = nativeCall.activeChannelId();+ if (!channelId) return null;++ const listedChannel = channelsCtx.channelsById()[channelId];+ if (listedChannel) {+ return {+ channelId,+ name: listedChannel.name,+ };+ }++ return null;+ });++ const channelTitleSyncValue = createMemo(+ (): NativeCallChannelTitleSyncValue => {+ const metadata = channelMetadata();+ if (!metadata) {+ return nativeCall.activeChannelId() ? undefined : null;+ }++ const channelTitle = metadata.name?.trim();+ if (!channelTitle) return undefined;++ return {+ channelId: metadata.channelId,+ channelTitle,+ };+ }+ );++ createEffect(+ on(channelTitleSyncValue, (syncValue, previousSyncValue) => {+ if (syncValue === undefined) return;++ if (syncValue === null) {+ if (previousSyncValue === null) return;+ setNativeCallKitChannelTitle(null).catch((err) =>+ console.error('[callkit] failed to clear native channel title', err)+ );+ return;+ }++ if (+ previousSyncValue &&+ previousSyncValue.channelTitle === syncValue.channelTitle+ ) {+ return;+ }++ console.info('[callkit] syncing native channel title', syncValue);+ setNativeCallKitChannelTitle(syncValue.channelTitle).catch((err) =>+ console.error('[callkit] failed to sync native channel title', err)+ );+ })+ );++ return null;+}++function useCallKitParticipantDisplayNameSync() {+ const nativeCall = useNativeCallState();+ const nativeParticipantIds = createMemo(() =>+ nativeCall.participantIdentities()+ );+ const participantIds = createMemo(() =>+ uniqueParticipantIds(nativeParticipantIds())+ );++ const participantUserNameQueries = useUserNamesQuery({+ userIds: participantIds,+ enabled: () => participantIds().length > 0,+ });++ const participantDisplayNames = createMemo(+ (): NativeParticipantDisplayNames | undefined => {+ const ids = participantIds();+ if (ids.length === 0) return undefined;++ const isPending = participantUserNameQueries.some(+ (query) => query.isPending+ );+ if (isPending) return { isPending: true };++ const fetchedNames = participantUserNameQueries+ .map((query) => query.data)+ .filter((name): name is UserName => Boolean(name));++ return {+ isPending: false,+ displayNames: buildParticipantDisplayNames(+ ids,+ fallbackParticipantDisplayNames(ids),+ fetchedNames+ ),+ fetchedNameCount: fetchedNames.length,+ errors: participantUserNameQueries+ .filter((query) => query.isError)+ .map((query) => query.error),+ };+ }+ );++ createEffect(+ on(participantDisplayNames, (displayNameData) => {+ if (!displayNameData) return;+ if (displayNameData.isPending) return;++ const channelId = nativeCall.activeChannelId();+ const nativeParticipantIds = nativeCall.participantIdentities();+ const ids = participantIds();++ if (displayNameData.errors.length > 0) {+ console.error('[callkit] failed to fetch participant display names', {+ channelId,+ nativeParticipantIds,+ participantIds: ids,+ errors: displayNameData.errors,+ });+ }++ console.info('[callkit] syncing native participant display names', {+ channelId,+ participantCount: ids.length,+ fetchedNameCount: displayNameData.fetchedNameCount,+ });++ syncNativeParticipantDisplayNames(displayNameData.displayNames);+ })+ );++ return null;+}++export function CallKitSync() {+ if (!isNativeIosCallKitEnabled()) return null;++ useCallKitNativeMetadataSync();+ useCallKitParticipantDisplayNameSync();+ useCallKitThemeSync();+ return null;+}++function buildParticipantDisplayNames(+ participantIds: string[],+ fallbackNames: Record<string, string>,+ fetchedNames: UserName[]+): Record<string, string> {+ const displayNames = { ...fallbackNames };+ const fetchedNamesByIdentity = new Map<string, string>();++ for (const user of fetchedNames) {+ fetchedNamesByIdentity.set(+ normalizeParticipantIdentity(user.id),+ displayNameFromUserName(user)+ );+ }++ for (const identity of participantIds) {+ displayNames[identity] =+ fetchedNamesByIdentity.get(normalizeParticipantIdentity(identity)) ??+ fallbackNames[identity];+ }++ return displayNames;+}++function fallbackParticipantDisplayNames(+ participantIds: string[]+): Record<string, string> {+ return Object.fromEntries(+ participantIds.map((identity) => [+ identity,+ fallbackParticipantName(identity),+ ])+ );+}++function syncNativeParticipantDisplayNames(+ displayNames: Record<string, string>+) {+ for (const [identity, displayName] of Object.entries(displayNames)) {+ setNativeCallKitParticipantDisplayName(identity, displayName).catch((err) =>+ console.error(+ '[callkit] failed to sync native participant display name',+ err+ )+ );+ }+}++function uniqueParticipantIds(ids: string[]): string[] {+ const seen = new Set<string>();+ const participantIds: string[] = [];+ for (const id of ids) {+ const trimmedId = id.trim();+ const normalizedId = normalizeParticipantIdentity(trimmedId);+ if (!isMacroParticipantIdentity(trimmedId) || seen.has(normalizedId)) {+ continue;+ }+ seen.add(normalizedId);+ participantIds.push(trimmedId);+ }+ return participantIds;+}++function isMacroParticipantIdentity(identity: string): boolean {+ const trimmedIdentity = identity.trim();+ return (+ normalizeParticipantIdentity(trimmedIdentity).startsWith('macro|') &&+ trimmedIdentity.includes('@')+ );+}++function normalizeParticipantIdentity(identity: string): string {+ return identity.trim().toLowerCase();+}++function displayNameFromUserName(user: {+ id: string;+ first_name?: string | null;+ last_name?: string | null;+}): string {+ const parts = [user.first_name, user.last_name]+ .map((part) => part?.trim())+ .filter((part): part is string => Boolean(part) && part !== 'N/A');+ return parts.length > 0 ? parts.join(' ') : fallbackParticipantName(user.id);+}++function fallbackParticipantName(identity: string): string {+ return identity.split('|').at(1)?.split('@').at(0) || 'Participant';+}+/*** Tells CallKit to end the active call session.*@@ -125,8 +647,59 @@ export function useCallKitSetup() {* the user leaves from within the app rather than from the CallKit sheet.*/export async function endCallKitCall(): Promise<void> {- if (!ENABLE_CALLKIT || !isTauri() || !isPlatform('ios')) return;+ if (!isNativeIosCallKitEnabled()) return;await invoke('plugin:call-kit|end_active_call').catch((err) =>- console.error('callkit: failed to end active call', err)+ console.error('[callkit] failed to end active call', err)+ );+}++export async function startNativeCallKitOutgoingCall(+ args: StartOutgoingCallArgs,+ nativeCall: Pick<NativeCallState, 'setBootstrapChannelId'>+): Promise<void> {+ if (!isNativeIosCallKitEnabled()) return;+ console.info('[callkit] starting native outgoing call', {+ channelId: args.channelId,+ callId: args.callId,+ channelTitle: args.channelTitle,+ });+ await invoke('plugin:call-kit|start_outgoing_call', args);+ nativeCall.setBootstrapChannelId(args.channelId);+}++export async function setNativeCallKitVideoOverlayMode(+ mode: NativeCallSnapshot['videoOverlayMode']+): Promise<void> {+ if (!isNativeIosCallKitEnabled()) return;+ await invoke('plugin:call-kit|set_video_overlay_mode', { mode }).catch(+ (err) =>+ console.error('[callkit] failed to set native video overlay mode', err)+ );+}++async function setNativeCallKitChannelTitle(+ channelTitle: string | null+): Promise<void> {+ if (!isNativeIosCallKitEnabled()) return;+ await invoke('plugin:call-kit|set_call_drawer_channel_title', {+ channelTitle,+ }).catch((err) =>+ console.error('[callkit] failed to set native channel title', err)+ );+}++async function setNativeCallKitParticipantDisplayName(+ identity: string,+ displayName: string | null+): Promise<void> {+ if (!isNativeIosCallKitEnabled()) return;+ await invoke('plugin:call-kit|set_participant_display_name', {+ identity,+ displayName,+ }).catch((err) =>+ console.error(+ '[callkit] failed to set native participant display name',+ err+ ));}diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 87bb5f6ac5..a874249506 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -375,7 +375,7 @@ export const ENABLE_AUTO_UPDATE_UI = resolveFeatureFlag(true);-export const ENABLE_CALLKIT = resolveFeatureFlag('ENABLE_CALLKIT', false);+export const ENABLE_CALLKIT = resolveFeatureFlag('ENABLE_CALLKIT', true);export const ENABLE_MARKDOWN_SIDE_PANEL = resolveFeatureFlag('ENABLE_MARKDOWN_SIDE_PANEL',diff --git a/js/app/packages/queries/auth/index.ts b/js/app/packages/queries/auth/index.tsindex f28bb4d0fe..69aa772879 100644--- a/js/app/packages/queries/auth/index.ts+++ b/js/app/packages/queries/auth/index.ts@@ -9,4 +9,9 @@ export { authKeys } from './keys';export { useSendMobileWelcomeEmail } from './mobile-welcome-email';export {} from './mutations';export type { UserInfoData } from './user-info';+export {+ normalizeUserNameQueryId,+ userNameQueryOptions,+ useUserNamesQuery,+} from './user-names';export { invalidateUserQuota } from './user-quota';diff --git a/js/app/packages/queries/auth/keys.ts b/js/app/packages/queries/auth/keys.tsindex b0d30c3f85..f2dabd3b3d 100644--- a/js/app/packages/queries/auth/keys.ts+++ b/js/app/packages/queries/auth/keys.ts@@ -2,5 +2,8 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';export const authKeys = createQueryKeys('auth', {userInfo: null,+ userName: (userId: string) => ({+ queryKey: [userId],+ }),userQuota: null,});diff --git a/js/app/packages/queries/auth/user-names.ts b/js/app/packages/queries/auth/user-names.tsnew file mode 100644index 0000000000..318320a2dd--- /dev/null+++ b/js/app/packages/queries/auth/user-names.ts@@ -0,0 +1,126 @@+import { throwOnErr } from '@core/util/result';+import { authServiceClient } from '@service-auth/client';+import type { UserName } from '@service-auth/generated/schemas/userName';+import { useQueries } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { authKeys } from './keys';++const USER_NAMES_STALE_TIME = 10 * 60 * 1000;+const MACRO_ID_PREFIX = 'macro|';++type UseUserNamesQueryOptions = {+ userIds: Accessor<readonly string[]>;+ enabled?: Accessor<boolean>;+};++type PendingUserNameRequest = {+ resolve: (userName: UserName | null) => void;+ reject: (error: unknown) => void;+};++let pendingUserNameRequests = new Map<string, PendingUserNameRequest[]>();+let pendingUserNameFlush: ReturnType<typeof setTimeout> | undefined;++export function normalizeUserNameQueryId(userId: string): string | null {+ const trimmed = userId.trim();+ return isMacroUserNameQueryId(trimmed) ? trimmed.toLowerCase() : null;+}++function uniqueUserNameQueryIds(userIds: readonly string[]): string[] {+ const seen = new Set<string>();+ const queryUserIds: string[] = [];++ for (const userId of userIds) {+ const queryUserId = normalizeUserNameQueryId(userId);+ if (!queryUserId || seen.has(queryUserId)) continue;+ seen.add(queryUserId);+ queryUserIds.push(queryUserId);+ }++ return queryUserIds;+}++function isMacroUserNameQueryId(userId: string): boolean {+ const trimmed = userId.trim().toLowerCase();+ return (+ trimmed.startsWith(MACRO_ID_PREFIX) &&+ trimmed.slice(MACRO_ID_PREFIX.length).includes('@')+ );+}++async function fetchUserNames(userIds: string[]): Promise<UserName[]> {+ if (userIds.length === 0) return [];++ const result = await throwOnErr(+ async () =>+ await authServiceClient.getUserNamesWithEmail({+ user_ids: userIds,+ })+ );++ return result.names;+}++function flushPendingUserNameRequests() {+ const requestsById = pendingUserNameRequests;+ pendingUserNameRequests = new Map();+ pendingUserNameFlush = undefined;++ const userIds = Array.from(requestsById.keys());+ fetchUserNames(userIds)+ .then((names) => {+ const namesById = new Map<string, UserName>();+ for (const name of names) {+ const normalizedId = normalizeUserNameQueryId(name.id);+ if (normalizedId) namesById.set(normalizedId, name);+ }++ for (const [userId, requests] of requestsById) {+ const userName = namesById.get(userId) ?? null;+ for (const request of requests) request.resolve(userName);+ }+ })+ .catch((error) => {+ for (const requests of requestsById.values()) {+ for (const request of requests) request.reject(error);+ }+ });+}++async function fetchUserName(userId: string): Promise<UserName | null> {+ return new Promise((resolve, reject) => {+ const requests = pendingUserNameRequests.get(userId) ?? [];+ requests.push({ resolve, reject });+ pendingUserNameRequests.set(userId, requests);++ if (pendingUserNameFlush) return;+ pendingUserNameFlush = setTimeout(flushPendingUserNameRequests, 0);+ });+}++export function userNameQueryOptions(userId: string) {+ const queryUserId = normalizeUserNameQueryId(userId);+ return {+ queryKey: authKeys.userName(queryUserId ?? '').queryKey,+ queryFn: () =>+ queryUserId ? fetchUserName(queryUserId) : Promise.resolve(null),+ enabled: Boolean(queryUserId),+ throwOnError: false,+ staleTime: USER_NAMES_STALE_TIME,+ };+}++export function useUserNamesQuery(options: UseUserNamesQueryOptions) {+ return useQueries(() => {+ const enabled = options.enabled?.() ?? true;+ return {+ queries: uniqueUserNameQueryIds(options.userIds()).map((userId) => {+ const queryOptions = userNameQueryOptions(userId);+ return {+ ...queryOptions,+ enabled: enabled && queryOptions.enabled,+ };+ }),+ };+ });+}diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsxindex 54f295193d..1e5bd0c6d5 100644--- a/js/app/packages/tauri/src/TauriProvider.tsx+++ b/js/app/packages/tauri/src/TauriProvider.tsx@@ -1,4 +1,4 @@-import { useCallKitSetup } from '@channel/Call';+import { NativeCallProvider, useCallKitSetup } from '@channel/Call';import { NativeAppUpdateRequiredDialog } from '@core/mobile/NativeAppUpdateRequiredDialog';import { isPlatform, isTauri } from '@core/util/platform';import { PlatformNotificationProvider } from '@notifications';@@ -171,11 +171,13 @@ function TauriProvider(props: { children: JSX.Element }) {export function MaybeTauriProvider(props: { children: JSX.Element }) {if (isTauri()) {return (- <TauriProvider>- <MaybePushNotificationRegistration>- {props.children}- </MaybePushNotificationRegistration>- </TauriProvider>+ <NativeCallProvider>+ <TauriProvider>+ <MaybePushNotificationRegistration>+ {props.children}+ </MaybePushNotificationRegistration>+ </TauriProvider>+ </NativeCallProvider>);}diff --git a/js/app/tauri/callkit_plugin/build.rs b/js/app/tauri/callkit_plugin/build.rsindex 8f641be29f..559f77089d 100644--- a/js/app/tauri/callkit_plugin/build.rs+++ b/js/app/tauri/callkit_plugin/build.rs@@ -1,6 +1,188 @@+use std::{+ env, fs,+ path::{Path, PathBuf},+};++const COMMANDS: &[&str] = &[+ "get_voip_token",+ "end_active_call",+ "get_pending_answered_call",+ "watch_call_answered",+ "watch_call_ended",+ "watch_connection_state",+ "watch_drawer_opened",+ "watch_participant_identities",+ "get_active_call_state",+ "start_outgoing_call",+ "set_video_enabled",+ "set_video_overlay_mode",+ "set_call_drawer_channel_title",+ "set_call_drawer_theme",+ "set_participant_display_name",+ "switch_camera",+];++struct BuildEnv {+ target_os: String,+ manifest_dir: PathBuf,+ tauri_ios_library_path: Option<PathBuf>,+ out_dir: Option<PathBuf>,+}++impl BuildEnv {+ fn from_env() -> Self {+ Self {+ target_os: env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(),+ manifest_dir: PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()),+ tauri_ios_library_path: env::var("DEP_TAURI_IOS_LIBRARY_PATH")+ .ok()+ .map(PathBuf::from),+ out_dir: env::var_os("OUT_DIR").map(PathBuf::from),+ }+ }++ fn is_ios_target(&self) -> bool {+ self.target_os == "ios"+ }++ fn tauri_ios_library_path(&self) -> &Path {+ self.tauri_ios_library_path+ .as_deref()+ .expect("missing DEP_TAURI_IOS_LIBRARY_PATH; make sure tauri is a plugin dependency")+ }+}+fn main() {- tauri_plugin::Builder::new(&["get_voip_token", "end_active_call"])- .ios_path("ios")- .try_build()- .unwrap();+ tauri_plugin::Builder::new(COMMANDS).try_build().unwrap();++ let build_env = BuildEnv::from_env();+ if build_env.is_ios_target() {+ prepare_ios_swift_package(&build_env);+ }+}++fn prepare_ios_swift_package(build_env: &BuildEnv) {+ let manifest_dir = &build_env.manifest_dir;+ let ios_dir = manifest_dir.join("ios");+ let tauri_library_path = build_env.tauri_ios_library_path();++ // Tauri's Swift package is exposed to plugin build scripts as an unpacked+ // dependency path, but SwiftPM needs it available from the plugin package's+ // local `../.tauri/tauri-api` path. Keep this as a copy so the plugin's+ // Package.swift can use the same layout Tauri's generated Xcode project+ // expects.+ let tauri_api_dir = manifest_dir.join(".tauri").join("tauri-api");+ let _ = fs::remove_dir_all(&tauri_api_dir);+ copy_dir_filtered(+ tauri_library_path,+ &tauri_api_dir,+ &[".build", "Package.resolved", "Tests"],+ build_env,+ );++ // Xcode links the final iOS app. Keep LiveKit and this plugin in Xcode's+ // SwiftPM graph so package resolution, binary-framework slice selection,+ // embedding, signing, and Swift runtime linkage all happen in one build+ // system. Cargo only prepares the local Tauri API dependency above.+ emit_ios_source_rerun_inputs(&ios_dir);+}++fn emit_ios_source_rerun_inputs(ios_dir: &Path) {+ emit_rerun_if_changed(&ios_dir.join("Package.swift"));+ let sources_dir = ios_dir.join("Sources");+ emit_rerun_if_changed(&sources_dir);+ emit_dir_rerun_inputs(&sources_dir);+}++fn emit_dir_rerun_inputs(dir: &Path) {+ if !dir.exists() {+ return;+ }++ for entry in fs::read_dir(dir).unwrap_or_else(|e| {+ panic!("failed to read {}: {e}", dir.display());+ }) {+ let entry = entry.unwrap();+ let path = entry.path();+ if path.is_dir() {+ emit_dir_rerun_inputs(&path);+ } else {+ emit_rerun_if_changed(&path);+ }+ }+}++fn emit_rerun_if_changed(path: &Path) {+ println!("cargo:rerun-if-changed={}", path.display());+}++fn copy_dir_filtered(source: &Path, target: &Path, ignore_paths: &[&str], build_env: &BuildEnv) {+ copy_dir_filtered_inner(source, target, ignore_paths, build_env, true);+}++fn copy_dir_filtered_inner(+ source: &Path,+ target: &Path,+ ignore_paths: &[&str],+ build_env: &BuildEnv,+ emit_rerun: bool,+) {+ fs::create_dir_all(target).unwrap_or_else(|e| {+ panic!("failed to create {}: {e}", target.display());+ });++ for entry in fs::read_dir(source).unwrap_or_else(|e| {+ panic!("failed to read {}: {e}", source.display());+ }) {+ let entry = entry.unwrap();+ let source_path = entry.path();+ let rel_path = source_path.strip_prefix(source).unwrap();+ let rel_path_str = rel_path.to_string_lossy();+ if ignore_paths+ .iter()+ .any(|ignore| rel_path_str.starts_with(ignore))+ {+ continue;+ }++ let target_path = target.join(rel_path);+ if source_path.is_dir() {+ copy_dir_filtered_inner(+ &source_path,+ &target_path,+ ignore_paths,+ build_env,+ emit_rerun,+ );+ } else {+ if let Some(parent) = target_path.parent() {+ fs::create_dir_all(parent).unwrap();+ }+ fs::copy(&source_path, &target_path).unwrap_or_else(|e| {+ panic!(+ "failed to copy {} to {}: {e}",+ source_path.display(),+ target_path.display()+ )+ });+ if emit_rerun && should_emit_rerun_for_source(&source_path, build_env) {+ emit_rerun_if_changed(&source_path);+ }+ }+ }+}++fn should_emit_rerun_for_source(source_path: &Path, build_env: &BuildEnv) -> bool {+ if build_env+ .out_dir+ .as_deref()+ .is_some_and(|out_dir| source_path.starts_with(out_dir))+ {+ return false;+ }++ !source_path.components().any(|component| {+ let name = component.as_os_str();+ name == ".build" || name == ".tauri"+ })}diff --git a/js/app/tauri/callkit_plugin/ios/Package.swift b/js/app/tauri/callkit_plugin/ios/Package.swiftindex 437e9836ca..a1df6a06d1 100644--- a/js/app/tauri/callkit_plugin/ios/Package.swift+++ b/js/app/tauri/callkit_plugin/ios/Package.swift@@ -1,10 +1,10 @@-// swift-tools-version:5.3+// swift-tools-version:5.9import PackageDescriptionlet package = Package(name: "tauri-plugin-call-kit",platforms: [- .macOS(.v10_13),+ .macOS(.v11),.iOS(.v14),],products: [@@ -15,13 +15,17 @@ let package = Package()],dependencies: [- .package(name: "Tauri", path: "../.tauri/tauri-api")+ .package(name: "Tauri", path: "../.tauri/tauri-api"),+ .package(url: "https://github.com/livekit/client-sdk-swift.git", exact: "2.13.0"),+ .package(url: "https://github.com/livekit/webrtc-xcframework.git", exact: "144.7559.03"),],targets: [.target(name: "tauri-plugin-call-kit",dependencies: [- .byName(name: "Tauri")+ .byName(name: "Tauri"),+ .product(name: "LiveKit", package: "client-sdk-swift"),+ .product(name: "LiveKitWebRTC", package: "webrtc-xcframework"),],path: "Sources")diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swiftnew file mode 100644index 0000000000..ea2f082952--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallAudioRouteController.swift@@ -0,0 +1,338 @@+import AVFAudio+import Foundation++enum CallAudioOutputRoute: String {+ case receiver+ case speaker+ case bluetooth+ case headphones+ case unknown+}++enum CallAudioInputRoute: String {+ case builtInMic+ case bluetooth+ case wired+ case unknown+}++struct CallAudioRouteSnapshot {+ let input: CallAudioInputRoute+ let output: CallAudioOutputRoute+ let isSpeakerForced: Bool+ let supportsSpeakerToggle: Bool+}++final class CallAudioRouteController: NSObject, @unchecked Sendable {+ var onRouteChanged: ((CallAudioRouteSnapshot) -> Void)? {+ get {+ onMainSync { routeChangedHandler }+ }+ set {+ let handler = newValue+ onMain { [weak self] in+ self?.routeChangedHandler = handler+ }+ }+ }++ private var routeChangedHandler: ((CallAudioRouteSnapshot) -> Void)?+ private var isObserving = false+ private var isSpeakerForced = false+ private var preferredBuiltInSpeakerEnabled: Bool?++ override init() {+ super.init()+ }++ deinit {+ NotificationCenter.default.removeObserver(self)+ }++ func startObserving() {+ onMain { [weak self] in+ self?.startObservingOnMain()+ }+ }++ private func startObservingOnMain() {+ guard !isObserving else { return }+ isObserving = true+ NotificationCenter.default.addObserver(+ self,+ selector: #selector(handleRouteChange(_:)),+ name: AVAudioSession.routeChangeNotification,+ object: AVAudioSession.sharedInstance()+ )+ print("[CallKit] Audio route observing started \(describeCurrentRoute())")+ emitCurrentRoute()+ }++ func stopObserving() {+ onMain { [weak self] in+ self?.stopObservingOnMain()+ }+ }++ private func stopObservingOnMain() {+ guard isObserving else { return }+ isObserving = false+ NotificationCenter.default.removeObserver(+ self,+ name: AVAudioSession.routeChangeNotification,+ object: AVAudioSession.sharedInstance()+ )+ }++ func setSpeakerEnabled(_ enabled: Bool) {+ onMain { [weak self] in+ self?.setSpeakerEnabledOnMain(enabled, isUserSelection: true)+ }+ }++ func prepareForCall() {+ onMain { [weak self] in+ self?.preferredBuiltInSpeakerEnabled = nil+ self?.isSpeakerForced = false+ self?.emitCurrentRouteOnMain()+ }+ }++ func defaultToSpeakerIfBuiltInRoute(reason: String) {+ onMain { [weak self] in+ self?.defaultToSpeakerIfBuiltInRouteOnMain(reason: reason)+ }+ }++ private func defaultToSpeakerIfBuiltInRouteOnMain(reason: String) {+ guard preferredBuiltInSpeakerEnabled != false else { return }+ guard !isExternalRouteAvailable() else {+ print("[CallKit] Skipping built-in speaker default because external route is available reason=\(reason) available=\(describeAvailableRoutes()) current=\(describeCurrentRoute())")+ return+ }+ let snapshot = currentSnapshotOnMain()+ guard snapshot.supportsSpeakerToggle, snapshot.output != .speaker else { return }+ print("[CallKit] Defaulting built-in audio route to speaker reason=\(reason) output=\(snapshot.output.rawValue)")+ setSpeakerEnabledOnMain(true, isUserSelection: false)+ }++ private func setSpeakerEnabledOnMain(_ enabled: Bool, isUserSelection: Bool) {+ let session = AVAudioSession.sharedInstance()+ let snapshot = currentSnapshotOnMain()+ if snapshot.output == .unknown {+ if isUserSelection {+ preferredBuiltInSpeakerEnabled = enabled+ }+ isSpeakerForced = enabled+ print("[CallKit] Queued audio route speaker preference enabled=\(enabled) userSelection=\(isUserSelection); current route is not ready \(describeCurrentRoute())")+ emitCurrentRouteOnMain()+ return+ }++ do {+ try session.overrideOutputAudioPort(enabled ? .speaker : .none)+ isSpeakerForced = enabled+ if isUserSelection {+ preferredBuiltInSpeakerEnabled = enabled+ }+ print("[CallKit] Audio route speaker override enabled=\(enabled) userSelection=\(isUserSelection) \(describeCurrentRoute())")+ print("[CallKit] Audio route available after speaker override \(describeAvailableRoutes())")+ emitCurrentRouteOnMain()+ } catch {+ print("[CallKit] Failed to set audio route speaker override enabled=\(enabled): \(error) \(describeCurrentRoute())")+ }+ }++ func resetSpeakerOverride() {+ onMain { [weak self] in+ self?.resetSpeakerOverrideOnMain()+ }+ }++ private func resetSpeakerOverrideOnMain() {+ preferredBuiltInSpeakerEnabled = nil+ guard isSpeakerForced else { return }+ setSpeakerEnabledOnMain(false, isUserSelection: false)+ }++ func emitCurrentRoute() {+ onMain { [weak self] in+ self?.emitCurrentRouteOnMain()+ }+ }++ 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())")+ routeChangedHandler?(snapshot)+ }++ func currentRouteSnapshot() -> CallAudioRouteSnapshot {+ onMainSync { currentSnapshotOnMain() }+ }++ func describeCurrentRoute() -> String {+ onMainSync { describeRoute(AVAudioSession.sharedInstance().currentRoute) }+ }++ private func currentSnapshotOnMain() -> CallAudioRouteSnapshot {+ let route = AVAudioSession.sharedInstance().currentRoute+ let output = classifyOutput(route.outputs.first)+ let supportsSpeakerToggle = output == .receiver || output == .speaker || (output == .unknown && !isExternalRouteAvailable())+ let snapshotSpeakerForced = isSpeakerForced+ && supportsSpeakerToggle+ && (output == .speaker || output == .unknown)++ return CallAudioRouteSnapshot(+ input: classifyInput(route.inputs.first),+ output: output,+ isSpeakerForced: snapshotSpeakerForced,+ supportsSpeakerToggle: supportsSpeakerToggle+ )+ }++ @objc private func handleRouteChange(_ notification: Notification) {+ onMain { [weak self] in+ self?.handleRouteChangeOnMain(notification)+ }+ }++ 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())")++ if shouldReleaseSpeakerOverrideForExternalRoute(reason: reason) {+ print("[CallKit] Releasing speaker override for external audio route reason=\(reason)")+ setSpeakerEnabledOnMain(false, isUserSelection: false)+ return+ }++ if shouldDefaultToSpeakerAfterRouteChange(reason: reason) {+ defaultToSpeakerIfBuiltInRouteOnMain(reason: "routeChange:\(reason)")+ return+ }+ emitCurrentRouteOnMain()+ }++ private func shouldDefaultToSpeakerAfterRouteChange(reason: String) -> Bool {+ guard preferredBuiltInSpeakerEnabled != false else { return false }+ guard !isExternalRouteAvailable() else { return false }+ let snapshot = currentSnapshotOnMain()+ guard snapshot.supportsSpeakerToggle, snapshot.output != .unknown else { return false }+ return reason != "override"+ }++ private func shouldReleaseSpeakerOverrideForExternalRoute(reason: String) -> Bool {+ guard isSpeakerForced, reason != "override" else { return false }+ if preferredBuiltInSpeakerEnabled == true, !isExternalRouteAvailable() {+ return false+ }+ let output = currentSnapshotOnMain().output+ if output != .speaker && output != .unknown {+ return true+ }+ return isExternalRouteAvailable()+ }++ private func isExternalRouteAvailable() -> Bool {+ let inputs = AVAudioSession.sharedInstance().availableInputs ?? []+ return inputs.contains { port in+ isExternalInput(port)+ }+ }++ private func isExternalInput(_ port: AVAudioSessionPortDescription) -> Bool {+ port.portType == .bluetoothHFP+ || port.portType == .bluetoothLE+ || port.portType == .headsetMic+ }++ private func describeAvailableRoutes() -> String {+ let inputs = (AVAudioSession.sharedInstance().availableInputs ?? [])+ .map(describePort)+ .joined(separator: ",")+ return "availableInputs=[\(inputs)]"+ }++ private func describePolicyState() -> String {+ "speakerForced=\(isSpeakerForced) preferredBuiltInSpeaker=\(preferredBuiltInSpeakerEnabled.map(String.init) ?? "nil") externalAvailable=\(isExternalRouteAvailable())"+ }++ private func classifyInput(_ port: AVAudioSessionPortDescription?) -> CallAudioInputRoute {+ guard let port else { return .unknown }+ switch port.portType {+ case .builtInMic:+ return .builtInMic+ case .bluetoothHFP, .bluetoothLE:+ return .bluetooth+ case .headsetMic:+ return .wired+ default:+ return .unknown+ }+ }++ private func routeChangeReason(from notification: Notification) -> String {+ guard+ let rawReason = notification.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt,+ let reason = AVAudioSession.RouteChangeReason(rawValue: rawReason)+ else {+ return "unknown"+ }++ switch reason {+ case .unknown: return "unknown"+ case .newDeviceAvailable: return "newDeviceAvailable"+ case .oldDeviceUnavailable: return "oldDeviceUnavailable"+ case .categoryChange: return "categoryChange"+ case .override: return "override"+ case .wakeFromSleep: return "wakeFromSleep"+ case .noSuitableRouteForCategory: return "noSuitableRouteForCategory"+ case .routeConfigurationChange: return "routeConfigurationChange"+ @unknown default: return "unknown"+ }+ }++ private func classifyOutput(_ port: AVAudioSessionPortDescription?) -> CallAudioOutputRoute {+ guard let port else { return .unknown }+ switch port.portType {+ case .builtInReceiver:+ return .receiver+ case .builtInSpeaker:+ return .speaker+ case .bluetoothHFP, .bluetoothA2DP, .bluetoothLE:+ return .bluetooth+ case .headphones:+ return .headphones+ default:+ return .unknown+ }+ }++ private func describeRoute(_ route: AVAudioSessionRouteDescription) -> String {+ let inputs = route.inputs.map(describePort).joined(separator: ",")+ let outputs = route.outputs.map(describePort).joined(separator: ",")+ return "inputs=[\(inputs)] outputs=[\(outputs)]"+ }++ private func describePort(_ port: AVAudioSessionPortDescription) -> String {+ "\(port.portType.rawValue):\(port.portName):uid=\(port.uid)"+ }++ private func onMain(_ block: @escaping () -> Void) {+ if Thread.isMainThread {+ block()+ } else {+ DispatchQueue.main.async(execute: block)+ }+ }++ private func onMainSync<T>(_ block: () -> T) -> T {+ if Thread.isMainThread {+ return block()+ }+ return DispatchQueue.main.sync(execute: block)+ }+}diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallKitModels.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallKitModels.swiftnew file mode 100644index 0000000000..6f2d72b167--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallKitModels.swift@@ -0,0 +1,55 @@+import Foundation++struct PendingCallToken {+ let serverUrl: String+ let token: String+}++struct PendingCallInfo {+ let channelId: String+ let channelName: String?+ let callerName: String?+}++struct ActiveCallSnapshot {+ let channelId: String+ let callId: String+ var connectionState: String+ var isAudioMuted: Bool+ var isVideoMuted: Bool+ var videoOverlayMode: String+}++struct SetParticipantDisplayNameArgs: Decodable {+ let identity: String+ let displayName: String?+}++struct RgbaColorArgs: Decodable {+ let red: Double+ let green: Double+ let blue: Double+ let alpha: Double?+}++struct SetCallDrawerThemeArgs: Decodable {+ let drawerBackground: RgbaColorArgs+ let text: RgbaColorArgs+ let messageBackground: RgbaColorArgs+ let overlayBackground: RgbaColorArgs+ let edgeMuted: RgbaColorArgs+ let edge: RgbaColorArgs+ let inkMuted: RgbaColorArgs+ let failure: RgbaColorArgs+ let failureInk: RgbaColorArgs+ let success: RgbaColorArgs+}++struct StartOutgoingCallArgs: Decodable {+ let channelId: String+ let callId: String+ let channelTitle: String?+ let callerName: String?+ let serverUrl: String+ let token: String+}diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swiftindex bf5064b27f..09f45b5099 100644--- a/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift@@ -1,155 +1,460 @@-import CallKit-import PushKit+import Foundationimport Tauri+import UIKitimport WebKit-class CallKitPlugin: Plugin, CXProviderDelegate, PKPushRegistryDelegate {- private var provider: CXProvider!- private let callController = CXCallController()- private var registry: PKPushRegistry!+struct WatchCallAnsweredArgs: Decodable {+ let channel: Channel+}++struct WatchCallEndedArgs: Decodable {+ let channel: Channel+}++struct WatchConnectionStateArgs: Decodable {+ let channel: Channel+}++struct WatchDrawerOpenedArgs: Decodable {+ let channel: Channel+}++struct WatchParticipantIdentitiesArgs: Decodable {+ let channel: Channel+}++struct SetVideoEnabledArgs: Decodable {+ let enabled: Bool+}++struct SetVideoOverlayModeArgs: Decodable {+ let mode: String+}- // Keyed by call UUID — holds the channelId so it's available when CXAnswerCallAction fires.- private var pendingCalls: [UUID: String] = [:]+struct SetCallDrawerChannelTitleArgs: Decodable {+ let channelTitle: String?+}++/// Tauri command/event facade; platform work lives in the coordinator/session.+class CallKitPlugin: Plugin, @unchecked Sendable {+ private var mediaSession: NativeLiveKitCallSession?+ private var callCoordinator: IncomingCallCoordinator!+ private let videoOverlay = CallVideoOverlayController()+ private var pendingParticipantDisplayNamesByIdentity: [String: String] = [:]- // The UUID of the most recently reported incoming call, used by endActiveCall.- private var activeCallUUID: UUID?+ // Singleton channels avoid leaking listeners across webview reloads/HMR.+ private var callAnsweredChannel: Channel?+ private var callEndedChannel: Channel?+ private var connectionStateChannel: Channel?+ private var drawerOpenedChannel: Channel?+ private var participantIdentitiesChannel: Channel?+ private var willTerminateObserver: NSObjectProtocol?- // Last VoIP token received from PushKit; may arrive before the JS listener is ready.- private var cachedVoipToken: String?+ deinit {+ if let willTerminateObserver {+ NotificationCenter.default.removeObserver(willTerminateObserver)+ }+ }override public func load(webview: WKWebView) {- let config = CXProviderConfiguration()- config.supportsVideo = false- config.maximumCallsPerCallGroup = 1- config.supportedHandleTypes = [.generic]- provider = CXProvider(configuration: config)- provider.setDelegate(self, queue: .main)-- registry = PKPushRegistry(queue: .main)- registry.delegate = self- registry.desiredPushTypes = [.voIP]- }-- // MARK: - PKPushRegistryDelegate-- public func pushRegistry(- _ registry: PKPushRegistry,- didUpdate pushCredentials: PKPushCredentials,- for type: PKPushType- ) {- guard type == .voIP else { return }- let token = pushCredentials.token.map { String(format: "%02.2hhx", $0) }.joined()- cachedVoipToken = token- trigger("voip-token-updated", data: ["token": token])- }-- public func pushRegistry(- _ registry: PKPushRegistry,- didReceiveIncomingPushWith payload: PKPushPayload,- for type: PKPushType,- completion: @escaping () -> Void- ) {- guard type == .voIP else { completion(); return }-- let dict = payload.dictionaryPayload- let channelId = dict["channelId"] as? String ?? ""- let callerName = dict["callerName"] as? String ?? "Incoming Call"- let callIdString = dict["callId"] as? String ?? ""- guard let uuid = UUID(uuidString: callIdString) else {- // iOS terminates apps that skip reportNewIncomingCall inside this- // delegate. Report a ghost call and immediately end it as failed so- // the system requirement is satisfied while surfacing the server bug.- print("[CallKit] Invalid callId '\(callIdString)' in VoIP payload: \(dict)")- let fallbackUUID = UUID()- provider.reportNewIncomingCall(with: fallbackUUID, update: CXCallUpdate()) { [weak self] _ in- self?.provider.reportCall(with: fallbackUUID, endedAt: nil, reason: .failed)- completion()+ print("[CallKit] Tauri CallKitPlugin loading")+ callCoordinator = IncomingCallCoordinator(+ mediaSession: { [weak self] in+ guard let self else {+ print("[CallKit] Media session requested after plugin deallocation; returning inert session")+ return NativeLiveKitCallSession(+ onSnapshotChanged: { _ in },+ requestSystemEndCall: { _ in },+ onDrawerOpened: { _ in },+ onParticipantIdentitiesChanged: { _ in },+ videoOverlay: CallVideoOverlayController()+ )+ }+ return self.getMediaSession()+ },+ onVoipTokenUpdated: { [weak self] token in+ print("[CallKit] 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)")+ self?.trigger("call-answered", data: eventPayload)+ if let channel = self?.callAnsweredChannel {+ let channelPayload: JsonObject = ["channelId": channelId, "nativeMedia": nativeMedia]+ channel.send(channelPayload)+ }+ },+ onCallEnded: { [weak self] callId in+ let eventPayload: JSObject = ["callId": callId]+ print("[CallKit] Triggering call ended event callId=\(callId)")+ self?.trigger("call-ended", data: eventPayload)+ if let channel = self?.callEndedChannel {+ let channelPayload: JsonObject = ["callId": callId]+ channel.send(channelPayload)+ }}- return+ )+ videoOverlay.attach(to: webview)+ callCoordinator.load()+ observeApplicationTermination()+ print("[CallKit] Tauri CallKitPlugin loaded")+ }++ private func observeApplicationTermination() {+ if let willTerminateObserver {+ NotificationCenter.default.removeObserver(willTerminateObserver)}+ willTerminateObserver = NotificationCenter.default.addObserver(+ forName: UIApplication.willTerminateNotification,+ object: nil,+ queue: .main+ ) { [weak self] _ in+ print("[CallKit] UIApplication will terminate")+ self?.callCoordinator.handleApplicationWillTerminate()+ }+ }- // Enforce the single-call invariant: if a stale entry exists (duplicate- // delivery or network retry), evict it before reporting the new call.- for staleUUID in pendingCalls.keys where staleUUID != uuid {- provider.reportCall(with: staleUUID, endedAt: nil, reason: .failed)- pendingCalls.removeValue(forKey: staleUUID)+ @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")+ self?.callAnsweredChannel = args.channel+ invoke.resolve()}+ }- pendingCalls[uuid] = channelId- activeCallUUID = uuid+ @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")+ self?.callEndedChannel = args.channel+ invoke.resolve()+ }+ }- let update = CXCallUpdate()- update.remoteHandle = CXHandle(type: .generic, value: channelId)- update.localizedCallerName = callerName- update.hasVideo = false+ @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")+ self?.connectionStateChannel = args.channel+ invoke.resolve()+ }+ }- // iOS 13+: must call reportNewIncomingCall synchronously within this delegate.- // If we don't, iOS will terminate the app.- provider.reportNewIncomingCall(with: uuid, update: update) { [weak self] error in- if error != nil {- // CallKit refused (e.g. Do Not Disturb, max calls reached).- // Still must complete the PushKit handler.- self?.pendingCalls.removeValue(forKey: uuid)- if self?.activeCallUUID == uuid { self?.activeCallUUID = nil }+ @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")+ self?.drawerOpenedChannel = args.channel+ invoke.resolve()+ }+ }++ @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")+ self?.participantIdentitiesChannel = args.channel+ invoke.resolve()+ }+ }++ @objc public func getVoipToken(_ invoke: Invoke) {+ onMain { [weak self] in+ print("[CallKit] JS requested cached VoIP token")+ invoke.resolve(["token": self?.callCoordinator.getVoipToken() as Any])+ }+ }++ @objc public func getPendingAnsweredCall(_ invoke: Invoke) {+ onMain { [weak self] in+ let answeredCall = self?.callCoordinator.drainPendingAnsweredCall()+ print("[CallKit] JS drained pending answered call channelId=\(answeredCall?.channelId ?? "nil") nativeMedia=\(answeredCall?.nativeMedia ?? false)")+ invoke.resolve([+ "channelId": answeredCall?.channelId as Any,+ "nativeMedia": answeredCall?.nativeMedia as Any,+ ])+ }+ }++ @objc public func getActiveCallState(_ invoke: Invoke) {+ onMain { [weak self] in+ guard let snapshot = self?.mediaSession?.currentSnapshot() else {+ print("[CallKit] JS requested active call state: none")+ invoke.resolve(["state": NSNull()])+ return}- completion()++ print("[CallKit] JS requested active call state: \(snapshot.connectionState) channelId=\(snapshot.channelId) callId=\(snapshot.callId)")+ let participantIdentities = self?.mediaSession?.currentParticipantIdentities() ?? []+ invoke.resolve([+ "state": [+ "channelId": snapshot.channelId,+ "callId": snapshot.callId,+ "connectionState": snapshot.connectionState,+ "isAudioMuted": snapshot.isAudioMuted,+ "isVideoMuted": snapshot.isVideoMuted,+ "videoOverlayMode": snapshot.videoOverlayMode,+ "participantIdentities": participantIdentities,+ ] as JsonObject+ ])}}- // MARK: - CXProviderDelegate+ @objc public func endActiveCall(_ invoke: Invoke) {+ onMain { [weak self] in+ guard let self else {+ print("[CallKit] JS requested endActiveCall after plugin deallocation")+ invoke.resolve()+ return+ }+ print("[CallKit] JS requested endActiveCall")+ self.callCoordinator.endActiveCall {+ invoke.resolve()+ }+ }+ }- public func providerDidReset(_ provider: CXProvider) {- pendingCalls.removeAll()- activeCallUUID = nil+ @objc public func startOutgoingCall(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(StartOutgoingCallArgs.self)+ onMain { [weak self] in+ guard let self else {+ print("[CallKit] 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)")+ invoke.reject("Invalid callId")+ return+ }++ print("[CallKit] JS requested startOutgoingCall uuid=\(uuid.uuidString) channelId=\(args.channelId)")+ self.callCoordinator.startOutgoingCall(+ uuid: uuid,+ channelId: args.channelId,+ channelName: args.channelTitle,+ callerName: args.callerName,+ serverUrl: args.serverUrl,+ token: args.token+ ) { error in+ if let error {+ invoke.reject(error.localizedDescription)+ } else {+ invoke.resolve(["uuid": uuid.uuidString])+ }+ }+ }}- public func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {- guard let channelId = pendingCalls[action.callUUID] else {- action.fail()- return+ @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)")+ self?.mediaSession?.setVideoEnabled(args.enabled)+ invoke.resolve()}- trigger("call-answered", data: [- "channelId": channelId,- ])- action.fulfill()- pendingCalls.removeValue(forKey: action.callUUID)}- public func provider(_ provider: CXProvider, perform action: CXEndCallAction) {- trigger("call-ended", data: [- "callId": action.callUUID.uuidString,- ])- action.fulfill()- pendingCalls.removeValue(forKey: action.callUUID)- if activeCallUUID == action.callUUID { activeCallUUID = nil }+ @objc public func setVideoOverlayMode(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(SetVideoOverlayModeArgs.self)+ onMain { [weak self] in+ let mode = CallVideoOverlayMode(rawValue: args.mode) ?? .minimized+ print("[CallKit] JS requested native video overlay mode=\(mode.rawValue)")+ self?.mediaSession?.setVideoOverlayMode(mode)+ invoke.resolve()+ }}- // MARK: - Tauri commands+ @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")")+ self?.videoOverlay.setChannelTitle(args.channelTitle)+ invoke.resolve()+ }+ }- /// Returns the last VoIP token received from PushKit, or null if none has- /// arrived yet. JS calls this once at startup after registering the- /// voip-token-updated listener to drain any token that arrived before the- /// listener was ready.- @objc public func getVoipToken(_ invoke: Invoke) {- invoke.resolve(["token": cachedVoipToken as Any])+ @objc public func setCallDrawerTheme(_ invoke: Invoke) throws {+ let args = try invoke.parseArgs(SetCallDrawerThemeArgs.self)+ onMain { [weak self] in+ let theme = CallVideoOverlayTheme(+ drawerBackgroundColor: Self.uiColor(args.drawerBackground),+ textColor: Self.uiColor(args.text),+ messageBackgroundColor: Self.uiColor(args.messageBackground),+ overlayBackgroundColor: Self.uiColor(args.overlayBackground),+ edgeMutedColor: Self.uiColor(args.edgeMuted),+ edgeColor: Self.uiColor(args.edge),+ inkMutedColor: Self.uiColor(args.inkMuted),+ failureColor: Self.uiColor(args.failure),+ failureInkColor: Self.uiColor(args.failureInk),+ successColor: Self.uiColor(args.success)+ )+ self?.videoOverlay.setTheme(theme)+ invoke.resolve()+ }}- /// Called by the JS layer when the user leaves a call from within the app,- /// so the system CallKit UI is dismissed.- @objc public func endActiveCall(_ invoke: Invoke) {- guard let uuid = activeCallUUID else {+ @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")")+ self?.setParticipantDisplayName(+ identity: args.identity,+ displayName: args.displayName+ )invoke.resolve()- return}- let transaction = CXTransaction(action: CXEndCallAction(call: uuid))- callController.request(transaction) { [weak self] error in- if error == nil {- self?.pendingCalls.removeValue(forKey: uuid)- self?.activeCallUUID = nil- }+ }++ @objc public func switchCamera(_ invoke: Invoke) {+ onMain { [weak self] in+ print("[CallKit] JS requested native camera switch")+ self?.mediaSession?.switchCamera()invoke.resolve()}}++ private func emitConnectionState(_ snapshot: ActiveCallSnapshot?) {+ let eventPayload: JSObject+ let channelPayload: JsonObject+ if let snapshot {+ print("[CallKit] 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)+ }+ eventPayload = [+ "state": snapshot.connectionState,+ "channelId": snapshot.channelId,+ "callId": snapshot.callId,+ "isAudioMuted": snapshot.isAudioMuted,+ "isVideoMuted": snapshot.isVideoMuted,+ "videoOverlayMode": snapshot.videoOverlayMode,+ ]+ channelPayload = [+ "state": snapshot.connectionState,+ "channelId": snapshot.channelId,+ "callId": snapshot.callId,+ "isAudioMuted": snapshot.isAudioMuted,+ "isVideoMuted": snapshot.isVideoMuted,+ "videoOverlayMode": snapshot.videoOverlayMode,+ ]+ } else {+ print("[CallKit] Sending connection state channel message state=disconnected")+ eventPayload = [+ "state": "disconnected",+ "channelId": NSNull(),+ "callId": NSNull(),+ "isAudioMuted": false,+ "isVideoMuted": true,+ "videoOverlayMode": "hidden",+ ]+ channelPayload = [+ "state": "disconnected",+ "channelId": NSNull(),+ "callId": NSNull(),+ "isAudioMuted": false,+ "isVideoMuted": true,+ "videoOverlayMode": "hidden",+ ]+ }+ trigger("connection-state", data: eventPayload)+ if let channel = connectionStateChannel {+ channel.send(channelPayload)+ }+ }++ private func emitDrawerOpened(channelId: String) {+ let eventPayload: JSObject = ["channelId": channelId]+ print("[CallKit] Triggering drawer opened event channelId=\(channelId)")+ trigger("drawer-opened", data: eventPayload)+ if let channel = drawerOpenedChannel {+ let channelPayload: JsonObject = ["channelId": channelId]+ channel.send(channelPayload)+ }+ }++ private func emitParticipantIdentities(_ identities: [String]) {+ let eventPayload: JSObject = ["identities": identities]+ print("[CallKit] Triggering participant identities event identities=\(identities)")+ trigger("participant-identities", data: eventPayload)+ if let channel = participantIdentitiesChannel {+ let channelPayload: JsonObject = ["identities": identities]+ channel.send(channelPayload)+ }+ }++ private func getMediaSession() -> NativeLiveKitCallSession {+ if let mediaSession {+ print("[CallKit] Reusing NativeLiveKitCallSession")+ return mediaSession+ }++ print("[CallKit] Creating NativeLiveKitCallSession")+ let mediaSession = NativeLiveKitCallSession(+ onSnapshotChanged: { [weak self] snapshot in+ self?.emitConnectionState(snapshot)+ },+ requestSystemEndCall: { [weak self] uuid in+ self?.callCoordinator.requestEndCall(uuid: uuid)+ },+ onDrawerOpened: { [weak self] channelId in+ self?.emitDrawerOpened(channelId: channelId)+ },+ onParticipantIdentitiesChanged: { [weak self] identities in+ self?.emitParticipantIdentities(identities)+ },+ videoOverlay: videoOverlay+ )+ self.mediaSession = mediaSession+ replayPendingParticipantDisplayNames(to: mediaSession)+ return mediaSession+ }++ private func setParticipantDisplayName(identity: String, displayName: String?) {+ if let mediaSession {+ mediaSession.setParticipantDisplayName(identity: identity, displayName: displayName)+ return+ }++ 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)")+ } else {+ pendingParticipantDisplayNamesByIdentity.removeValue(forKey: identity)+ print("[CallKit] Cleared pending participant display name before native session exists identity=\(identity)")+ }+ }++ private func replayPendingParticipantDisplayNames(to mediaSession: NativeLiveKitCallSession) {+ guard !pendingParticipantDisplayNamesByIdentity.isEmpty else { return }++ print("[CallKit] Replaying pending participant display names count=\(pendingParticipantDisplayNamesByIdentity.count)")+ for (identity, displayName) in pendingParticipantDisplayNamesByIdentity {+ mediaSession.setParticipantDisplayName(identity: identity, displayName: displayName)+ }+ pendingParticipantDisplayNamesByIdentity.removeAll()+ }++ private func onMain(_ block: @escaping () -> Void) {+ if Thread.isMainThread {+ block()+ } else {+ DispatchQueue.main.async(execute: block)+ }+ }++ private static func uiColor(_ color: RgbaColorArgs) -> UIColor {+ UIColor(+ red: max(0, min(1, color.red)),+ green: max(0, min(1, color.green)),+ blue: max(0, min(1, color.blue)),+ alpha: max(0, min(1, color.alpha ?? 1))+ )+ }}@_cdecl("init_plugin_call_kit")diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swiftnew file mode 100644index 0000000000..c913964fa3--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallPictureInPictureController.swift@@ -0,0 +1,428 @@+import AVFoundation+import AVKit+import LiveKit+import UIKit++protocol CallPictureInPictureManaging: AnyObject {+ func prepare()+ func setParticipants(+ localTitle: String?,+ localTrack: VideoTrack?,+ remoteTitle: String?,+ remoteTrack: VideoTrack?+ )+ func stopAndReset()+}++func makeCallPictureInPictureController(+ sourceViewProvider: @escaping () -> UIView?,+ onRestore: @escaping () -> Void+) -> CallPictureInPictureManaging {+ if #available(iOS 15.0, *) {+ return AVKitCallPictureInPictureController(+ sourceViewProvider: sourceViewProvider,+ onRestore: onRestore+ )+ }++ return NoOpCallPictureInPictureController()+}++private final class NoOpCallPictureInPictureController: CallPictureInPictureManaging {+ func prepare() {}++ func setParticipants(+ localTitle: String?,+ localTrack: VideoTrack?,+ remoteTitle: String?,+ remoteTrack: VideoTrack?+ ) {+ if localTrack != nil || remoteTrack != nil {+ print("[CallKit] Picture in Picture unavailable before iOS 15")+ }+ }++ func stopAndReset() {}+}++@available(iOS 15.0, *)+private final class AVKitCallPictureInPictureController: NSObject, AVPictureInPictureControllerDelegate, CallPictureInPictureManaging, @unchecked Sendable {+ private let sourceViewProvider: () -> UIView?+ private let onRestore: () -> Void+ private 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?+ private var didObserveAppLifecycle = false++ init(+ sourceViewProvider: @escaping () -> UIView?,+ onRestore: @escaping () -> Void+ ) {+ self.sourceViewProvider = sourceViewProvider+ self.onRestore = onRestore+ super.init()+ observeAppLifecycle()+ }++ deinit {+ NotificationCenter.default.removeObserver(self)+ }++ func prepare() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.prepareControllerIfPossible()+ }+ }++ func setParticipants(+ localTitle: String?,+ localTrack: VideoTrack?,+ remoteTitle: String?,+ remoteTrack: VideoTrack?+ ) {+ DispatchQueue.main.async { [weak self, weak localTrack, weak remoteTrack] in+ guard let self else { return }++ let normalizedLocalTitle = self.normalizedTitle(localTitle)+ let normalizedRemoteTitle = self.normalizedTitle(remoteTitle)+ self.currentLocalTitle = normalizedLocalTitle+ self.currentRemoteTitle = normalizedRemoteTitle+ self.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")")++ if self.currentLocalTrack !== localTrack {+ self.currentLocalTrack = localTrack+ self.videoCallController.setLocalTrack(localTrack)+ print("[CallKit] Picture in Picture local video track \(localTrack == nil ? "detached" : "attached")")+ }++ if self.currentRemoteTrack !== remoteTrack {+ self.currentRemoteTrack = remoteTrack+ self.videoCallController.setRemoteTrack(remoteTrack)+ print("[CallKit] Picture in Picture remote video track \(remoteTrack == nil ? "detached" : "attached")")+ }++ if localTrack == nil {+ print("[CallKit] Picture in Picture local side using placeholder")+ }+ if remoteTrack == nil {+ print("[CallKit] Picture in Picture remote side using placeholder")+ }+ self.prepareControllerIfPossible()+ }+ }++ func stopAndReset() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ if self.pictureInPictureController?.isPictureInPictureActive == true {+ print("[CallKit] Stopping Picture in Picture")+ self.pictureInPictureController?.stopPictureInPicture()+ }+ self.currentLocalTrack = nil+ self.currentRemoteTrack = nil+ self.currentLocalTitle = nil+ self.currentRemoteTitle = nil+ self.currentSourceView = nil+ self.pictureInPictureController = nil+ self.videoCallController.resetLocal(hasVideo: false)+ self.videoCallController.resetRemote(hasVideo: false)+ self.videoCallController.setTitles(localTitle: nil, remoteTitle: nil)+ }+ }++ private func observeAppLifecycle() {+ guard !didObserveAppLifecycle else { return }+ didObserveAppLifecycle = true+ NotificationCenter.default.addObserver(+ self,+ selector: #selector(appWillResignActive),+ name: UIApplication.willResignActiveNotification,+ object: nil+ )+ NotificationCenter.default.addObserver(+ self,+ selector: #selector(appDidEnterBackground),+ name: UIApplication.didEnterBackgroundNotification,+ object: nil+ )+ print("[CallKit] Picture in Picture observing app lifecycle")+ }++ private func prepareControllerIfPossible() {+ guard AVPictureInPictureController.isPictureInPictureSupported() else {+ print("[CallKit] Picture in Picture unsupported on this device")+ return+ }+ guard let sourceView = sourceViewProvider() else {+ print("[CallKit] 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)")+ return+ }++ currentSourceView = sourceView+ videoCallController.loadViewIfNeeded()+ let contentSource = AVPictureInPictureController.ContentSource(+ activeVideoCallSourceView: sourceView,+ contentViewController: videoCallController+ )+ let controller = AVPictureInPictureController(contentSource: contentSource)+ controller.canStartPictureInPictureAutomaticallyFromInline = true+ controller.delegate = self+ pictureInPictureController = 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)")+ }++ @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) {+ 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)")+ return+ }++ print("[CallKit] Starting Picture in Picture reason=\(reason) localTitle=\(currentLocalTitle ?? "nil") localTrack=\(currentLocalTrack != nil) remoteTitle=\(currentRemoteTitle ?? "nil") remoteTrack=\(currentRemoteTrack != nil)")+ controller.startPictureInPicture()+ }++ private func normalizedTitle(_ title: String?) -> String? {+ let trimmed = title?.trimmingCharacters(in: .whitespacesAndNewlines)+ return trimmed?.isEmpty == false ? trimmed : nil+ }++ func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {+ print("[CallKit] Picture in Picture will start")+ }++ func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {+ print("[CallKit] Picture in Picture did start")+ }++ func pictureInPictureController(+ _ pictureInPictureController: AVPictureInPictureController,+ failedToStartPictureInPictureWithError error: Error+ ) {+ print("[CallKit] Picture in Picture failed to start error=\(error)")+ }++ func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) {+ print("[CallKit] Picture in Picture did stop")+ }++ func pictureInPictureController(+ _ pictureInPictureController: AVPictureInPictureController,+ restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void+ ) {+ print("[CallKit] Picture in Picture restore requested")+ onRestore()+ completionHandler(true)+ }+}++@available(iOS 15.0, *)+private final class CallPiPVideoCallViewController: AVPictureInPictureVideoCallViewController, @unchecked Sendable {+ private lazy var contentView = CallPiPContentView()++ override func loadView() {+ view = contentView+ preferredContentSize = CGSize(width: 320, height: 150)+ }++ func setTitles(localTitle: String?, remoteTitle: String?) {+ contentView.localView.setParticipantTitle(localTitle ?? "You")+ contentView.remoteView.setParticipantTitle(remoteTitle ?? "No one else is here")+ }++ func resetLocal(hasVideo: Bool) {+ contentView.localView.reset(hasVideo: hasVideo)+ }++ func resetRemote(hasVideo: Bool) {+ contentView.remoteView.reset(hasVideo: hasVideo)+ }++ func setLocalTrack(_ track: VideoTrack?) {+ contentView.localView.setTrack(track)+ }++ func setRemoteTrack(_ track: VideoTrack?) {+ contentView.remoteView.setTrack(track)+ }+}++private final class CallPiPContentView: UIView {+ let localView = CallPiPParticipantView(isMirrored: true)+ let remoteView = CallPiPParticipantView(isMirrored: false)+ private let dividerView = UIView()++ override init(frame: CGRect) {+ super.init(frame: frame)+ backgroundColor = UIColor(white: 0.06, alpha: 1)++ localView.translatesAutoresizingMaskIntoConstraints = false+ remoteView.translatesAutoresizingMaskIntoConstraints = false+ dividerView.backgroundColor = UIColor.white.withAlphaComponent(0.18)+ dividerView.translatesAutoresizingMaskIntoConstraints = false+ addSubview(localView)+ addSubview(remoteView)+ addSubview(dividerView)++ NSLayoutConstraint.activate([+ localView.leadingAnchor.constraint(equalTo: leadingAnchor),+ localView.topAnchor.constraint(equalTo: topAnchor),+ localView.bottomAnchor.constraint(equalTo: bottomAnchor),+ localView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.5),+ remoteView.leadingAnchor.constraint(equalTo: localView.trailingAnchor),+ remoteView.trailingAnchor.constraint(equalTo: trailingAnchor),+ remoteView.topAnchor.constraint(equalTo: topAnchor),+ remoteView.bottomAnchor.constraint(equalTo: bottomAnchor),+ dividerView.centerXAnchor.constraint(equalTo: centerXAnchor),+ dividerView.topAnchor.constraint(equalTo: topAnchor),+ dividerView.bottomAnchor.constraint(equalTo: bottomAnchor),+ dividerView.widthAnchor.constraint(equalToConstant: 1),+ ])+ localView.setParticipantTitle("You")+ remoteView.setParticipantTitle("No one else is here")+ }++ required init?(coder: NSCoder) {+ nil+ }+}++private final class CallPiPParticipantView: UIView {+ private let videoView = VideoView()+ private let placeholderView = UIView()+ private let initialsLabel = UILabel()+ private let nameLabel = UILabel()++ init(frame: CGRect = .zero, isMirrored: Bool) {+ super.init(frame: frame)+ backgroundColor = UIColor(white: 0.06, alpha: 1)++ videoView.layoutMode = .fill+ videoView.renderMode = .sampleBuffer+ videoView.mirrorMode = isMirrored ? .auto : .off+ videoView.backgroundColor = UIColor(white: 0.06, alpha: 1)+ videoView.translatesAutoresizingMaskIntoConstraints = false+ addSubview(videoView)++ placeholderView.backgroundColor = UIColor(white: 0.06, alpha: 1)+ placeholderView.translatesAutoresizingMaskIntoConstraints = false+ addSubview(placeholderView)++ initialsLabel.textAlignment = .center+ initialsLabel.textColor = .white+ initialsLabel.backgroundColor = UIColor(white: 0.18, alpha: 1)+ initialsLabel.font = .systemFont(ofSize: 20, weight: .semibold)+ initialsLabel.layer.cornerRadius = 22+ initialsLabel.layer.masksToBounds = true+ initialsLabel.clipsToBounds = true+ initialsLabel.translatesAutoresizingMaskIntoConstraints = false+ placeholderView.addSubview(initialsLabel)++ nameLabel.textAlignment = .center+ nameLabel.textColor = UIColor.white.withAlphaComponent(0.88)+ nameLabel.font = .systemFont(ofSize: 10, weight: .medium)+ nameLabel.numberOfLines = 2+ nameLabel.translatesAutoresizingMaskIntoConstraints = false+ placeholderView.addSubview(nameLabel)++ NSLayoutConstraint.activate([+ videoView.leadingAnchor.constraint(equalTo: leadingAnchor),+ videoView.trailingAnchor.constraint(equalTo: trailingAnchor),+ videoView.topAnchor.constraint(equalTo: topAnchor),+ videoView.bottomAnchor.constraint(equalTo: bottomAnchor),+ placeholderView.leadingAnchor.constraint(equalTo: leadingAnchor),+ placeholderView.trailingAnchor.constraint(equalTo: trailingAnchor),+ placeholderView.topAnchor.constraint(equalTo: topAnchor),+ placeholderView.bottomAnchor.constraint(equalTo: bottomAnchor),+ initialsLabel.centerXAnchor.constraint(equalTo: placeholderView.centerXAnchor),+ initialsLabel.centerYAnchor.constraint(equalTo: placeholderView.centerYAnchor, constant: -7),+ initialsLabel.widthAnchor.constraint(equalToConstant: 44),+ initialsLabel.heightAnchor.constraint(equalToConstant: 44),+ nameLabel.leadingAnchor.constraint(greaterThanOrEqualTo: placeholderView.leadingAnchor, constant: 8),+ nameLabel.trailingAnchor.constraint(lessThanOrEqualTo: placeholderView.trailingAnchor, constant: -8),+ nameLabel.topAnchor.constraint(equalTo: initialsLabel.bottomAnchor, constant: 5),+ nameLabel.centerXAnchor.constraint(equalTo: placeholderView.centerXAnchor),+ ])+ }++ required init?(coder: NSCoder) {+ nil+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ initialsLabel.layer.cornerRadius = initialsLabel.bounds.width / 2+ initialsLabel.layer.masksToBounds = true+ initialsLabel.clipsToBounds = true+ }++ func setParticipantTitle(_ title: String?) {+ let displayTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines)+ let resolvedTitle = displayTitle?.isEmpty == false ? displayTitle! : "Call"+ initialsLabel.text = initials(from: resolvedTitle)+ nameLabel.text = resolvedTitle+ }++ func setTrack(_ track: VideoTrack?) {+ videoView.track = track+ setHasVideo(track != nil)+ }++ func setHasVideo(_ hasVideo: Bool) {+ videoView.isHidden = !hasVideo+ placeholderView.isHidden = hasVideo+ }++ func reset(hasVideo: Bool) {+ if !hasVideo {+ videoView.track = nil+ }+ setHasVideo(hasVideo)+ }++ private func initials(from title: String) -> String {+ let words = title+ .split { $0.isWhitespace || $0 == "@" || $0 == "." || $0 == "|" }+ .map(String.init)+ .filter { !$0.isEmpty && $0.lowercased() != "macro" }+ if words.count >= 2 {+ return "\(words[0].prefix(1))\(words[1].prefix(1))".uppercased()+ }+ if let first = words.first {+ return String(first.prefix(1)).uppercased()+ }+ return "?"+ }+}diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swiftnew file mode 100644index 0000000000..c886e8d51a--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallVideoOverlayController.swift@@ -0,0 +1,1251 @@+import LiveKit+import UIKit+import WebKit++enum CallVideoOverlayMode: String {+ case hidden+ case expanded+ case minimized+}++struct NativeVideoParticipant {+ let id: String+ let title: String+ var avatarTitle: String? = nil+ let track: VideoTrack?+ let isSpeaking: Bool+ let isPinned: Bool+ let isScreenShare: Bool+}++struct CallVideoOverlayTheme {+ let drawerBackgroundColor: UIColor+ let textColor: UIColor+ let messageBackgroundColor: UIColor+ let overlayBackgroundColor: UIColor+ let edgeMutedColor: UIColor+ let edgeColor: UIColor+ let inkMutedColor: UIColor+ let failureColor: UIColor+ let failureInkColor: UIColor+ let successColor: UIColor++ static let fallback = CallVideoOverlayTheme(+ drawerBackgroundColor: UIColor.black.withAlphaComponent(0.94),+ textColor: .white,+ messageBackgroundColor: UIColor(white: 0.08, alpha: 1),+ overlayBackgroundColor: UIColor.black.withAlphaComponent(0.46),+ edgeMutedColor: UIColor(white: 0.18, alpha: 1),+ edgeColor: UIColor(white: 0.36, alpha: 1),+ inkMutedColor: UIColor(white: 0.84, alpha: 1),+ failureColor: UIColor.systemRed,+ failureInkColor: .white,+ successColor: UIColor.systemGreen+ )+}++/// Native video surface that floats above the Tauri WKWebView.+final class CallVideoOverlayController: NSObject, UIGestureRecognizerDelegate, @unchecked Sendable {+ private let rootView = PassthroughOverlayView()+ private let modalOverlayView = UIView()+ private let drawerView = UIView()+ private let drawerHandle = UIView()+ private let channelTitleLabel = UILabel()+ private let leaveButton = UIButton(type: .system)+ private let primaryVideoView = VideoView()+ private let primaryPlaceholderView = UIView()+ private let primaryInitialsLabel = UILabel()+ private let primaryEmptyStateLabel = UILabel()+ private let primaryParticipantLabel = UILabel()+ private let stripScrollView = UIScrollView()+ private let stripStackView = UIStackView()+ private let localTileView = RemoteVideoTileView(isMirrored: true)+ private let controlsView = UIStackView()+ private let microphoneButton = UIButton(type: .system)+ private let speakerButton = UIButton(type: .system)+ private let cameraButton = UIButton(type: .system)+ private let switchCameraButton = UIButton(type: .system)+ private let thumbnailView = UIView()+ private let thumbnailLocalVideoView = VideoView()+ private let thumbnailLocalPlaceholderView = UIView()+ private let thumbnailLocalInitialsLabel = UILabel()+ private let thumbnailRemoteVideoView = VideoView()+ private let thumbnailRemotePlaceholderView = UIView()+ private let thumbnailRemoteInitialsLabel = UILabel()+ private let thumbnailDividerView = UIView()+ private let edgeTabView = UILabel()++ var onToggleMicrophone: (() -> Void)?+ var onToggleSpeaker: (() -> Void)?+ var onToggleCamera: (() -> Void)?+ var onSwitchCamera: (() -> Void)?+ var onEndCall: (() -> Void)?+ var onSelectRemoteParticipant: ((String) -> Void)?+ var onOpenDrawerFromThumbnail: (() -> Void)?+ var onModeChanged: ((CallVideoOverlayMode) -> Void)?++ private var mode: CallVideoOverlayMode = .hidden+ private var thumbnailCorner: ThumbnailCorner = .topRight+ private var didAutoPresent = false+ private var isAudioMuted = false+ private var audioRoute = CallAudioRouteSnapshot(+ input: .unknown,+ output: .unknown,+ isSpeakerForced: false,+ supportsSpeakerToggle: true+ )+ private var isLocalVideoEnabled = false+ private var channelTitle = "Call"+ private var theme = CallVideoOverlayTheme.fallback+ private var localParticipantTitle = "You"+ private var localVideoTrack: VideoTrack?+ private var renderedLocalPreviewTrack: VideoTrack?+ private var remoteVideoParticipants: [NativeVideoParticipant] = []+ private var primaryRemoteParticipantId: String?+ private var primaryRemoteParticipantTitle: String?+ private var primaryRemoteVideoTrack: VideoTrack?+ private var renderedThumbnailLocalVideoTrack: VideoTrack?+ private var renderedThumbnailRemoteVideoTrack: VideoTrack?+ private var stripTileViews: [String: RemoteVideoTileView] = [:]+ private var drawerPanStartFrame: CGRect = .zero+ private weak var webview: WKWebView?++ override init() {+ super.init()+ configureViews()+ }++ func attach(to webview: WKWebView) {+ DispatchQueue.main.async { [weak self, weak webview] in+ guard let self, let webview else { return }+ self.webview = webview+ self.attachToBestAvailableParent()+ self.layoutOverlay()+ }+ }++ func setMode(_ mode: CallVideoOverlayMode) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.mode = mode+ self.attachToBestAvailableParent()+ self.rootView.superview?.bringSubviewToFront(self.rootView)+ self.updateVideoRenderTargets()+ self.layoutOverlay()+ print("[CallKit] Native video overlay mode=\(mode.rawValue)")+ self.onModeChanged?(mode)+ }+ }++ func setChannelTitle(_ title: String?) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ let trimmedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines)+ if let trimmedTitle, !trimmedTitle.isEmpty {+ self.channelTitle = trimmedTitle+ } else {+ self.channelTitle = "Call"+ }+ self.channelTitleLabel.text = self.channelTitle+ self.layoutOverlay()+ print("[CallKit] Native video overlay channelTitle=\(self.channelTitle)")+ }+ }++ func setTheme(_ theme: CallVideoOverlayTheme?) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.theme = theme ?? .fallback+ self.applyTheme()+ print("[CallKit] Native video overlay theme updated")+ }+ }++ func pictureInPictureSourceView() -> UIView {+ if mode == .minimized {+ return thumbnailView+ }++ return primaryVideoView+ }++ func presentForActiveCallIfNeeded() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.attachToBestAvailableParent()+ guard self.mode == .hidden, !self.didAutoPresent else { return }+ self.didAutoPresent = true+ self.mode = .expanded+ self.rootView.superview?.bringSubviewToFront(self.rootView)+ self.layoutOverlay()+ print("[CallKit] Native video overlay auto-presented for active call")+ }+ }++ func setRemoteVideoTrack(_ track: VideoTrack?) {+ DispatchQueue.main.async { [weak self, weak track] in+ guard let self else { return }+ self.attachToBestAvailableParent()+ self.remoteVideoParticipants = []+ self.primaryRemoteParticipantId = nil+ self.primaryRemoteParticipantTitle = nil+ self.primaryRemoteVideoTrack = track+ self.rebuildParticipantStrip()+ self.primaryVideoView.track = track+ self.updateVideoRenderTargets()+ if track != nil, self.mode == .hidden, !self.didAutoPresent {+ self.didAutoPresent = true+ self.mode = .expanded+ self.updateVideoRenderTargets()+ }+ self.rootView.superview?.bringSubviewToFront(self.rootView)+ self.layoutOverlay()+ print("[CallKit] Native video overlay remoteTrack=\(track == nil ? "nil" : "set")")+ }+ }++ func setRemoteVideoParticipants(_ participants: [NativeVideoParticipant], primaryId: String?) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.attachToBestAvailableParent()+ self.remoteVideoParticipants = participants+ self.primaryRemoteParticipantId = primaryId++ let primary = participants.first(where: { $0.id == primaryId }) ?? participants.first+ self.primaryRemoteVideoTrack = primary?.track+ self.primaryRemoteParticipantTitle = primary.map { $0.isScreenShare ? "Screen" : $0.title }+ self.primaryVideoView.track = primary?.track+ self.updateVideoRenderTargets()+ self.rebuildParticipantStrip()++ if primary != nil, self.mode == .hidden, !self.didAutoPresent {+ self.didAutoPresent = true+ self.mode = .expanded+ self.updateVideoRenderTargets()+ }++ self.rootView.superview?.bringSubviewToFront(self.rootView)+ self.layoutOverlay()+ print("[CallKit] Native video overlay remoteParticipants=\(participants.count) primary=\(primary?.id ?? "nil")")+ }+ }++ func setLocalVideoTrack(_ track: VideoTrack?) {+ DispatchQueue.main.async { [weak self, weak track] in+ guard let self else { return }+ self.attachToBestAvailableParent()+ self.localVideoTrack = track+ self.updateVideoRenderTargets()+ self.setLocalVideoEnabled(track != nil)+ if track != nil, self.mode == .hidden, !self.didAutoPresent {+ self.didAutoPresent = true+ self.mode = .expanded+ }+ self.rootView.superview?.bringSubviewToFront(self.rootView)+ self.layoutOverlay()+ print("[CallKit] Native video overlay localTrack=\(track == nil ? "nil" : "set")")+ }+ }++ func setLocalParticipantTitle(_ title: String?) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ let trimmedTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines)+ if let trimmedTitle, !trimmedTitle.isEmpty {+ self.localParticipantTitle = trimmedTitle+ } else {+ self.localParticipantTitle = "You"+ }+ self.configureLocalTile(track: self.renderedLocalPreviewTrack)+ self.layoutOverlay()+ print("[CallKit] Native video overlay localParticipantTitle=\(self.localParticipantTitle)")+ }+ }++ func setLocalVideoEnabled(_ enabled: Bool) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.isLocalVideoEnabled = enabled+ self.configureControlState()+ self.layoutOverlay()+ print("[CallKit] Native video overlay localVideoEnabled=\(enabled)")+ }+ }++ func setAudioMuted(_ muted: Bool) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.isAudioMuted = muted+ self.configureControlState()+ self.layoutOverlay()+ print("[CallKit] Native video overlay audioMuted=\(muted)")+ }+ }++ func setAudioRoute(_ route: CallAudioRouteSnapshot) {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.audioRoute = route+ self.configureControlState()+ print("[CallKit] Native video overlay audioRoute input=\(route.input.rawValue) output=\(route.output.rawValue) speakerForced=\(route.isSpeakerForced) supportsSpeakerToggle=\(route.supportsSpeakerToggle)")+ }+ }++ func reset() {+ DispatchQueue.main.async { [weak self] in+ guard let self else { return }+ self.primaryVideoView.track = nil+ self.thumbnailLocalVideoView.track = nil+ self.thumbnailLocalPlaceholderView.isHidden = false+ self.thumbnailRemoteVideoView.track = nil+ self.thumbnailRemotePlaceholderView.isHidden = false+ self.localVideoTrack = nil+ self.renderedLocalPreviewTrack = nil+ self.configureLocalTile(track: nil)+ self.remoteVideoParticipants = []+ self.primaryRemoteParticipantId = nil+ self.primaryRemoteParticipantTitle = nil+ self.primaryRemoteVideoTrack = nil+ self.renderedThumbnailLocalVideoTrack = nil+ self.renderedThumbnailRemoteVideoTrack = nil+ self.rebuildParticipantStrip()+ self.isAudioMuted = false+ self.audioRoute = CallAudioRouteSnapshot(+ input: .unknown,+ output: .unknown,+ isSpeakerForced: false,+ supportsSpeakerToggle: true+ )+ self.isLocalVideoEnabled = false+ self.localParticipantTitle = "You"+ self.mode = .hidden+ self.didAutoPresent = false+ self.channelTitle = "Call"+ self.channelTitleLabel.text = self.channelTitle+ self.configureControlState()+ self.layoutOverlay()+ print("[CallKit] Native video overlay reset")+ }+ }++ private func attachToBestAvailableParent() {+ guard let webview else { return }+ let parent = webview.window ?? webview.superview ?? webview+ if rootView.superview !== parent {+ rootView.removeFromSuperview()+ rootView.frame = parent.bounds+ rootView.autoresizingMask = [.flexibleWidth, .flexibleHeight]+ parent.addSubview(rootView)+ print("[CallKit] Attached native video overlay parent=\(type(of: parent)) frame=\(parent.bounds)")+ } else {+ rootView.frame = parent.bounds+ }+ }++ private func configureViews() {+ rootView.backgroundColor = .clear+ rootView.onLayout = { [weak self] in self?.layoutOverlay() }++ modalOverlayView.backgroundColor = theme.overlayBackgroundColor+ rootView.addSubview(modalOverlayView)++ drawerView.backgroundColor = theme.drawerBackgroundColor+ drawerView.layer.cornerRadius = 18+ drawerView.layer.maskedCorners = [.layerMinXMinYCorner, .layerMaxXMinYCorner]+ drawerView.clipsToBounds = true+ rootView.addSubview(drawerView)++ let drawerPan = UIPanGestureRecognizer(target: self, action: #selector(dragDrawer(_:)))+ drawerPan.delegate = self+ drawerPan.cancelsTouchesInView = false+ drawerView.addGestureRecognizer(drawerPan)++ drawerHandle.backgroundColor = theme.edgeColor+ drawerHandle.layer.cornerRadius = 2+ drawerView.addSubview(drawerHandle)++ channelTitleLabel.text = channelTitle+ channelTitleLabel.textColor = theme.textColor+ channelTitleLabel.font = .systemFont(ofSize: 17, weight: .semibold)+ channelTitleLabel.lineBreakMode = .byTruncatingTail+ drawerView.addSubview(channelTitleLabel)++ leaveButton.tintColor = theme.drawerBackgroundColor+ leaveButton.backgroundColor = theme.failureColor+ leaveButton.layer.cornerRadius = 16+ leaveButton.clipsToBounds = true+ leaveButton.titleLabel?.font = .systemFont(ofSize: 15, weight: .semibold)+ leaveButton.setTitle("Leave", for: .normal)+ leaveButton.addTarget(self, action: #selector(endCall), for: .touchUpInside)+ drawerView.addSubview(leaveButton)++ primaryVideoView.layoutMode = .fill+ primaryVideoView.backgroundColor = theme.messageBackgroundColor+ primaryVideoView.layer.cornerRadius = 6+ primaryVideoView.clipsToBounds = true+ drawerView.addSubview(primaryVideoView)++ primaryPlaceholderView.backgroundColor = theme.messageBackgroundColor+ primaryPlaceholderView.layer.cornerRadius = 6+ primaryPlaceholderView.clipsToBounds = true+ drawerView.addSubview(primaryPlaceholderView)++ primaryInitialsLabel.textColor = theme.textColor+ primaryInitialsLabel.textAlignment = .center+ primaryInitialsLabel.font = .systemFont(ofSize: 34, weight: .semibold)+ primaryInitialsLabel.backgroundColor = theme.edgeMutedColor+ primaryInitialsLabel.layer.cornerRadius = 38+ primaryInitialsLabel.clipsToBounds = true+ primaryPlaceholderView.addSubview(primaryInitialsLabel)++ primaryEmptyStateLabel.text = "No one else is here"+ primaryEmptyStateLabel.textColor = theme.inkMutedColor+ primaryEmptyStateLabel.textAlignment = .center+ primaryEmptyStateLabel.font = .systemFont(ofSize: 16, weight: .semibold)+ primaryEmptyStateLabel.numberOfLines = 0+ primaryPlaceholderView.addSubview(primaryEmptyStateLabel)++ primaryParticipantLabel.textColor = theme.textColor+ primaryParticipantLabel.font = .systemFont(ofSize: 14, weight: .semibold)+ primaryParticipantLabel.lineBreakMode = .byTruncatingTail+ primaryParticipantLabel.backgroundColor = theme.edgeMutedColor+ primaryParticipantLabel.textAlignment = .center+ primaryParticipantLabel.layer.cornerRadius = 8+ primaryParticipantLabel.clipsToBounds = true+ drawerView.addSubview(primaryParticipantLabel)++ stripScrollView.showsHorizontalScrollIndicator = false+ stripScrollView.alwaysBounceHorizontal = true+ stripScrollView.backgroundColor = .clear+ drawerView.addSubview(stripScrollView)++ stripStackView.axis = .horizontal+ stripStackView.alignment = .fill+ stripStackView.distribution = .fill+ stripStackView.spacing = 10+ stripScrollView.addSubview(stripStackView)++ localTileView.applyTheme(theme)+ localTileView.configure(+ participant: NativeVideoParticipant(+ id: "__local",+ title: "You",+ avatarTitle: self.localParticipantTitle,+ track: nil,+ isSpeaking: false,+ isPinned: true,+ isScreenShare: false+ ),+ isPrimary: false+ )+ drawerView.addSubview(localTileView)++ controlsView.axis = .horizontal+ controlsView.alignment = .fill+ controlsView.distribution = .fill+ controlsView.spacing = 10+ controlsView.backgroundColor = .clear+ controlsView.clipsToBounds = false+ drawerView.addSubview(controlsView)++ configureControlButton(microphoneButton, systemImageName: "mic.fill", action: #selector(toggleMicrophone))+ configureControlButton(speakerButton, systemImageName: "speaker.wave.2.fill", action: #selector(toggleSpeaker))+ configureControlButton(cameraButton, systemImageName: "video.slash.fill", action: #selector(toggleCamera))+ speakerButton.layer.maskedCorners = [.layerMinXMinYCorner, .layerMinXMaxYCorner]+ microphoneButton.layer.maskedCorners = []+ cameraButton.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMaxXMaxYCorner]+ controlsView.addArrangedSubview(speakerButton)+ controlsView.addArrangedSubview(microphoneButton)+ controlsView.addArrangedSubview(cameraButton)++ configurePreviewOverlayButton(switchCameraButton, systemImageName: "camera.rotate.fill", action: #selector(switchCamera))+ drawerView.addSubview(switchCameraButton)+ configureControlState()++ let minimizeTap = UITapGestureRecognizer(target: self, action: #selector(minimizeFromDrawer))+ drawerHandle.addGestureRecognizer(minimizeTap)+ drawerHandle.isUserInteractionEnabled = true++ thumbnailView.backgroundColor = theme.messageBackgroundColor+ thumbnailView.layer.cornerRadius = 12+ thumbnailView.layer.borderColor = theme.edgeColor.cgColor+ thumbnailView.layer.borderWidth = 1+ thumbnailView.clipsToBounds = true+ rootView.addSubview(thumbnailView)++ thumbnailLocalVideoView.layoutMode = .fill+ thumbnailLocalVideoView.mirrorMode = .auto+ thumbnailLocalVideoView.backgroundColor = theme.messageBackgroundColor+ thumbnailView.addSubview(thumbnailLocalVideoView)++ configureThumbnailPlaceholder(thumbnailLocalPlaceholderView, initialsLabel: thumbnailLocalInitialsLabel)+ thumbnailView.addSubview(thumbnailLocalPlaceholderView)++ thumbnailRemoteVideoView.layoutMode = .fill+ thumbnailRemoteVideoView.backgroundColor = theme.messageBackgroundColor+ thumbnailView.addSubview(thumbnailRemoteVideoView)++ configureThumbnailPlaceholder(thumbnailRemotePlaceholderView, initialsLabel: thumbnailRemoteInitialsLabel)+ thumbnailView.addSubview(thumbnailRemotePlaceholderView)++ thumbnailDividerView.backgroundColor = theme.edgeColor+ thumbnailView.addSubview(thumbnailDividerView)++ let thumbnailTap = UITapGestureRecognizer(target: self, action: #selector(expandFromThumbnail))+ thumbnailView.addGestureRecognizer(thumbnailTap)+ let thumbnailPan = UIPanGestureRecognizer(target: self, action: #selector(dragThumbnail(_:)))+ thumbnailView.addGestureRecognizer(thumbnailPan)++ edgeTabView.backgroundColor = theme.edgeMutedColor+ edgeTabView.textColor = theme.textColor+ edgeTabView.textAlignment = .center+ edgeTabView.font = .boldSystemFont(ofSize: 18)+ edgeTabView.layer.cornerRadius = 10+ edgeTabView.clipsToBounds = true+ edgeTabView.isUserInteractionEnabled = true+ edgeTabView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showThumbnailFromEdge)))+ rootView.addSubview(edgeTabView)+ }++ private func configureControlButton(_ button: UIButton, systemImageName: String, action: Selector) {+ button.layer.cornerRadius = 8+ applyActionButtonTheme(button)+ button.clipsToBounds = true+ button.setImage(UIImage(systemName: systemImageName), for: .normal)+ button.addTarget(self, action: action, for: .touchUpInside)+ button.widthAnchor.constraint(equalToConstant: 48).isActive = true+ button.heightAnchor.constraint(equalToConstant: 44).isActive = true+ }++ private func applyActionButtonTheme(_ button: UIButton, isActive: Bool = false) {+ button.tintColor = theme.textColor+ button.backgroundColor = isActive+ ? theme.edgeMutedColor+ : theme.inkMutedColor.withAlphaComponent(0.025)+ button.layer.borderColor = isActive+ ? theme.edgeColor.cgColor+ : theme.inkMutedColor.withAlphaComponent(0.08).cgColor+ button.layer.borderWidth = 1+ }++ private func configurePreviewOverlayButton(_ button: UIButton, systemImageName: String, action: Selector) {+ button.tintColor = theme.textColor+ button.backgroundColor = theme.edgeMutedColor+ button.layer.cornerRadius = 18+ button.layer.borderColor = theme.edgeColor.cgColor+ button.layer.borderWidth = 1+ button.clipsToBounds = true+ button.setImage(UIImage(systemName: systemImageName), for: .normal)+ button.addTarget(self, action: action, for: .touchUpInside)+ }++ private func configureThumbnailPlaceholder(_ placeholderView: UIView, initialsLabel: UILabel) {+ placeholderView.backgroundColor = theme.messageBackgroundColor++ initialsLabel.textColor = theme.textColor+ initialsLabel.textAlignment = .center+ initialsLabel.font = .systemFont(ofSize: 18, weight: .semibold)+ initialsLabel.numberOfLines = 2+ initialsLabel.backgroundColor = theme.edgeMutedColor+ initialsLabel.layer.cornerRadius = 22+ initialsLabel.clipsToBounds = true+ placeholderView.addSubview(initialsLabel)+ }++ private func participantLabelBackgroundColor(hasVideo: Bool) -> UIColor {+ hasVideo ? theme.drawerBackgroundColor.withAlphaComponent(0.70) : theme.edgeMutedColor+ }++ private func configureControlState() {+ let microphoneImage = isAudioMuted ? "mic.slash.fill" : "mic.fill"+ microphoneButton.setImage(UIImage(systemName: microphoneImage), for: .normal)+ applyActionButtonTheme(microphoneButton)++ speakerButton.setImage(audioRouteButtonImage(), for: .normal)+ speakerButton.isEnabled = audioRoute.supportsSpeakerToggle+ speakerButton.alpha = audioRoute.supportsSpeakerToggle ? 1 : 0.45+ applyActionButtonTheme(speakerButton, isActive: audioRoute.output == .speaker || (audioRoute.output == .unknown && audioRoute.isSpeakerForced))++ let cameraImage = isLocalVideoEnabled ? "video.fill" : "video.slash.fill"+ cameraButton.setImage(UIImage(systemName: cameraImage), for: .normal)+ applyActionButtonTheme(cameraButton)+ switchCameraButton.isHidden = !isLocalVideoEnabled+ }++ private func audioRouteButtonImage() -> UIImage? {+ switch audioRoute.output {+ case .speaker, .receiver, .unknown:+ return UIImage(systemName: "speaker.wave.2.fill")+ case .bluetooth:+ return UIImage(systemName: "bluetooth") ?? bluetoothTemplateImage()+ case .headphones:+ return UIImage(systemName: "headphones")+ }+ }++ private func bluetoothTemplateImage() -> UIImage {+ let size = CGSize(width: 20, height: 20)+ let renderer = UIGraphicsImageRenderer(size: size)+ return renderer.image { context in+ let h = size.height+ let y1 = h * 0.05+ let y2 = h * 0.25+ let cgContext = context.cgContext+ cgContext.move(to: CGPoint(x: y2, y: y2))+ cgContext.addLine(to: CGPoint(x: h - y2, y: h - y2))+ cgContext.addLine(to: CGPoint(x: h / 2, y: h - y1))+ cgContext.addLine(to: CGPoint(x: h / 2, y: y1))+ cgContext.addLine(to: CGPoint(x: h - y2, y: y2))+ cgContext.addLine(to: CGPoint(x: y2, y: h - y2))+ cgContext.setStrokeColor(UIColor.black.cgColor)+ cgContext.setLineCap(.round)+ cgContext.setLineJoin(.round)+ cgContext.setLineWidth(2)+ cgContext.strokePath()+ }.withRenderingMode(.alwaysTemplate)+ }++ private func rebuildParticipantStrip() {+ UIView.performWithoutAnimation {+ let participants = stripParticipants+ let activeIds = Set(participants.map(\.id))+ let staleIds = stripTileViews.keys.filter { !activeIds.contains($0) }+ for id in staleIds {+ guard let tile = stripTileViews.removeValue(forKey: id) else { continue }+ tile.prepareForRemoval()+ stripStackView.removeArrangedSubview(tile)+ tile.removeFromSuperview()+ }++ stripStackView.arrangedSubviews.forEach { view in+ stripStackView.removeArrangedSubview(view)+ view.removeFromSuperview()+ }++ for participant in participants {+ let tile = stripTileViews[participant.id] ?? RemoteVideoTileView()+ stripTileViews[participant.id] = tile+ tile.applyTheme(theme)+ tile.configure(participant: participant, isPrimary: participant.id == primaryRemoteParticipantId)+ tile.onTap = { [weak self] id in+ print("[CallKit] Native video overlay remote tile tapped id=\(id)")+ self?.onSelectRemoteParticipant?(id)+ }+ tile.ensureFixedSize()+ stripStackView.addArrangedSubview(tile)+ }+ }+ }++ private var stripParticipants: [NativeVideoParticipant] {+ remoteVideoParticipants.filter { $0.id != primaryRemoteParticipantId }+ }++ private func applyTheme() {+ applyDrawerTheme()+ applyPrimaryVideoTheme()+ applyParticipantStripTheme()+ applyControlsTheme()+ applyThumbnailTheme()+ applyEdgeTabTheme()+ layoutOverlay()+ }++ private func applyDrawerTheme() {+ drawerView.backgroundColor = theme.drawerBackgroundColor+ modalOverlayView.backgroundColor = theme.overlayBackgroundColor+ drawerHandle.backgroundColor = theme.edgeColor+ channelTitleLabel.textColor = theme.textColor+ leaveButton.tintColor = theme.drawerBackgroundColor+ leaveButton.backgroundColor = theme.failureColor+ }++ private func applyPrimaryVideoTheme() {+ primaryVideoView.backgroundColor = theme.messageBackgroundColor+ primaryPlaceholderView.backgroundColor = theme.messageBackgroundColor+ primaryInitialsLabel.textColor = theme.textColor+ primaryInitialsLabel.backgroundColor = theme.edgeMutedColor+ primaryEmptyStateLabel.textColor = theme.inkMutedColor+ primaryParticipantLabel.textColor = theme.textColor+ primaryParticipantLabel.backgroundColor = participantLabelBackgroundColor(hasVideo: primaryRemoteVideoTrack != nil)+ }++ private func applyParticipantStripTheme() {+ localTileView.applyTheme(theme)+ for tile in stripTileViews.values {+ tile.applyTheme(theme)+ }+ }++ private func applyControlsTheme() {+ controlsView.backgroundColor = .clear+ applyActionButtonTheme(microphoneButton)+ applyActionButtonTheme(cameraButton)+ switchCameraButton.tintColor = theme.textColor+ switchCameraButton.backgroundColor = theme.edgeMutedColor+ switchCameraButton.layer.borderColor = theme.edgeColor.cgColor+ configureControlState()+ }++ private func applyThumbnailTheme() {+ thumbnailView.backgroundColor = theme.messageBackgroundColor+ thumbnailView.layer.borderColor = theme.edgeColor.cgColor+ thumbnailLocalVideoView.backgroundColor = theme.messageBackgroundColor+ thumbnailRemoteVideoView.backgroundColor = theme.messageBackgroundColor+ thumbnailLocalPlaceholderView.backgroundColor = theme.messageBackgroundColor+ thumbnailRemotePlaceholderView.backgroundColor = theme.messageBackgroundColor+ thumbnailLocalInitialsLabel.textColor = theme.textColor+ thumbnailLocalInitialsLabel.backgroundColor = theme.edgeMutedColor+ thumbnailRemoteInitialsLabel.textColor = theme.textColor+ if primaryRemoteParticipantTitle != nil {+ thumbnailRemoteInitialsLabel.backgroundColor = theme.edgeMutedColor+ }+ thumbnailDividerView.backgroundColor = theme.edgeColor+ }++ private func applyEdgeTabTheme() {+ edgeTabView.backgroundColor = theme.edgeMutedColor+ edgeTabView.textColor = theme.textColor+ }++ private func updateVideoRenderTargets() {+ updateLocalPreviewTrack()+ updateThumbnailTracks()+ }++ private func updateLocalPreviewTrack() {+ let desiredTrack = mode == .expanded ? localVideoTrack : nil+ guard renderedLocalPreviewTrack !== desiredTrack else { return }+ renderedLocalPreviewTrack = desiredTrack+ configureLocalTile(track: desiredTrack)+ }++ private func configureLocalTile(track: VideoTrack?) {+ localTileView.applyTheme(theme)+ localTileView.configure(+ participant: NativeVideoParticipant(+ id: "__local",+ title: "You",+ avatarTitle: localParticipantTitle,+ track: track,+ isSpeaking: false,+ isPinned: true,+ isScreenShare: false+ ),+ isPrimary: false+ )+ }++ private func updateThumbnailTracks() {+ let desiredLocalTrack = mode == .minimized ? localVideoTrack : nil+ if renderedThumbnailLocalVideoTrack !== desiredLocalTrack {+ renderedThumbnailLocalVideoTrack = desiredLocalTrack+ thumbnailLocalVideoView.track = desiredLocalTrack+ }+ thumbnailLocalPlaceholderView.isHidden = desiredLocalTrack != nil++ let desiredRemoteTrack = mode == .minimized ? primaryRemoteVideoTrack : nil+ if renderedThumbnailRemoteVideoTrack !== desiredRemoteTrack {+ renderedThumbnailRemoteVideoTrack = desiredRemoteTrack+ thumbnailRemoteVideoView.track = desiredRemoteTrack+ }+ thumbnailRemotePlaceholderView.isHidden = desiredRemoteTrack != nil+ }++ private func layoutOverlay() {+ let bounds = rootView.bounds+ guard !bounds.isEmpty else { return }++ drawerView.isHidden = mode != .expanded+ modalOverlayView.isHidden = mode != .expanded+ thumbnailView.isHidden = mode != .minimized+ edgeTabView.isHidden = mode != .hidden || primaryRemoteParticipantTitle == nil+ rootView.blocksBackgroundTouches = mode == .expanded++ modalOverlayView.frame = bounds+ drawerView.frame = drawerFrame(in: bounds)+ drawerHandle.frame = CGRect(x: (drawerView.bounds.width - 42) / 2, y: 10, width: 42, height: 4)+ leaveButton.frame = CGRect(x: drawerView.bounds.width - 80, y: 18, width: 64, height: 32)+ channelTitleLabel.frame = CGRect(+ x: 16,+ y: 18,+ width: max(0, leaveButton.frame.minX - 28),+ height: 32+ )+ updateVideoRenderTargets()++ let stripParticipantCount = stripParticipants.count+ let shouldShowParticipantRow = mode == .expanded+ let stripHeight: CGFloat = shouldShowParticipantRow ? 92 : 0+ let controlsSize = controlsView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)+ let controlsBottomInset: CGFloat = 36+ let controlsTop = drawerView.bounds.height - controlsSize.height - controlsBottomInset+ let participantControlsGap: CGFloat = stripHeight > 0 ? 14 : 28+ let stripTop = controlsTop - stripHeight - participantControlsGap+ let primaryStripGap: CGFloat = stripHeight > 0 ? 18 : 0+ let primaryHorizontalInset: CGFloat = 16+ primaryVideoView.frame = CGRect(+ x: primaryHorizontalInset,+ y: 62,+ width: max(0, drawerView.bounds.width - (primaryHorizontalInset * 2)),+ height: max(0, stripTop - 62 - primaryStripGap)+ )+ let primaryHasParticipant = primaryRemoteParticipantTitle != nil+ let primaryHasVideo = primaryRemoteVideoTrack != nil+ primaryPlaceholderView.frame = primaryVideoView.frame+ primaryPlaceholderView.isHidden = primaryHasParticipant && primaryHasVideo+ primaryInitialsLabel.isHidden = !primaryHasParticipant+ primaryEmptyStateLabel.isHidden = primaryHasParticipant+ primaryInitialsLabel.text = primaryRemoteParticipantTitle.map(initials)+ primaryInitialsLabel.frame = CGRect(+ x: (primaryPlaceholderView.bounds.width - 76) / 2,+ y: (primaryPlaceholderView.bounds.height - 76) / 2,+ width: 76,+ height: 76+ )+ primaryEmptyStateLabel.frame = primaryPlaceholderView.bounds.insetBy(dx: 24, dy: 0)+ primaryParticipantLabel.text = primaryRemoteParticipantTitle+ primaryParticipantLabel.isHidden = primaryRemoteParticipantTitle == nil+ primaryParticipantLabel.backgroundColor = participantLabelBackgroundColor(hasVideo: primaryHasVideo)+ let primaryParticipantLabelSize = primaryParticipantLabel.sizeThatFits(+ CGSize(width: max(0, drawerView.bounds.width - 28), height: 28)+ )+ let primaryParticipantLabelWidth = min(+ max(0, drawerView.bounds.width - 28),+ primaryParticipantLabelSize.width + 12+ )+ primaryParticipantLabel.frame = CGRect(+ x: primaryVideoView.frame.minX + 10,+ y: primaryVideoView.frame.maxY - 42,+ width: primaryParticipantLabelWidth,+ height: 28+ )++ let tileWidth: CGFloat = 128+ let tileSpacing: CGFloat = 10+ let rowHorizontalInset: CGFloat = 16+ localTileView.isHidden = stripHeight == 0+ localTileView.frame = CGRect(+ x: rowHorizontalInset,+ y: stripTop,+ width: tileWidth,+ height: stripHeight+ )++ let scrollX = localTileView.frame.maxX + tileSpacing+ stripScrollView.isHidden = stripHeight == 0 || stripParticipantCount == 0+ stripScrollView.frame = CGRect(+ x: scrollX,+ y: stripTop,+ width: max(0, drawerView.bounds.width - scrollX - rowHorizontalInset),+ height: stripHeight+ )+ stripStackView.frame = CGRect(+ x: 0,+ y: 0,+ width: CGFloat(stripParticipantCount) * tileWidth + CGFloat(max(stripParticipantCount - 1, 0)) * tileSpacing,+ height: stripHeight+ )+ stripScrollView.contentSize = CGSize(width: stripStackView.frame.width, height: stripHeight)+ stripStackView.arrangedSubviews.forEach { $0.frame.size = CGSize(width: tileWidth, height: stripHeight) }++ switchCameraButton.frame = CGRect(+ x: localTileView.frame.maxX - 44,+ y: localTileView.frame.maxY - 44,+ width: 36,+ height: 36+ )+ switchCameraButton.isHidden = !isLocalVideoEnabled || localTileView.isHidden+ drawerView.bringSubviewToFront(switchCameraButton)+ controlsView.frame = CGRect(+ x: (drawerView.bounds.width - controlsSize.width) / 2,+ y: controlsTop,+ width: controlsSize.width,+ height: controlsSize.height+ )++ let thumbnailSize = CGSize(width: 160, height: 112)+ if thumbnailView.frame == .zero+ || thumbnailView.bounds.size != thumbnailSize+ || !bounds.insetBy(dx: -40, dy: -40).contains(thumbnailView.center) {+ thumbnailView.frame = thumbnailFrame(for: thumbnailCorner, size: thumbnailSize, in: bounds, safeAreaInsets: rootView.safeAreaInsets)+ }+ let thumbnailHalfWidth = thumbnailView.bounds.width / 2+ thumbnailLocalVideoView.frame = CGRect(x: 0, y: 0, width: thumbnailHalfWidth, height: thumbnailView.bounds.height)+ thumbnailLocalPlaceholderView.frame = thumbnailLocalVideoView.frame+ thumbnailLocalInitialsLabel.text = initials(from: localParticipantTitle)+ thumbnailLocalInitialsLabel.frame = CGRect(+ x: (thumbnailLocalPlaceholderView.bounds.width - 44) / 2,+ y: (thumbnailLocalPlaceholderView.bounds.height - 44) / 2,+ width: 44,+ height: 44+ )+ thumbnailRemoteVideoView.frame = CGRect(+ x: thumbnailHalfWidth,+ y: 0,+ width: thumbnailView.bounds.width - thumbnailHalfWidth,+ height: thumbnailView.bounds.height+ )+ thumbnailRemotePlaceholderView.frame = thumbnailRemoteVideoView.frame+ if let primaryRemoteParticipantTitle {+ thumbnailRemoteInitialsLabel.text = initials(from: primaryRemoteParticipantTitle)+ thumbnailRemoteInitialsLabel.font = .systemFont(ofSize: 18, weight: .semibold)+ thumbnailRemoteInitialsLabel.backgroundColor = theme.edgeMutedColor+ thumbnailRemoteInitialsLabel.layer.cornerRadius = 22+ thumbnailRemoteInitialsLabel.frame = CGRect(+ x: (thumbnailRemotePlaceholderView.bounds.width - 44) / 2,+ y: (thumbnailRemotePlaceholderView.bounds.height - 44) / 2,+ width: 44,+ height: 44+ )+ } else {+ thumbnailRemoteInitialsLabel.text = "No one\nelse is here"+ thumbnailRemoteInitialsLabel.font = .systemFont(ofSize: 11, weight: .semibold)+ thumbnailRemoteInitialsLabel.backgroundColor = .clear+ thumbnailRemoteInitialsLabel.layer.cornerRadius = 0+ thumbnailRemoteInitialsLabel.frame = thumbnailRemotePlaceholderView.bounds.insetBy(dx: 8, dy: 0)+ }+ thumbnailDividerView.frame = CGRect(x: thumbnailHalfWidth - 0.5, y: 0, width: 1, height: thumbnailView.bounds.height)++ edgeTabView.frame = CGRect(x: bounds.width - 34, y: bounds.midY - 36, width: 34, height: 72)+ edgeTabView.text = "‹"+ }++ private func initials(from title: String) -> String {+ let words = title+ .split { $0.isWhitespace || $0 == "@" || $0 == "." || $0 == "|" }+ .map(String.init)+ .filter { !$0.isEmpty && $0.lowercased() != "macro" }+ if words.count >= 2 {+ return "\(words[0].prefix(1))\(words[1].prefix(1))".uppercased()+ }+ if let first = words.first {+ return String(first.prefix(1)).uppercased()+ }+ return "?"+ }++ private func thumbnailFrame(+ for corner: ThumbnailCorner,+ size: CGSize,+ in bounds: CGRect,+ safeAreaInsets: UIEdgeInsets+ ) -> CGRect {+ let margin: CGFloat = 8+ let bottomOffset: CGFloat = 88+ let top = safeAreaInsets.top+ let bottom = bounds.height - safeAreaInsets.bottom - margin - size.height - bottomOffset+ let left = margin+ let right = bounds.width - margin - size.width++ switch corner {+ case .topLeft: return CGRect(origin: CGPoint(x: left, y: top), size: size)+ case .topRight: return CGRect(origin: CGPoint(x: right, y: top), size: size)+ case .bottomLeft: return CGRect(origin: CGPoint(x: left, y: bottom), size: size)+ case .bottomRight: return CGRect(origin: CGPoint(x: right, y: bottom), size: size)+ }+ }++ private func drawerFrame(in bounds: CGRect) -> CGRect {+ let drawerHeight = min(max(bounds.height * 0.8, 320), bounds.height - 72)+ return CGRect(x: 0, y: bounds.height - drawerHeight, width: bounds.width, height: drawerHeight)+ }++ private func nearestCorner(to center: CGPoint, in bounds: CGRect) -> ThumbnailCorner {+ let left = center.x < bounds.midX+ let top = center.y < bounds.midY+ switch (left, top) {+ case (true, true): return .topLeft+ case (false, true): return .topRight+ case (true, false): return .bottomLeft+ case (false, false): return .bottomRight+ }+ }++ @objc private func minimizeFromDrawer() {+ minimizeDrawerToThumbnail()+ }++ @objc private func expandFromThumbnail() {+ onOpenDrawerFromThumbnail?()+ setMode(.expanded)+ }++ @objc private func showThumbnailFromEdge() {+ setMode(.minimized)+ }++ @objc private func toggleMicrophone() {+ print("[CallKit] 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)")+ guard audioRoute.supportsSpeakerToggle else { return }+ onToggleSpeaker?()+ }++ @objc private func toggleCamera() {+ print("[CallKit] Native video overlay camera toggle tapped currentEnabled=\(isLocalVideoEnabled)")+ onToggleCamera?()+ }++ @objc private func switchCamera() {+ print("[CallKit] Native video overlay camera switch tapped")+ onSwitchCamera?()+ }++ @objc private func endCall() {+ print("[CallKit] Native video overlay end call tapped")+ onEndCall?()+ }++ @objc private func dragDrawer(_ recognizer: UIPanGestureRecognizer) {+ guard mode == .expanded else { return }++ switch recognizer.state {+ case .began:+ drawerPanStartFrame = drawerView.frame+ case .changed:+ let translation = recognizer.translation(in: rootView)+ let offset = max(0, translation.y)+ drawerView.frame = drawerPanStartFrame.offsetBy(dx: 0, dy: offset)+ case .ended, .cancelled, .failed:+ let translation = recognizer.translation(in: rootView)+ let velocity = recognizer.velocity(in: rootView)+ let shouldMinimize = translation.y > 96 || velocity.y > 700+ if shouldMinimize {+ minimizeDrawerToThumbnail()+ } else {+ UIView.animate(withDuration: 0.22, delay: 0, options: [.curveEaseOut]) {+ self.drawerView.frame = self.drawerFrame(in: self.rootView.bounds)+ }+ }+ default:+ break+ }+ }++ @objc private func dragThumbnail(_ recognizer: UIPanGestureRecognizer) {+ let translation = recognizer.translation(in: rootView)+ recognizer.setTranslation(.zero, in: rootView)+ thumbnailView.center = CGPoint(+ x: thumbnailView.center.x + translation.x,+ y: thumbnailView.center.y + translation.y+ )++ guard recognizer.state == .ended || recognizer.state == .cancelled else { return }++ let bounds = rootView.bounds+ if thumbnailView.center.x > bounds.width + 24 || thumbnailView.center.x < -24 {+ mode = .hidden+ layoutOverlay()+ return+ }++ thumbnailCorner = nearestCorner(to: thumbnailView.center, in: bounds)+ UIView.animate(withDuration: 0.2, delay: 0, options: [.curveEaseOut]) {+ self.thumbnailView.frame = self.thumbnailFrame(+ for: self.thumbnailCorner,+ size: self.thumbnailView.bounds.size,+ in: bounds,+ safeAreaInsets: self.rootView.safeAreaInsets+ )+ }+ }++ private func minimizeDrawerToThumbnail() {+ thumbnailCorner = .topRight+ thumbnailView.frame = .zero+ setMode(.minimized)+ }++ func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {+ guard gestureRecognizer.view === drawerView,+ let pan = gestureRecognizer as? UIPanGestureRecognizer else {+ return true+ }++ let velocity = pan.velocity(in: drawerView)+ return abs(velocity.y) > abs(velocity.x) && velocity.y > 0+ }++ func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {+ guard gestureRecognizer.view === drawerView else { return true }+ return !(touch.view is UIControl)+ }+}++private enum ThumbnailCorner {+ case topLeft+ case topRight+ case bottomLeft+ case bottomRight+}++private final class RemoteVideoTileView: UIControl {+ private let videoView = VideoView()+ private let placeholderView = UIView()+ private let initialsLabel = UILabel()+ private let label = UILabel()+ private let speakingIndicator = UIView()+ private let isMirrored: Bool+ private var theme = CallVideoOverlayTheme.fallback+ private var participantId: String?+ private var hasVideoTrack = false+ private var didInstallFixedSizeConstraints = false+ var onTap: ((String) -> Void)?++ init(frame: CGRect = .zero, isMirrored: Bool = false) {+ self.isMirrored = isMirrored+ super.init(frame: frame)+ configureViews()+ }++ required init?(coder: NSCoder) {+ self.isMirrored = false+ super.init(coder: coder)+ configureViews()+ }++ func configure(participant: NativeVideoParticipant, isPrimary: Bool) {+ participantId = participant.id+ hasVideoTrack = participant.track != nil+ videoView.track = participant.track+ placeholderView.isHidden = hasVideoTrack+ initialsLabel.text = initials(from: participant.avatarTitle ?? participant.title)+ label.text = participant.isScreenShare ? "Screen" : participant.title+ applyLabelBackground()+ speakingIndicator.isHidden = !participant.isSpeaking+ layer.borderColor = (isPrimary ? theme.edgeColor : theme.edgeMutedColor).cgColor+ layer.borderWidth = isPrimary ? 2 : 1+ setNeedsLayout()+ }++ func prepareForRemoval() {+ videoView.track = nil+ placeholderView.isHidden = false+ onTap = nil+ participantId = nil+ hasVideoTrack = false+ applyLabelBackground()+ }++ func applyTheme(_ theme: CallVideoOverlayTheme) {+ self.theme = theme+ backgroundColor = theme.messageBackgroundColor+ videoView.backgroundColor = theme.messageBackgroundColor+ placeholderView.backgroundColor = theme.messageBackgroundColor+ initialsLabel.textColor = theme.textColor+ initialsLabel.backgroundColor = theme.edgeMutedColor+ label.textColor = theme.textColor+ applyLabelBackground()+ speakingIndicator.backgroundColor = theme.successColor+ }++ func ensureFixedSize() {+ guard !didInstallFixedSizeConstraints else { return }+ didInstallFixedSizeConstraints = true+ widthAnchor.constraint(equalToConstant: 128).isActive = true+ heightAnchor.constraint(equalToConstant: 92).isActive = true+ }++ private func configureViews() {+ backgroundColor = theme.messageBackgroundColor+ layer.cornerRadius = 6+ clipsToBounds = true++ videoView.layoutMode = .fill+ videoView.mirrorMode = isMirrored ? .auto : .off+ videoView.backgroundColor = theme.messageBackgroundColor+ addSubview(videoView)++ placeholderView.backgroundColor = CallVideoOverlayTheme.fallback.messageBackgroundColor+ addSubview(placeholderView)++ initialsLabel.textColor = CallVideoOverlayTheme.fallback.textColor+ initialsLabel.textAlignment = .center+ initialsLabel.font = .systemFont(ofSize: 18, weight: .semibold)+ initialsLabel.backgroundColor = CallVideoOverlayTheme.fallback.edgeMutedColor+ initialsLabel.layer.cornerRadius = 22+ initialsLabel.clipsToBounds = true+ placeholderView.addSubview(initialsLabel)++ label.textColor = CallVideoOverlayTheme.fallback.textColor+ label.font = .systemFont(ofSize: 12, weight: .semibold)+ label.lineBreakMode = .byTruncatingTail+ label.backgroundColor = CallVideoOverlayTheme.fallback.edgeMutedColor+ label.textAlignment = .center+ addSubview(label)++ speakingIndicator.backgroundColor = CallVideoOverlayTheme.fallback.successColor+ speakingIndicator.layer.cornerRadius = 4+ addSubview(speakingIndicator)++ addTarget(self, action: #selector(tapped), for: .touchUpInside)+ }++ private func applyLabelBackground() {+ label.backgroundColor = hasVideoTrack+ ? theme.drawerBackgroundColor.withAlphaComponent(0.70)+ : theme.edgeMutedColor+ }++ override func layoutSubviews() {+ super.layoutSubviews()+ videoView.frame = bounds+ placeholderView.frame = bounds+ initialsLabel.frame = CGRect(+ x: (bounds.width - 44) / 2,+ y: (bounds.height - 44) / 2,+ width: 44,+ height: 44+ )+ let labelHeight: CGFloat = 22+ let labelY = bounds.height - 26+ let labelSize = label.sizeThatFits(CGSize(width: bounds.width - 12, height: labelHeight))+ let labelWidth = min(max(0, bounds.width - 12), labelSize.width + 12)+ label.frame = CGRect(x: 6, y: labelY, width: labelWidth, height: labelHeight)+ label.layer.cornerRadius = 8+ label.clipsToBounds = true+ speakingIndicator.frame = CGRect(x: bounds.width - 14, y: 8, width: 8, height: 8)+ }++ private func initials(from title: String) -> String {+ let words = title+ .split { $0.isWhitespace || $0 == "@" || $0 == "." || $0 == "|" }+ .map(String.init)+ .filter { !$0.isEmpty && $0.lowercased() != "macro" }+ if words.count >= 2 {+ return "\(words[0].prefix(1))\(words[1].prefix(1))".uppercased()+ }+ if let first = words.first {+ return String(first.prefix(1)).uppercased()+ }+ return "?"+ }++ @objc private func tapped() {+ guard let participantId else { return }+ onTap?(participantId)+ }+}++private final class PassthroughOverlayView: UIView {+ var onLayout: (() -> Void)?+ var blocksBackgroundTouches = false++ override func layoutSubviews() {+ super.layoutSubviews()+ onLayout?()+ }++ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {+ let hit = super.hitTest(point, with: event)+ if hit === self {+ return blocksBackgroundTouches ? self : nil+ }+ return hit+ }+}diff --git a/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift b/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swiftnew file mode 100644index 0000000000..7601e09a94--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/IncomingCallCoordinator.swift@@ -0,0 +1,502 @@+import AVFAudio+import CallKit+import Foundation+import PushKit++private let enableNativeLiveKitAnswer = true++/// PushKit + CallKit coordinator. Mutable state is main-queue only.+final class IncomingCallCoordinator: NSObject, CXProviderDelegate, PKPushRegistryDelegate, @unchecked Sendable {+ private let mediaSessionProvider: () -> NativeLiveKitCallSession+ private let onVoipTokenUpdated: (String) -> Void+ private let onCallAnswered: (String, Bool) -> Void+ private let onCallEnded: (String) -> Void++ private var provider: CXProvider!+ private var providerConfiguration: CXProviderConfiguration!+ private let callController = CXCallController()+ private var registry: PKPushRegistry!++ private var pendingCalls: [UUID: PendingCallInfo] = [:]+ private var pendingCallTokens: [UUID: PendingCallToken] = [:]+ private var activeCallUUID: UUID?+ private var activeNativeMediaUUID: UUID?+ private var isCallKitAudioSessionActive = false+ private var outgoingCallUUIDs: Set<UUID> = []+ private var reportedConnectedOutgoingCallUUIDs: Set<UUID> = []+ private var cachedVoipToken: String?+ private var pendingAnsweredCall: (channelId: String, nativeMedia: Bool)?++ init(+ mediaSession: @escaping () -> NativeLiveKitCallSession,+ onVoipTokenUpdated: @escaping (String) -> Void,+ onCallAnswered: @escaping (String, Bool) -> Void,+ onCallEnded: @escaping (String) -> Void+ ) {+ self.mediaSessionProvider = mediaSession+ self.onVoipTokenUpdated = onVoipTokenUpdated+ self.onCallAnswered = onCallAnswered+ self.onCallEnded = onCallEnded+ }++ func load() {+ print("[CallKit] Loading PushKit/CallKit coordinator")+ let config = makeProviderConfiguration()++ providerConfiguration = config+ provider = CXProvider(configuration: config)+ provider.setDelegate(self, queue: .main)++ registry = PKPushRegistry(queue: .main)+ registry.delegate = self+ registry.desiredPushTypes = [.voIP]+ print("[CallKit] PushKit registry configured for VoIP pushes")+ }++ func getVoipToken() -> String? {+ cachedVoipToken+ }++ func drainPendingAnsweredCall() -> (channelId: String, nativeMedia: Bool)? {+ let answeredCall = pendingAnsweredCall+ pendingAnsweredCall = nil+ return answeredCall+ }++ func startOutgoingCall(+ uuid: UUID,+ channelId: String,+ channelName: String?,+ callerName: String?,+ serverUrl: String,+ token: String,+ completion: @escaping (Error?) -> Void+ ) {+ if let activeCallUUID, activeCallUUID != uuid {+ print("[CallKit] startOutgoingCall rejected; active call already exists activeUuid=\(activeCallUUID.uuidString) requestedUuid=\(uuid.uuidString)")+ completion(NSError(+ domain: "CallKitPlugin",+ code: 1,+ userInfo: [NSLocalizedDescriptionKey: "A CallKit call is already active"]+ ))+ return+ }++ let title = channelName?.trimmingCharacters(in: .whitespacesAndNewlines)+ let displayTitle = title?.isEmpty == false ? title : nil+ pendingCalls[uuid] = PendingCallInfo(+ channelId: channelId,+ channelName: displayTitle,+ callerName: callerName+ )+ pendingCallTokens[uuid] = PendingCallToken(serverUrl: serverUrl, token: token)+ activeCallUUID = uuid+ activeNativeMediaUUID = uuid+ outgoingCallUUIDs.insert(uuid)+ reportedConnectedOutgoingCallUUIDs.remove(uuid)+ mediaSessionProvider().setChannelTitle(displayTitle)+ activateNativeMediaAudioIfNeeded(reason: "outgoing call prepared")++ let handle = CXHandle(type: .generic, value: displayTitle ?? channelId)+ let action = CXStartCallAction(call: uuid, handle: handle)+ action.isVideo = true+ let transaction = CXTransaction(action: action)+ print("[CallKit] Requesting CXStartCallAction uuid=\(uuid.uuidString) channelId=\(channelId) channelName=\(displayTitle ?? "nil")")+ callController.request(transaction) { [weak self] error in+ DispatchQueue.main.async {+ if let error {+ print("[CallKit] CXStartCallAction request failed uuid=\(uuid.uuidString) error=\(error)")+ self?.clearCallState(uuid: uuid)+ } else {+ print("[CallKit] CXStartCallAction request accepted uuid=\(uuid.uuidString)")+ }+ completion(error)+ }+ }+ }++ func reportNativeCallConnected(uuid: UUID) {+ guard 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)")+ provider.reportOutgoingCall(with: uuid, connectedAt: Date())+ }++ func endActiveCall(completion: @escaping () -> Void) {+ guard let uuid = activeCallUUID else {+ print("[CallKit] endActiveCall requested with no active CallKit UUID")+ completion()+ return+ }++ print("[CallKit] endActiveCall requesting CXEndCallAction uuid=\(uuid.uuidString)")+ requestEndCall(uuid: uuid) { [weak self] error in+ guard let self else {+ completion()+ return+ }+ self.onMain {+ if error != nil {+ print("[CallKit] CXEndCallAction failed; clearing local state uuid=\(uuid.uuidString)")+ let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid+ self.clearCallState(uuid: uuid)+ if shouldDisconnectNativeMedia {+ let mediaSession = self.mediaSessionProvider()+ Task {+ await mediaSession.disconnect()+ }+ }+ }+ completion()+ }+ }+ }++ func requestEndCall(uuid: UUID) {+ print("[CallKit] requestEndCall uuid=\(uuid.uuidString)")+ requestEndCall(uuid: uuid) { [weak self] error in+ guard let self, error != nil else { return }+ self.onMain {+ print("[CallKit] requestEndCall failed; disconnecting media session uuid=\(uuid.uuidString)")+ let shouldDisconnectNativeMedia = self.activeNativeMediaUUID == uuid+ self.clearCallState(uuid: uuid)+ if shouldDisconnectNativeMedia {+ let mediaSession = self.mediaSessionProvider()+ Task {+ await mediaSession.disconnect()+ }+ }+ }+ }+ }++ func handleApplicationWillTerminate() {+ guard let uuid = activeCallUUID else {+ print("[CallKit] Application terminating with no active CallKit call")+ return+ }++ print("[CallKit] Application terminating with active CallKit call uuid=\(uuid.uuidString)")+ let shouldDisconnectNativeMedia = activeNativeMediaUUID == uuid+ if shouldDisconnectNativeMedia {+ mediaSessionProvider().disconnectForAppTermination()+ }+ provider.reportCall(with: uuid, endedAt: Date(), reason: .remoteEnded)+ clearCallState(uuid: uuid)+ }++ private func requestEndCall(uuid: UUID, completion: @escaping (Error?) -> Void) {+ let transaction = CXTransaction(action: CXEndCallAction(call: uuid))+ callController.request(transaction) { error in+ if let error {+ print("[CallKit] CXEndCallAction request failed: \(error)")+ }+ completion(error)+ }+ }++ func pushRegistry(+ _ registry: PKPushRegistry,+ didUpdate pushCredentials: PKPushCredentials,+ for type: PKPushType+ ) {+ guard 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)")+ onVoipTokenUpdated(token)+ }++ func pushRegistry(+ _ registry: PKPushRegistry,+ didReceiveIncomingPushWith payload: PKPushPayload,+ for type: PKPushType,+ completion: @escaping () -> Void+ ) {+ guard type == .voIP else {+ completion()+ return+ }++ let dict = payload.dictionaryPayload+ let channelId = dict["channelId"] as? String ?? ""+ let channelName = dict["channelName"] as? String+ let callerName = dict["callerName"] as? String ?? "Incoming Call"+ let callIdString = dict["callId"] as? String ?? ""+ let livekitServerUrl = dict["livekitServerUrl"] as? String+ let livekitToken = dict["livekitToken"] as? String+ let hasNativeCredentials = livekitServerUrl != nil && livekitToken != nil+ print("[CallKit] Received VoIP push callId=\(callIdString) channelId=\(channelId) channelName=\(channelName ?? "nil") hasNativeCredentials=\(hasNativeCredentials)")++ guard let uuid = UUID(uuidString: callIdString) else {+ // PushKit requires every VoIP push to be reported to CallKit.+ let safePayloadKeys = dict.keys+ .compactMap { $0 as? String }+ .filter { $0 != "livekitServerUrl" && $0 != "livekitToken" }+ .sorted()+ print("[CallKit] 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+ self?.provider.reportCall(with: fallbackUUID, endedAt: nil, reason: .failed)+ completion()+ }+ return+ }++ // Copy keys before mutating; Dictionary.Keys is a live view.+ for staleUUID in Array(pendingCalls.keys) where staleUUID != uuid {+ print("[CallKit] Marking stale pending call failed uuid=\(staleUUID.uuidString)")+ provider.reportCall(with: staleUUID, endedAt: nil, reason: .failed)+ pendingCalls.removeValue(forKey: staleUUID)+ pendingCallTokens.removeValue(forKey: staleUUID)+ }++ pendingCalls[uuid] = PendingCallInfo(+ channelId: channelId,+ channelName: channelName,+ callerName: callerName+ )+ if let serverUrl = livekitServerUrl, let token = livekitToken {+ pendingCallTokens[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")+ }+ activeCallUUID = uuid++ let update = CXCallUpdate()+ update.remoteHandle = CXHandle(type: .generic, value: channelName ?? channelId)+ update.localizedCallerName = callerName+ update.hasVideo = true++ // Must happen from the PushKit delegate; otherwise iOS can terminate us.+ applyProviderConfiguration(reason: "incoming call report")+ provider.reportNewIncomingCall(with: uuid, update: update) { [weak self] error in+ if error != nil {+ print("[CallKit] reportNewIncomingCall failed uuid=\(uuid.uuidString) error=\(String(describing: error))")+ self?.pendingCalls.removeValue(forKey: uuid)+ self?.pendingCallTokens.removeValue(forKey: uuid)+ if self?.activeCallUUID == uuid { self?.activeCallUUID = nil }+ } else {+ print("[CallKit] reportNewIncomingCall succeeded uuid=\(uuid.uuidString)")+ }+ completion()+ }+ }++ func providerDidReset(_ provider: CXProvider) {+ print("[CallKit] CXProvider reset; clearing CallKit and media state")+ pendingCalls.removeAll()+ pendingCallTokens.removeAll()+ activeCallUUID = nil+ isCallKitAudioSessionActive = false+ pendingAnsweredCall = nil+ outgoingCallUUIDs.removeAll()+ reportedConnectedOutgoingCallUUIDs.removeAll()+ if activeNativeMediaUUID != nil {+ activeNativeMediaUUID = nil+ let mediaSession = mediaSessionProvider()+ Task {+ await mediaSession.disconnect()+ }+ }+ }++ func provider(_ provider: CXProvider, perform action: CXStartCallAction) {+ let uuid = action.callUUID+ print("[CallKit] 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)")+ action.fail()+ clearCallState(uuid: uuid)+ return+ }++ activeCallUUID = uuid+ activeNativeMediaUUID = uuid+ provider.reportOutgoingCall(with: uuid, startedConnectingAt: Date())+ action.fulfill()+ print("[CallKit] Fulfilled CXStartCallAction uuid=\(uuid.uuidString)")++ Task { @MainActor [weak self] in+ guard let self else { return }+ guard self.canStartNativeMediaConnect(uuid: uuid),+ self.pendingCalls[uuid] != nil,+ self.pendingCallTokens[uuid] != nil else {+ print("[CallKit] 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)")+ mediaSession.connect(+ uuid: uuid,+ channelId: pendingCall.channelId,+ serverUrl: pendingToken.serverUrl,+ token: pendingToken.token+ )+ }+ }++ func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {+ print("[CallKit] CXAnswerCallAction received uuid=\(action.callUUID.uuidString)")+ guard let pendingCall = pendingCalls[action.callUUID] else {+ print("[CallKit] Answer failed: no pending channel for uuid=\(action.callUUID.uuidString)")+ action.fail()+ return+ }+ let channelId = pendingCall.channelId++ let answeredUUID = action.callUUID+ let pendingToken = pendingCallTokens[answeredUUID]+ let shouldConnectNatively = enableNativeLiveKitAnswer && pendingToken != nil+ if shouldConnectNatively {+ activeNativeMediaUUID = answeredUUID+ print("[CallKit] 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)")+ } else {+ print("[CallKit] No cached LiveKit token for answered call \(answeredUUID.uuidString); JS-driven join required")+ }++ pendingAnsweredCall = (channelId: channelId, nativeMedia: shouldConnectNatively)++ // Keep activeCallUUID so JS can still request CXEndCallAction.+ pendingCalls.removeValue(forKey: answeredUUID)+ pendingCallTokens.removeValue(forKey: answeredUUID)++ print("[CallKit] Fulfilling CXAnswerCallAction uuid=\(answeredUUID.uuidString)")+ applyProviderConfiguration(reason: "answer action fulfillment")+ action.fulfill()+ print("[CallKit] Fulfilled CXAnswerCallAction uuid=\(answeredUUID.uuidString)")++ if shouldConnectNatively, let pendingToken {+ Task { @MainActor [weak self] in+ guard let self else { return }+ print("[CallKit] 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)")+ 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")+ mediaSession.connect(+ uuid: answeredUUID,+ channelId: channelId,+ serverUrl: pendingToken.serverUrl,+ token: pendingToken.token+ )+ }+ }++ 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)+ }+ }++ func provider(_ provider: CXProvider, perform action: CXEndCallAction) {+ let callId = action.callUUID.uuidString+ print("[CallKit] CXEndCallAction received uuid=\(callId)")+ onCallEnded(callId)++ if activeNativeMediaUUID == action.callUUID {+ let mediaSession = mediaSessionProvider()+ Task {+ await mediaSession.disconnect()+ }+ }++ action.fulfill()+ print("[CallKit] Fulfilled CXEndCallAction uuid=\(callId)")+ clearCallState(uuid: action.callUUID)+ }++ func provider(_ provider: CXProvider, didActivate audioSession: AVAudioSession) {+ isCallKitAudioSessionActive = true+ guard activeNativeMediaUUID != nil else {+ print("[CallKit] AVAudioSession activated by CallKit; native media not active yet")+ return+ }+ print("[CallKit] AVAudioSession activated by CallKit for native media")+ mediaSessionProvider().activateAudioEngine(reason: "provider didActivate", audioSession: audioSession)+ }++ func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {+ isCallKitAudioSessionActive = false+ guard activeNativeMediaUUID != nil else {+ print("[CallKit] AVAudioSession deactivated by CallKit; no native media session active")+ return+ }+ print("[CallKit] 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)")+ }++ private func clearCallState(uuid: UUID) {+ print("[CallKit] Clearing call state uuid=\(uuid.uuidString)")+ pendingCalls.removeValue(forKey: uuid)+ pendingCallTokens.removeValue(forKey: uuid)+ if activeCallUUID == uuid { activeCallUUID = nil }+ if activeNativeMediaUUID == uuid { activeNativeMediaUUID = nil }+ outgoingCallUUIDs.remove(uuid)+ reportedConnectedOutgoingCallUUIDs.remove(uuid)+ pendingAnsweredCall = nil+ }++ private func activateNativeMediaAudioIfNeeded(reason: String) {+ guard activeNativeMediaUUID != nil else { return }+ guard isCallKitAudioSessionActive else {+ print("[CallKit] Native media waiting for CallKit AVAudioSession activation reason=\(reason)")+ return+ }+ print("[CallKit] Applying existing CallKit AVAudioSession activation to native media reason=\(reason) \(describeCurrentAudioRoute())")+ mediaSessionProvider().activateAudioEngine(reason: reason)+ }++ private func canStartNativeMediaConnect(uuid: UUID) -> Bool {+ activeCallUUID == uuid && activeNativeMediaUUID == uuid+ }++ private func makeProviderConfiguration() -> CXProviderConfiguration {+ let config = CXProviderConfiguration()+ config.supportsVideo = true+ config.maximumCallsPerCallGroup = 1+ config.supportedHandleTypes = [.generic]+ return config+ }++ private func applyProviderConfiguration(reason: String) {+ let config = providerConfiguration ?? makeProviderConfiguration()+ providerConfiguration = config+ print("[CallKit] 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: ",")+ return "audioRoute(inputs=[\(inputs)], outputs=[\(outputs)])"+ }++ private func onMain(_ block: @escaping () -> Void) {+ if Thread.isMainThread {+ block()+ } else {+ DispatchQueue.main.async(execute: block)+ }+ }+}diff --git a/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift b/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swiftnew file mode 100644index 0000000000..f06804d83b--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/NativeLiveKitCallSession.swift@@ -0,0 +1,1087 @@+import AVFAudio+import AVFoundation+import Foundation+import LiveKit+import LiveKitWebRTC+import UIKit++/// Native LiveKit Room plus CallKit-owned audio-session integration.+final class NativeLiveKitCallSession: NSObject, RoomDelegate, @unchecked Sendable {+ private let onSnapshotChanged: (ActiveCallSnapshot?) -> Void+ private let requestSystemEndCall: (UUID) -> Void+ private let onDrawerOpened: (String) -> Void+ private let onParticipantIdentitiesChanged: ([String]) -> Void+ private let videoOverlay: CallVideoOverlayController+ private lazy var pictureInPicture: CallPictureInPictureManaging = makeCallPictureInPictureController(+ sourceViewProvider: { [weak self] in+ self?.videoOverlay.pictureInPictureSourceView()+ },+ onRestore: { [weak self] in+ guard let self else { return }+ self.setVideoOverlayMode(.expanded)+ if let channelId = self.activeCall?.channelId {+ print("[CallKit] Picture in Picture restoring channelId=\(channelId)")+ self.onDrawerOpened(channelId)+ }+ }+ )++ private var room: Room?+ private var connectTask: Task<Void, Never>?+ private var activeCallUUID: UUID?+ private var activeCall: ActiveCallSnapshot?+ private var pinnedRemoteVideoParticipantId: String?+ private var speakingRemoteParticipantIds: [String] = []+ private var participantDisplayNamesByIdentity: [String: String] = [:]+ private var didPrepareAudio = false+ private var isCallKitAudioActive = false+ private var isActivatingAudioEngine = false+ private var desiredAudioMuted = false+ private let audioEngineLogger = CallKitAudioEngineLogger()+ private let audioRouteController = CallAudioRouteController()++ init(+ onSnapshotChanged: @escaping (ActiveCallSnapshot?) -> Void,+ requestSystemEndCall: @escaping (UUID) -> Void,+ onDrawerOpened: @escaping (String) -> Void,+ onParticipantIdentitiesChanged: @escaping ([String]) -> Void,+ videoOverlay: CallVideoOverlayController+ ) {+ self.onSnapshotChanged = onSnapshotChanged+ self.requestSystemEndCall = requestSystemEndCall+ self.onDrawerOpened = onDrawerOpened+ self.onParticipantIdentitiesChanged = onParticipantIdentitiesChanged+ self.videoOverlay = videoOverlay+ super.init()+ audioEngineLogger.desiredMutedProvider = { [weak self] in+ self?.desiredAudioMuted+ }+ configureLiveKitAudioForCallKit()+ videoOverlay.onToggleMicrophone = { [weak self] in+ self?.toggleAudioFromOverlay()+ }+ videoOverlay.onToggleSpeaker = { [weak self] in+ self?.toggleSpeakerFromOverlay()+ }+ videoOverlay.onToggleCamera = { [weak self] in+ self?.toggleVideoFromOverlay()+ }+ videoOverlay.onSwitchCamera = { [weak self] in+ self?.switchCamera()+ }+ videoOverlay.onEndCall = { [weak self] in+ self?.endCallFromOverlay()+ }+ videoOverlay.onSelectRemoteParticipant = { [weak self] participantId in+ self?.togglePinnedRemoteVideoParticipant(participantId)+ }+ videoOverlay.onOpenDrawerFromThumbnail = { [weak self] in+ guard let channelId = self?.activeCall?.channelId else { return }+ print("[CallKit] 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)")+ self?.updateVideoOverlayMode(mode.rawValue)+ self?.pictureInPicture.prepare()+ }+ audioRouteController.onRouteChanged = { [weak self] route in+ guard let self else { return }+ self.videoOverlay.setAudioRoute(route)+ guard self.activeCallUUID != nil else { return }+ if self.isCallKitAudioActive, !AudioManager.shared.engineAvailability.isOutputAvailable {+ self.activateAudioEngine(reason: "audio route changed")+ } else if self.canEnableMicrophoneAudio() {+ self.enableMicrophoneAfterAudioActivationIfNeeded(reason: "audio route changed")+ }+ }+ audioRouteController.startObserving()+ pictureInPicture.prepare()+ print("[CallKit] NativeLiveKitCallSession initialized")+ }++ func prepareForCallKitAudio() {+ guard !didPrepareAudio else { return }+ didPrepareAudio = true++ print("[CallKit] Prepared LiveKit audio for CallKit-controlled activation")+ configureAudioSessionCategory(reason: "prepareForCallKitAudio")+ }++ private func configureLiveKitAudioForCallKit() {+ AudioManager.shared.audioSession.isAutomaticConfigurationEnabled = false+ AudioManager.shared.audioSession.isAutomaticDeactivationEnabled = false+ AudioManager.shared.set(engineObservers: [+ AudioManager.shared.audioSession,+ audioEngineLogger,+ AudioManager.shared.mixer,+ ])+ do {+ try AudioManager.shared.setEngineAvailability(.none)+ print("[CallKit] Configured LiveKit audio for CallKit engine gating")+ } catch {+ print("[CallKit] Failed to gate LiveKit audio engine before CallKit activation: \(error)")+ }+ }++ func configureAudioSessionCategory(reason: String) {+ let session = AVAudioSession.sharedInstance()+ do {+ try session.setCategory(+ .playAndRecord,+ mode: .voiceChat,+ options: [.allowBluetoothHFP, .mixWithOthers]+ )+ try session.setPreferredIOBufferDuration(0.02)+ print("[CallKit] Configured AVAudioSession category for voice call reason=\(reason) \(describeAudioSession())")+ audioRouteController.emitCurrentRoute()+ if hasUsableAudioOutputRoute() {+ audioRouteController.defaultToSpeakerIfBuiltInRoute(reason: "audioSessionCategoryConfigured")+ } else {+ print("[CallKit] Skipping built-in speaker default because AVAudioSession route is not ready reason=\(reason) \(describeAudioSession())")+ }+ } catch {+ print("[CallKit] Failed to set audio session category reason=\(reason): \(error) \(describeAudioSession())")+ }+ }++ func activateAudioEngine(reason: String = "CallKit didActivate", audioSession: AVAudioSession? = nil) {+ guard !isActivatingAudioEngine else {+ print("[CallKit] Ignoring nested LiveKit audio engine activation reason=\(reason)")+ return+ }+ isActivatingAudioEngine = true+ defer { isActivatingAudioEngine = false }++ configureAudioSessionCategory(reason: reason)+ if !hasUsableAudioOutputRoute() {+ print("[CallKit] 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)")+ }+ let availability = callKitAudioEngineAvailability()+ print("[CallKit] 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())")+ enableMicrophoneAfterAudioActivationIfNeeded(reason: reason)+ } catch {+ print("[CallKit] Failed to enable LiveKit audio engine after CallKit activation reason=\(reason): \(error) \(describeAudioSession())")+ }+ }++ func deactivateAudioEngine(audioSession: AVAudioSession? = nil) {+ isCallKitAudioActive = false+ do {+ if let audioSession {+ LKRTCAudioSession.sharedInstance().audioSessionDidDeactivate(audioSession)+ print("[CallKit] Notified LiveKit WebRTC audio session didDeactivate")+ }+ print("[CallKit] 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())")+ } catch {+ print("[CallKit] Failed to disable LiveKit audio engine after CallKit deactivation: \(error) \(describeAudioSession())")+ }+ }++ func currentSnapshot() -> ActiveCallSnapshot? {+ activeCall+ }++ func currentParticipantIdentities() -> [String] {+ guard let room else { return [] }+ return participantIdentities(from: room)+ }++ func connect(uuid: UUID, channelId: String, serverUrl: String, token: String) {+ print("[CallKit] Native LiveKit connect requested uuid=\(uuid.uuidString) channelId=\(channelId)")+ prepareForCallKitAudio()+ audioRouteController.prepareForCall()++ print("[CallKit] Creating LiveKit Room uuid=\(uuid.uuidString)")+ let newRoom = Room(+ delegate: self,+ roomOptions: RoomOptions(suspendLocalVideoTracksInBackground: false)+ )+ print("[CallKit] Created LiveKit Room uuid=\(uuid.uuidString)")++ activeCallUUID = uuid+ activeCall = ActiveCallSnapshot(+ channelId: channelId,+ callId: uuid.uuidString,+ connectionState: "connecting",+ isAudioMuted: false,+ isVideoMuted: true,+ videoOverlayMode: "hidden"+ )+ desiredAudioMuted = false+ pinnedRemoteVideoParticipantId = nil+ speakingRemoteParticipantIds = []+ videoOverlay.setAudioMuted(false)+ videoOverlay.setLocalVideoEnabled(false)+ emitSnapshot()++ connectTask?.cancel()+ let oldRoom = room+ room = newRoom++ connectTask = Task { [weak self, oldRoom, weak newRoom] in+ guard let self else { return }+ if let oldRoom {+ print("[CallKit] Disconnecting previous LiveKit room before new connect uuid=\(uuid.uuidString)")+ await oldRoom.disconnect()+ print("[CallKit] Previous LiveKit room disconnected uuid=\(uuid.uuidString)")+ }+ guard let newRoom else { return }+ do {+ print("[CallKit] Connecting LiveKit room uuid=\(uuid.uuidString)")+ try await newRoom.connect(url: serverUrl, token: token)+ guard self.activeCallUUID == uuid, self.room === newRoom else {+ print("[CallKit] Ignoring LiveKit connect completion for stale room uuid=\(uuid.uuidString)")+ return+ }+ 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))")+ for participant in newRoom.remoteParticipants.values {+ print("[CallKit] LiveKit existing remote participant \(self.describeParticipant(participant))")+ }+ self.emitParticipantIdentities(from: newRoom)+ await self.videoOverlay.setLocalParticipantTitle(self.displayTitle(newRoom.localParticipant))+ await self.videoOverlay.presentForActiveCallIfNeeded()+ self.rebuildRemoteVideoLayout(from: newRoom)+ } catch is CancellationError {+ print("[CallKit] LiveKit connect task cancelled uuid=\(uuid.uuidString)")+ return+ } catch {+ print("[CallKit] Failed to connect LiveKit room: \(error)")+ DispatchQueue.main.async { [weak self, weak newRoom] in+ guard let self, self.activeCallUUID == uuid, self.room === newRoom else { return }+ self.requestSystemEndCall(uuid)+ }+ return+ }++ do {+ guard await self.ensureMicrophonePermission(uuid: uuid) else {+ self.updateAudioMuted(true, room: newRoom, uuid: uuid)+ return+ }++ print("[CallKit] Enabling LiveKit microphone uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")+ guard self.canEnableMicrophoneAudio() else {+ print("[CallKit] Deferring LiveKit microphone enable until CallKit audio engine is ready uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")+ return+ }+ let microphoneWarning = Task {+ try? await Task.sleep(nanoseconds: 5_000_000_000)+ if !Task.isCancelled {+ print("[CallKit] Still waiting for LiveKit microphone enable uuid=\(uuid.uuidString) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ }+ }+ defer { microphoneWarning.cancel() }+ try await newRoom.localParticipant.setMicrophone(enabled: true)+ self.updateAudioMuted(false, room: newRoom, uuid: uuid)+ print("[CallKit] LiveKit microphone enabled uuid=\(uuid.uuidString) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ } catch is CancellationError {+ print("[CallKit] LiveKit microphone enable cancelled uuid=\(uuid.uuidString)")+ return+ } catch {+ print("[CallKit] Failed to enable LiveKit microphone; keeping room connected uuid=\(uuid.uuidString) error=\(error) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) callKitAudioActive=\(self.isCallKitAudioActive) \(self.describeAudioSession())")+ self.updateAudioMuted(true, room: newRoom, uuid: uuid)+ }+ }+ }++ func disconnect() async {+ print("[CallKit] 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")+ } else {+ print("[CallKit] Native LiveKit disconnect had no active room")+ }+ }++ func disconnectForAppTermination() {+ print("[CallKit] Native LiveKit app termination disconnect requested")+ let backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "CallKitLiveKitDisconnectOnTerminate") {+ print("[CallKit] Native LiveKit app termination disconnect background task expired")+ }++ Task { @MainActor [weak self] in+ guard let self else {+ if backgroundTask != .invalid {+ UIApplication.shared.endBackgroundTask(backgroundTask)+ }+ return+ }++ let toDisconnect = self.clearNativeCallState(deactivateAudio: true)+ if let toDisconnect {+ await toDisconnect.disconnect()+ print("[CallKit] Native LiveKit room disconnected for app termination")+ } else {+ print("[CallKit] Native LiveKit app termination disconnect had no active room")+ }++ if backgroundTask != .invalid {+ UIApplication.shared.endBackgroundTask(backgroundTask)+ }+ }+ }++ func setAudioMuted(_ muted: Bool) {+ guard let room, let uuid = activeCallUUID else {+ print("[CallKit] setAudioMuted ignored; no active native room muted=\(muted)")+ return+ }++ desiredAudioMuted = muted+ print("[CallKit] Native LiveKit desired microphone muted=\(muted) uuid=\(uuid.uuidString) currentSnapshotMuted=\(activeCall?.isAudioMuted.description ?? "nil")")++ Task { [weak self, weak room] in+ guard let self, let room else { return }++ do {+ if muted {+ print("[CallKit] Applying native LiveKit microphone muted=true uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")+ try await room.localParticipant.setMicrophone(enabled: false)+ self.updateAudioMuted(true, room: room, uuid: uuid)+ print("[CallKit] Native LiveKit microphone muted uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")+ return+ }++ guard await self.ensureMicrophonePermission(uuid: uuid) else {+ self.updateAudioMuted(true, room: room, uuid: uuid)+ return+ }++ print("[CallKit] Applying native LiveKit microphone muted=false uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ guard self.canEnableMicrophoneAudio() else {+ print("[CallKit] Deferring native LiveKit microphone unmute until CallKit audio engine is ready uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ return+ }+ try await room.localParticipant.setMicrophone(enabled: true)+ self.updateAudioMuted(false, room: room, uuid: uuid)+ print("[CallKit] Native LiveKit microphone unmuted uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted)")+ } catch {+ print("[CallKit] Failed to set native LiveKit microphone muted=\(muted) uuid=\(uuid.uuidString) desiredMuted=\(self.desiredAudioMuted): \(error)")+ self.updateAudioMuted(true, room: room, uuid: uuid)+ }+ }+ }++ func setParticipantDisplayName(identity: String, displayName: String?) {+ let trimmedIdentity = identity.trimmingCharacters(in: .whitespacesAndNewlines)+ let normalizedIdentity = normalizedParticipantIdentity(trimmedIdentity)+ let trimmedName = displayName?.trimmingCharacters(in: .whitespacesAndNewlines)+ if let trimmedName, !trimmedName.isEmpty {+ participantDisplayNamesByIdentity[trimmedIdentity] = trimmedName+ participantDisplayNamesByIdentity[normalizedIdentity] = trimmedName+ } else {+ participantDisplayNamesByIdentity.removeValue(forKey: trimmedIdentity)+ participantDisplayNamesByIdentity.removeValue(forKey: normalizedIdentity)+ }++ print("[CallKit] Native LiveKit participant display name set identity=\(trimmedIdentity) normalizedIdentity=\(normalizedIdentity) displayName=\(participantDisplayNamesByIdentity[normalizedIdentity] ?? "nil")")+ if let room {+ videoOverlay.setLocalParticipantTitle(displayTitle(room.localParticipant))+ rebuildRemoteVideoLayout(from: room)+ }+ }++ func setChannelTitle(_ title: String?) {+ videoOverlay.setChannelTitle(title)+ }++ func setVideoEnabled(_ enabled: Bool) {+ guard let room, let uuid = activeCallUUID else {+ print("[CallKit] setVideoEnabled ignored; no active native room enabled=\(enabled)")+ return+ }++ Task { [weak self, weak room] in+ guard let self, let room else { return }+ if enabled {+ guard await self.ensureCameraPermission(uuid: uuid) else {+ self.updateVideoMuted(true, overlayMode: self.activeCall?.videoOverlayMode)+ return+ }+ }++ do {+ print("[CallKit] 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 self.videoOverlay.setLocalVideoTrack(room.localParticipant.firstCameraVideoTrack)+ self.rebuildRemoteVideoLayout(from: room)+ self.setVideoOverlayMode(.expanded)+ } else {+ await self.videoOverlay.setLocalVideoTrack(nil)+ self.rebuildRemoteVideoLayout(from: room)+ }+ self.updateVideoMuted(!enabled, overlayMode: enabled ? "expanded" : self.activeCall?.videoOverlayMode)+ print("[CallKit] Native LiveKit camera set enabled=\(enabled) uuid=\(uuid.uuidString)")+ } catch {+ print("[CallKit] Failed to set native LiveKit camera enabled=\(enabled) uuid=\(uuid.uuidString): \(error)")+ self.updateVideoMuted(true, overlayMode: self.activeCall?.videoOverlayMode)+ }+ }+ }++ func setVideoOverlayMode(_ mode: CallVideoOverlayMode) {+ videoOverlay.setMode(mode)+ }++ private func toggleVideoFromOverlay() {+ let enabled = activeCall?.isVideoMuted ?? true+ print("[CallKit] 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)")+ setAudioMuted(muted)+ }++ private func toggleSpeakerFromOverlay() {+ let currentOutput = audioRouteController.currentRouteSnapshot().output+ let enableSpeaker = currentOutput != .speaker+ print("[CallKit] Native video overlay requested speaker enabled=\(enableSpeaker) currentOutput=\(currentOutput.rawValue)")+ audioRouteController.setSpeakerEnabled(enableSpeaker)+ }++ private func endCallFromOverlay() {+ guard let uuid = activeCallUUID else {+ print("[CallKit] Native video overlay end call ignored; no active call")+ return+ }++ 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")")+ if let room {+ rebuildRemoteVideoLayout(from: room)+ }+ }++ func switchCamera() {+ guard let room, let uuid = activeCallUUID else {+ print("[CallKit] switchCamera ignored; no active native room")+ return+ }++ Task { [weak room] in+ guard+ let track = room?.localParticipant.firstCameraVideoTrack as? LocalVideoTrack,+ let capturer = track.capturer as? CameraCapturer+ else {+ print("[CallKit] 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)")+ } catch {+ print("[CallKit] Failed to switch native LiveKit camera uuid=\(uuid.uuidString): \(error)")+ }+ }+ }++ func room(+ _ room: Room,+ didUpdateConnectionState connectionState: ConnectionState,+ from oldConnectionState: ConnectionState+ ) {+ let stateString = describe(connectionState)+ print("[CallKit] LiveKit connection state changed \(describe(oldConnectionState)) -> \(stateString)")+ DispatchQueue.main.async { [weak self, weak room] in+ guard let self, let room, self.room === room else { return }++ if connectionState == .disconnected {+ if let uuid = self.activeCallUUID {+ self.requestSystemEndCall(uuid)+ }+ _ = self.clearNativeCallState(deactivateAudio: true)+ return+ }++ if var snapshot = self.activeCall {+ snapshot.connectionState = stateString+ self.activeCall = snapshot+ self.emitSnapshot()+ }+ }+ }++ func room(_ room: Room, didFailToConnectWithError error: LiveKitError?) {+ print("[CallKit] LiveKit delegate didFailToConnect error=\(String(describing: error))")+ }++ func room(_ room: Room, didDisconnectWithError error: LiveKitError?) {+ print("[CallKit] LiveKit delegate didDisconnect error=\(String(describing: error))")+ }++ func room(_ room: Room, didStartReconnectWithMode reconnectMode: ReconnectMode) {+ print("[CallKit] LiveKit reconnect started mode=\(reconnectMode)")+ }++ func room(_ room: Room, didCompleteReconnectWithMode reconnectMode: ReconnectMode) {+ print("[CallKit] LiveKit reconnect completed mode=\(reconnectMode)")+ }++ func room(_ room: Room, participantDidConnect participant: RemoteParticipant) {+ print("[CallKit] LiveKit remote participant connected \(describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")+ emitParticipantIdentities(from: room)+ rebuildRemoteVideoLayout(from: room)+ }++ func room(_ room: Room, participantDidDisconnect participant: RemoteParticipant) {+ print("[CallKit] LiveKit remote participant disconnected \(describeParticipant(participant)) remoteCount=\(room.remoteParticipants.count)")+ let id = participantId(participant)+ if pinnedRemoteVideoParticipantId == id {+ pinnedRemoteVideoParticipantId = nil+ }+ speakingRemoteParticipantIds.removeAll { $0 == id }+ emitParticipantIdentities(from: room)+ rebuildRemoteVideoLayout(from: room)+ }++ func room(_ room: Room, didUpdateSpeakingParticipants participants: [Participant]) {+ speakingRemoteParticipantIds = participants+ .filter { $0 is RemoteParticipant && !isAgentParticipant($0) }+ .map { participantId($0) }+ print("[CallKit] LiveKit speaking participants updated participants=\(participants.map { describeParticipant($0) })")+ rebuildRemoteVideoLayout(from: room)+ }++ func room(_ room: Room, participant: Participant, didUpdateState state: ParticipantState) {+ print("[CallKit] LiveKit participant state updated \(describeParticipant(participant)) state=\(state)")+ }++ func room(_ room: Room, participant: Participant, didUpdateConnectionQuality quality: ConnectionQuality) {+ print("[CallKit] LiveKit participant quality updated \(describeParticipant(participant)) quality=\(quality)")+ }++ func room(_ room: Room, participant: LocalParticipant, didPublishTrack publication: LocalTrackPublication) {+ print("[CallKit] LiveKit local track published \(describeParticipant(participant)) \(describe(publication))")+ guard isCurrentRoom(room) else {+ print("[CallKit] Ignoring local track publish from stale room")+ return+ }+ if let track = publication.track as? VideoTrack, publication.source == .camera {+ enableMultitaskingCameraAccessIfSupported(room: room, uuid: activeCallUUID)+ videoOverlay.setLocalVideoTrack(track)+ rebuildRemoteVideoLayout(from: room)+ updateVideoMuted(false, overlayMode: "expanded")+ }+ }++ func room(_ room: Room, participant: LocalParticipant, didUnpublishTrack publication: LocalTrackPublication) {+ print("[CallKit] LiveKit local track unpublished \(describeParticipant(participant)) \(describe(publication))")+ guard isCurrentRoom(room) else {+ print("[CallKit] Ignoring local track unpublish from stale room")+ return+ }+ if publication.source == .camera {+ videoOverlay.setLocalVideoTrack(nil)+ rebuildRemoteVideoLayout(from: room)+ updateVideoMuted(true, overlayMode: activeCall?.videoOverlayMode)+ }+ }++ func room(_ room: Room, participant: LocalParticipant, remoteDidSubscribeTrack publication: LocalTrackPublication) {+ print("[CallKit] LiveKit remote subscribed to local track \(describeParticipant(participant)) \(describe(publication))")+ }++ func room(_ room: Room, participant: RemoteParticipant, didPublishTrack publication: RemoteTrackPublication) {+ print("[CallKit] LiveKit remote track published \(describeParticipant(participant)) \(describe(publication))")+ if publication.kind == .video {+ rebuildRemoteVideoLayout(from: room)+ }+ }++ func room(_ room: Room, participant: RemoteParticipant, didSubscribeTrack publication: RemoteTrackPublication) {+ print("[CallKit] LiveKit remote track subscribed \(describeParticipant(participant)) \(describe(publication))")+ if publication.track is VideoTrack, isRemoteVideoSource(publication.source) {+ rebuildRemoteVideoLayout(from: room)+ setVideoOverlayMode(.expanded)+ }+ }++ func room(_ room: Room, participant: RemoteParticipant, didUnsubscribeTrack publication: RemoteTrackPublication) {+ print("[CallKit] LiveKit remote track unsubscribed \(describeParticipant(participant)) \(describe(publication))")+ if isRemoteVideoSource(publication.source) {+ rebuildRemoteVideoLayout(from: room)+ }+ }++ func room(_ room: Room, participant: RemoteParticipant, didFailToSubscribeTrackWithSid trackSid: Track.Sid, error: LiveKitError) {+ print("[CallKit] LiveKit remote track subscribe failed \(describeParticipant(participant)) trackSid=\(trackSid) error=\(error)")+ }++ func room(+ _ room: Room,+ participant: Participant,+ trackPublication: TrackPublication,+ didUpdateIsMuted isMuted: Bool+ ) {+ print("[CallKit] LiveKit track mute updated \(describeParticipant(participant)) \(describe(trackPublication)) muted=\(isMuted)")+ if participant is RemoteParticipant, trackPublication.kind == .video {+ rebuildRemoteVideoLayout(from: room)+ }+ }++ private func describe(_ state: ConnectionState) -> String {+ switch state {+ case .disconnected: return "disconnected"+ case .connecting: return "connecting"+ case .reconnecting: return "reconnecting"+ case .connected: return "connected"+ case .disconnecting: return "disconnecting"+ @unknown default: return "disconnected"+ }+ }++ private func describe(_ publication: TrackPublication) -> String {+ "trackSid=\(publication.sid) source=\(publication.source) kind=\(publication.kind) muted=\(publication.isMuted)"+ }++ private func rebuildRemoteVideoLayout(from room: Room) {+ guard isCurrentRoom(room) else {+ print("[CallKit] Ignoring remote video layout rebuild from stale room")+ return+ }++ let participants = room.remoteParticipants.values.filter { !isAgentParticipant($0) }.map { participant -> NativeVideoParticipant in+ let id = participantId(participant)+ if let track = participant.firstScreenShareVideoTrack {+ return NativeVideoParticipant(+ id: id,+ title: displayTitle(participant),+ track: track,+ isSpeaking: speakingRemoteParticipantIds.contains(id),+ isPinned: pinnedRemoteVideoParticipantId == id,+ isScreenShare: true+ )+ }++ return NativeVideoParticipant(+ id: id,+ title: displayTitle(participant),+ track: participant.firstCameraVideoTrack,+ isSpeaking: speakingRemoteParticipantIds.contains(id),+ isPinned: pinnedRemoteVideoParticipantId == id,+ isScreenShare: false+ )+ }++ if let pinnedId = pinnedRemoteVideoParticipantId,+ !participants.contains(where: { $0.id == pinnedId }) {+ pinnedRemoteVideoParticipantId = nil+ }++ let primary = participants.first(where: { $0.isScreenShare })+ ?? participants.first(where: { $0.id == pinnedRemoteVideoParticipantId })+ ?? speakingRemoteParticipantIds.compactMap { speakingId in+ participants.first(where: { $0.id == speakingId })+ }.first+ ?? participants.first++ videoOverlay.setRemoteVideoParticipants(participants, primaryId: primary?.id)+ updatePictureInPicture(from: room, primary: primary)+ print("[CallKit] Rebuilt remote video layout participants=\(participants.map { "\($0.id):\($0.title)" }) primary=\(primary?.id ?? "nil") pinned=\(pinnedRemoteVideoParticipantId ?? "nil")")+ }++ 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)")+ pictureInPicture.setParticipants(+ localTitle: displayTitle(room.localParticipant),+ localTrack: localTrack,+ remoteTitle: primary?.title,+ remoteTrack: primary?.track+ )+ }++ private 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")")+ return+ }+ guard+ let track = room.localParticipant.firstCameraVideoTrack as? LocalVideoTrack,+ let capturer = track.capturer as? CameraCapturer+ else {+ print("[CallKit] 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")")+ return+ }++ capturer.isMultitaskingAccessEnabled = true+ print("[CallKit] 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")+ return+ }+ onParticipantIdentitiesChanged(participantIdentities(from: room))+ }++ private func participantIdentities(from room: Room) -> [String] {+ let identities = ([room.localParticipant.identity?.stringValue]+ + room.remoteParticipants.values+ .filter { !isAgentParticipant($0) }+ .map { $0.identity?.stringValue })+ .compactMap { $0?.trimmingCharacters(in: .whitespacesAndNewlines) }+ .filter { !$0.isEmpty }+ return Array(Set(identities)).sorted()+ }++ private func isAgentParticipant(_ participant: Participant) -> Bool {+ participant.identity?.stringValue+ .trimmingCharacters(in: .whitespacesAndNewlines)+ .hasPrefix("agent-") == true+ }++ private func isCurrentRoom(_ room: Room) -> Bool {+ self.room === room && activeCall != nil+ }++ private func isRemoteVideoSource(_ source: Track.Source) -> Bool {+ source == .camera || source == .screenShareVideo+ }++ private func participantId(_ participant: Participant) -> String {+ participant.sid?.stringValue+ ?? participant.identity?.stringValue+ ?? "\(ObjectIdentifier(participant).hashValue)"+ }++ private func displayTitle(_ participant: Participant) -> String {+ if let identity = participant.identity?.stringValue {+ let trimmedIdentity = identity.trimmingCharacters(in: .whitespacesAndNewlines)+ if let displayName = participantDisplayNamesByIdentity[trimmedIdentity],+ !displayName.isEmpty {+ return displayName+ }+ let normalizedIdentity = normalizedParticipantIdentity(trimmedIdentity)+ if let displayName = participantDisplayNamesByIdentity[normalizedIdentity],+ !displayName.isEmpty {+ return displayName+ }+ }+ if let name = participant.name, !name.isEmpty {+ return name+ }+ if let identity = participant.identity?.stringValue, !identity.isEmpty {+ return fallbackParticipantName(identity: identity)+ }+ return "Participant"+ }++ private func normalizedParticipantIdentity(_ identity: String) -> String {+ identity.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()+ }++ private func describeParticipant(_ participant: Participant) -> String {+ "participantSid=\(describeOptional(participant.sid)) identity=\(describeOptional(participant.identity?.stringValue)) name=\(describeOptional(participant.name)) title=\(displayTitle(participant))"+ }++ private func fallbackParticipantName(identity: String) -> String {+ let trimmedIdentity = identity.trimmingCharacters(in: .whitespacesAndNewlines)+ let emailOrIdentity = trimmedIdentity.hasPrefix("macro|")+ ? String(trimmedIdentity.dropFirst("macro|".count))+ : trimmedIdentity+ if let localPart = emailOrIdentity.split(separator: "@").first, !localPart.isEmpty {+ return String(localPart)+ }+ return trimmedIdentity.isEmpty ? "Participant" : trimmedIdentity+ }++ private func ensureMicrophonePermission(uuid: UUID) async -> Bool {+ let session = AVAudioSession.sharedInstance()+ switch session.recordPermission {+ case .granted:+ print("[CallKit] 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)")+ } catch {+ print("[CallKit] Failed to restore LiveKit input availability after microphone grant uuid=\(uuid.uuidString): \(error)")+ }+ }+ return true+ case .denied:+ setOutputOnlyAvailabilityIfNeeded(uuid: uuid)+ print("[CallKit] Microphone permission denied uuid=\(uuid.uuidString); keeping native room connected muted")+ return false+ case .undetermined:+ print("[CallKit] Microphone permission undetermined uuid=\(uuid.uuidString); requesting permission")+ let granted = await withCheckedContinuation { continuation in+ session.requestRecordPermission { granted in+ continuation.resume(returning: granted)+ }+ }+ print("[CallKit] 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)")+ } catch {+ print("[CallKit] Failed to enable LiveKit input availability after microphone permission request uuid=\(uuid.uuidString): \(error)")+ }+ } else if !granted {+ setOutputOnlyAvailabilityIfNeeded(uuid: uuid)+ }+ return granted+ @unknown default:+ setOutputOnlyAvailabilityIfNeeded(uuid: uuid)+ print("[CallKit] Microphone permission unknown uuid=\(uuid.uuidString); keeping native room connected muted")+ return false+ }+ }++ private func ensureCameraPermission(uuid: UUID) async -> Bool {+ switch AVCaptureDevice.authorizationStatus(for: .video) {+ case .authorized:+ print("[CallKit] Camera permission granted uuid=\(uuid.uuidString)")+ return true+ case .denied, .restricted:+ print("[CallKit] Camera permission denied uuid=\(uuid.uuidString)")+ return false+ case .notDetermined:+ print("[CallKit] 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)")+ return granted+ @unknown default:+ print("[CallKit] Camera permission unknown uuid=\(uuid.uuidString)")+ return false+ }+ }++ private func callKitAudioEngineAvailability() -> AudioEngineAvailability {+ if AVAudioSession.sharedInstance().recordPermission == .denied {+ return AudioEngineAvailability(isInputAvailable: false, isOutputAvailable: true)+ }+ return .default+ }++ private func hasUsableAudioOutputRoute() -> Bool {+ !AVAudioSession.sharedInstance().currentRoute.outputs.isEmpty+ }++ private func canEnableMicrophoneAudio() -> Bool {+ isCallKitAudioActive+ && AudioManager.shared.engineAvailability.isInputAvailable+ }++ private func enableMicrophoneAfterAudioActivationIfNeeded(reason: String) {+ guard !desiredAudioMuted else { return }+ guard let room, let uuid = activeCallUUID else { return }+ guard activeCall?.connectionState == "connected" else { return }+ guard canEnableMicrophoneAudio() else {+ print("[CallKit] Waiting to restore LiveKit microphone after audio activation reason=\(reason) engineAvailable=\(AudioManager.shared.engineAvailability.isInputAvailable) engineRunning=\(AudioManager.shared.isEngineRunning) \(describeAudioSession())")+ return+ }++ Task { [weak self, weak room] in+ guard let self, let room else { return }+ guard self.activeCallUUID == uuid, self.room === room, !self.desiredAudioMuted else { return }+ do {+ print("[CallKit] Restoring LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString) engineRunning=\(AudioManager.shared.isEngineRunning) \(self.describeAudioSession())")+ try await room.localParticipant.setMicrophone(enabled: true)+ self.updateAudioMuted(false, room: room, uuid: uuid)+ print("[CallKit] Restored LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString)")+ } catch {+ print("[CallKit] Failed to restore LiveKit microphone after audio activation reason=\(reason) uuid=\(uuid.uuidString): \(error) \(self.describeAudioSession())")+ }+ }+ }++ private func setOutputOnlyAvailabilityIfNeeded(uuid: UUID) {+ guard isCallKitAudioActive else { return }+ do {+ try 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())")+ } catch {+ print("[CallKit] Failed to set LiveKit audio engine to output-only uuid=\(uuid.uuidString): \(error) \(describeAudioSession())")+ }+ }++ 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: ",")+ 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)])"+ }++ private func describe(_ permission: AVAudioSession.RecordPermission) -> String {+ switch permission {+ case .granted: return "granted"+ case .denied: return "denied"+ case .undetermined: return "undetermined"+ @unknown default: return "unknown"+ }+ }++ private func describeOptional<T>(_ value: T?) -> String {+ value.map { "\($0)" } ?? "nil"+ }++ private func updateVideoMuted(_ isMuted: Bool, overlayMode: String?) {+ DispatchQueue.main.async { [weak self] in+ guard let self, var snapshot = self.activeCall else { return }+ snapshot.isVideoMuted = isMuted+ if let overlayMode {+ snapshot.videoOverlayMode = overlayMode+ }+ self.activeCall = snapshot+ self.videoOverlay.setLocalVideoEnabled(!isMuted)+ self.emitSnapshot()+ }+ }++ private func updateAudioMuted(_ isMuted: Bool, room: Room, uuid: UUID) {+ DispatchQueue.main.async { [weak self, weak room] in+ guard let self, let room, self.activeCallUUID == uuid, self.room === room, var snapshot = self.activeCall else { return }+ let previousMuted = snapshot.isAudioMuted+ snapshot.isAudioMuted = isMuted+ self.desiredAudioMuted = isMuted+ self.activeCall = snapshot+ print("[CallKit] Native LiveKit microphone state updated uuid=\(uuid.uuidString) previousMuted=\(previousMuted) actualMuted=\(isMuted) desiredMuted=\(self.desiredAudioMuted)")+ self.videoOverlay.setAudioMuted(isMuted)+ self.emitSnapshot()+ }+ }++ private func updateVideoOverlayMode(_ overlayMode: String) {+ DispatchQueue.main.async { [weak self] in+ guard let self, var snapshot = self.activeCall else { return }+ snapshot.videoOverlayMode = overlayMode+ self.activeCall = snapshot+ self.emitSnapshot()+ }+ }++ @MainActor+ private func clearNativeCallState(deactivateAudio: Bool) -> Room? {+ connectTask?.cancel()+ connectTask = nil+ if deactivateAudio, isCallKitAudioActive {+ deactivateAudioEngine()+ }+ let r = room+ room = nil+ activeCallUUID = nil+ activeCall = nil+ desiredAudioMuted = false+ pinnedRemoteVideoParticipantId = nil+ speakingRemoteParticipantIds = []+ participantDisplayNamesByIdentity = [:]+ onParticipantIdentitiesChanged([])+ pictureInPicture.stopAndReset()+ audioRouteController.resetSpeakerOverride()+ emitSnapshot()+ videoOverlay.reset()+ return r+ }++ private func emitSnapshot() {+ if let activeCall {+ print("[CallKit] Emitting native snapshot state=\(activeCall.connectionState) channelId=\(activeCall.channelId) callId=\(activeCall.callId)")+ } else {+ print("[CallKit] Emitting native snapshot state=disconnected")+ }+ onSnapshotChanged(activeCall)+ }+}++private final class CallKitAudioEngineLogger: AudioEngineObserver, @unchecked Sendable {+ var next: (any AudioEngineObserver)?+ var desiredMutedProvider: (() -> Bool?)?++ func engineDidCreate(_ engine: AVAudioEngine) -> Int {+ print("[CallKit] 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())")+ let result = next?.engineWillEnable(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0+ print("[CallKit] 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())")+ let result = next?.engineWillStart(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0+ print("[CallKit] 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())")+ 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())")+ return next?.engineDidDisable(engine, isPlayoutEnabled: isPlayoutEnabled, isRecordingEnabled: isRecordingEnabled) ?? 0+ }++ func engineWillRelease(_ engine: AVAudioEngine) -> Int {+ print("[CallKit] LiveKit audio engine will release desiredMuted=\(describeDesiredMuted())")+ return next?.engineWillRelease(engine) ?? 0+ }++ func engineWillConnectOutput(+ _ engine: AVAudioEngine,+ src: AVAudioNode,+ dst: AVAudioNode?,+ format: AVAudioFormat,+ context: [AnyHashable: Any]+ ) -> Int {+ print("[CallKit] LiveKit audio engine will connect output format=\(format) desiredMuted=\(describeDesiredMuted())")+ return next?.engineWillConnectOutput(engine, src: src, dst: dst, format: format, context: context) ?? 0+ }++ func engineWillConnectInput(+ _ engine: AVAudioEngine,+ src: AVAudioNode?,+ dst: AVAudioNode,+ format: AVAudioFormat,+ context: [AnyHashable: Any]+ ) -> Int {+ print("[CallKit] LiveKit audio engine will connect input format=\(format) desiredMuted=\(describeDesiredMuted())")+ return next?.engineWillConnectInput(engine, src: src, dst: dst, format: format, context: context) ?? 0+ }++ private func describeDesiredMuted() -> String {+ desiredMutedProvider?().map(String.init) ?? "nil"+ }+}diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_active_call_state.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_active_call_state.tomlnew file mode 100644index 0000000000..96592e24b9--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_active_call_state.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-active-call-state"+description = "Enables the get_active_call_state command without any pre-configured scope."+commands.allow = ["get_active_call_state"]++[[permission]]+identifier = "deny-get-active-call-state"+description = "Denies the get_active_call_state command without any pre-configured scope."+commands.deny = ["get_active_call_state"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_pending_answered_call.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_pending_answered_call.tomlnew file mode 100644index 0000000000..7dfa7aff2d--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/get_pending_answered_call.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-get-pending-answered-call"+description = "Enables the get_pending_answered_call command without any pre-configured scope."+commands.allow = ["get_pending_answered_call"]++[[permission]]+identifier = "deny-get-pending-answered-call"+description = "Denies the get_pending_answered_call command without any pre-configured scope."+commands.deny = ["get_pending_answered_call"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_channel_title.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_channel_title.tomlnew file mode 100644index 0000000000..c86a132d62--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_channel_title.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-call-drawer-channel-title"+description = "Enables the set_call_drawer_channel_title command without any pre-configured scope."+commands.allow = ["set_call_drawer_channel_title"]++[[permission]]+identifier = "deny-set-call-drawer-channel-title"+description = "Denies the set_call_drawer_channel_title command without any pre-configured scope."+commands.deny = ["set_call_drawer_channel_title"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_theme.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_theme.tomlnew file mode 100644index 0000000000..3228133947--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_call_drawer_theme.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-call-drawer-theme"+description = "Enables the set_call_drawer_theme command without any pre-configured scope."+commands.allow = ["set_call_drawer_theme"]++[[permission]]+identifier = "deny-set-call-drawer-theme"+description = "Denies the set_call_drawer_theme command without any pre-configured scope."+commands.deny = ["set_call_drawer_theme"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_participant_display_name.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_participant_display_name.tomlnew file mode 100644index 0000000000..c138989c29--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_participant_display_name.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-participant-display-name"+description = "Enables the set_participant_display_name command without any pre-configured scope."+commands.allow = ["set_participant_display_name"]++[[permission]]+identifier = "deny-set-participant-display-name"+description = "Denies the set_participant_display_name command without any pre-configured scope."+commands.deny = ["set_participant_display_name"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_enabled.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_enabled.tomlnew file mode 100644index 0000000000..a33a27a2eb--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_enabled.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-video-enabled"+description = "Enables the set_video_enabled command without any pre-configured scope."+commands.allow = ["set_video_enabled"]++[[permission]]+identifier = "deny-set-video-enabled"+description = "Denies the set_video_enabled command without any pre-configured scope."+commands.deny = ["set_video_enabled"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_overlay_mode.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_overlay_mode.tomlnew file mode 100644index 0000000000..b3348ba239--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/set_video_overlay_mode.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-set-video-overlay-mode"+description = "Enables the set_video_overlay_mode command without any pre-configured scope."+commands.allow = ["set_video_overlay_mode"]++[[permission]]+identifier = "deny-set-video-overlay-mode"+description = "Denies the set_video_overlay_mode command without any pre-configured scope."+commands.deny = ["set_video_overlay_mode"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/start_outgoing_call.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/start_outgoing_call.tomlnew file mode 100644index 0000000000..64c7498686--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/start_outgoing_call.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-start-outgoing-call"+description = "Enables the start_outgoing_call command without any pre-configured scope."+commands.allow = ["start_outgoing_call"]++[[permission]]+identifier = "deny-start-outgoing-call"+description = "Denies the start_outgoing_call command without any pre-configured scope."+commands.deny = ["start_outgoing_call"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/switch_camera.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/switch_camera.tomlnew file mode 100644index 0000000000..0911db304f--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/switch_camera.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-switch-camera"+description = "Enables the switch_camera command without any pre-configured scope."+commands.allow = ["switch_camera"]++[[permission]]+identifier = "deny-switch-camera"+description = "Denies the switch_camera command without any pre-configured scope."+commands.deny = ["switch_camera"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_answered.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_answered.tomlnew file mode 100644index 0000000000..e3e7a3bc25--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_answered.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-call-answered"+description = "Enables the watch_call_answered command without any pre-configured scope."+commands.allow = ["watch_call_answered"]++[[permission]]+identifier = "deny-watch-call-answered"+description = "Denies the watch_call_answered command without any pre-configured scope."+commands.deny = ["watch_call_answered"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_ended.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_ended.tomlnew file mode 100644index 0000000000..cf91cf3a10--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_call_ended.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-call-ended"+description = "Enables the watch_call_ended command without any pre-configured scope."+commands.allow = ["watch_call_ended"]++[[permission]]+identifier = "deny-watch-call-ended"+description = "Denies the watch_call_ended command without any pre-configured scope."+commands.deny = ["watch_call_ended"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_connection_state.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_connection_state.tomlnew file mode 100644index 0000000000..28b5f54859--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_connection_state.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-connection-state"+description = "Enables the watch_connection_state command without any pre-configured scope."+commands.allow = ["watch_connection_state"]++[[permission]]+identifier = "deny-watch-connection-state"+description = "Denies the watch_connection_state command without any pre-configured scope."+commands.deny = ["watch_connection_state"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_drawer_opened.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_drawer_opened.tomlnew file mode 100644index 0000000000..3eb015ee27--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_drawer_opened.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-drawer-opened"+description = "Enables the watch_drawer_opened command without any pre-configured scope."+commands.allow = ["watch_drawer_opened"]++[[permission]]+identifier = "deny-watch-drawer-opened"+description = "Denies the watch_drawer_opened command without any pre-configured scope."+commands.deny = ["watch_drawer_opened"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_participant_identities.toml b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_participant_identities.tomlnew file mode 100644index 0000000000..20f133a7ce--- /dev/null+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/commands/watch_participant_identities.toml@@ -0,0 +1,13 @@+# Automatically generated - DO NOT EDIT!++"$schema" = "../../schemas/schema.json"++[[permission]]+identifier = "allow-watch-participant-identities"+description = "Enables the watch_participant_identities command without any pre-configured scope."+commands.allow = ["watch_participant_identities"]++[[permission]]+identifier = "deny-watch-participant-identities"+description = "Denies the watch_participant_identities command without any pre-configured scope."+commands.deny = ["watch_participant_identities"]diff --git a/js/app/tauri/callkit_plugin/permissions/autogenerated/reference.md b/js/app/tauri/callkit_plugin/permissions/autogenerated/reference.mdindex 343f88f06c..3e7629bf8d 100644--- a/js/app/tauri/callkit_plugin/permissions/autogenerated/reference.md+++ b/js/app/tauri/callkit_plugin/permissions/autogenerated/reference.md@@ -36,6 +36,58 @@ Denies the end_active_call command without any pre-configured scope.<tr><td>+`call-kit:allow-get-active-call-state`++</td>+<td>++Enables the get_active_call_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-get-active-call-state`++</td>+<td>++Denies the get_active_call_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-get-pending-answered-call`++</td>+<td>++Enables the get_pending_answered_call command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-get-pending-answered-call`++</td>+<td>++Denies the get_pending_answered_call command without any pre-configured scope.++</td>+</tr>++<tr>+<td>+`call-kit:allow-get-voip-token`</td>@@ -56,6 +108,318 @@ Enables the get_voip_token command without any pre-configured scope.Denies the get_voip_token command without any pre-configured scope.+</td>+</tr>++<tr>+<td>++`call-kit:allow-set-call-drawer-channel-title`++</td>+<td>++Enables the set_call_drawer_channel_title command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-set-call-drawer-channel-title`++</td>+<td>++Denies the set_call_drawer_channel_title command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-set-call-drawer-theme`++</td>+<td>++Enables the set_call_drawer_theme command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-set-call-drawer-theme`++</td>+<td>++Denies the set_call_drawer_theme command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-set-participant-display-name`++</td>+<td>++Enables the set_participant_display_name command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-set-participant-display-name`++</td>+<td>++Denies the set_participant_display_name command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-set-video-enabled`++</td>+<td>++Enables the set_video_enabled command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-set-video-enabled`++</td>+<td>++Denies the set_video_enabled command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-set-video-overlay-mode`++</td>+<td>++Enables the set_video_overlay_mode command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-set-video-overlay-mode`++</td>+<td>++Denies the set_video_overlay_mode command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-start-outgoing-call`++</td>+<td>++Enables the start_outgoing_call command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-start-outgoing-call`++</td>+<td>++Denies the start_outgoing_call command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-switch-camera`++</td>+<td>++Enables the switch_camera command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-switch-camera`++</td>+<td>++Denies the switch_camera command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-watch-call-answered`++</td>+<td>++Enables the watch_call_answered command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-watch-call-answered`++</td>+<td>++Denies the watch_call_answered command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-watch-call-ended`++</td>+<td>++Enables the watch_call_ended command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-watch-call-ended`++</td>+<td>++Denies the watch_call_ended command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-watch-connection-state`++</td>+<td>++Enables the watch_connection_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-watch-connection-state`++</td>+<td>++Denies the watch_connection_state command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-watch-drawer-opened`++</td>+<td>++Enables the watch_drawer_opened command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-watch-drawer-opened`++</td>+<td>++Denies the watch_drawer_opened command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:allow-watch-participant-identities`++</td>+<td>++Enables the watch_participant_identities command without any pre-configured scope.++</td>+</tr>++<tr>+<td>++`call-kit:deny-watch-participant-identities`++</td>+<td>++Denies the watch_participant_identities command without any pre-configured scope.+</td></tr></table>diff --git a/js/app/tauri/callkit_plugin/permissions/schemas/schema.json b/js/app/tauri/callkit_plugin/permissions/schemas/schema.jsonindex 3ae9260b77..494b75fecf 100644--- a/js/app/tauri/callkit_plugin/permissions/schemas/schema.json+++ b/js/app/tauri/callkit_plugin/permissions/schemas/schema.json@@ -306,6 +306,30 @@"const": "deny-end-active-call","markdownDescription": "Denies the end_active_call command without any pre-configured scope."},+ {+ "description": "Enables the get_active_call_state command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-active-call-state",+ "markdownDescription": "Enables the get_active_call_state command without any pre-configured scope."+ },+ {+ "description": "Denies the get_active_call_state command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-active-call-state",+ "markdownDescription": "Denies the get_active_call_state command without any pre-configured scope."+ },+ {+ "description": "Enables the get_pending_answered_call command without any pre-configured scope.",+ "type": "string",+ "const": "allow-get-pending-answered-call",+ "markdownDescription": "Enables the get_pending_answered_call command without any pre-configured scope."+ },+ {+ "description": "Denies the get_pending_answered_call command without any pre-configured scope.",+ "type": "string",+ "const": "deny-get-pending-answered-call",+ "markdownDescription": "Denies the get_pending_answered_call command without any pre-configured scope."+ },{"description": "Enables the get_voip_token command without any pre-configured scope.","type": "string",@@ -317,6 +341,150 @@"type": "string","const": "deny-get-voip-token","markdownDescription": "Denies the get_voip_token command without any pre-configured scope."+ },+ {+ "description": "Enables the set_call_drawer_channel_title command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-call-drawer-channel-title",+ "markdownDescription": "Enables the set_call_drawer_channel_title command without any pre-configured scope."+ },+ {+ "description": "Denies the set_call_drawer_channel_title command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-call-drawer-channel-title",+ "markdownDescription": "Denies the set_call_drawer_channel_title command without any pre-configured scope."+ },+ {+ "description": "Enables the set_call_drawer_theme command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-call-drawer-theme",+ "markdownDescription": "Enables the set_call_drawer_theme command without any pre-configured scope."+ },+ {+ "description": "Denies the set_call_drawer_theme command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-call-drawer-theme",+ "markdownDescription": "Denies the set_call_drawer_theme command without any pre-configured scope."+ },+ {+ "description": "Enables the set_participant_display_name command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-participant-display-name",+ "markdownDescription": "Enables the set_participant_display_name command without any pre-configured scope."+ },+ {+ "description": "Denies the set_participant_display_name command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-participant-display-name",+ "markdownDescription": "Denies the set_participant_display_name command without any pre-configured scope."+ },+ {+ "description": "Enables the set_video_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-video-enabled",+ "markdownDescription": "Enables the set_video_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_video_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-video-enabled",+ "markdownDescription": "Denies the set_video_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_video_overlay_mode command without any pre-configured scope.",+ "type": "string",+ "const": "allow-set-video-overlay-mode",+ "markdownDescription": "Enables the set_video_overlay_mode command without any pre-configured scope."+ },+ {+ "description": "Denies the set_video_overlay_mode command without any pre-configured scope.",+ "type": "string",+ "const": "deny-set-video-overlay-mode",+ "markdownDescription": "Denies the set_video_overlay_mode command without any pre-configured scope."+ },+ {+ "description": "Enables the start_outgoing_call command without any pre-configured scope.",+ "type": "string",+ "const": "allow-start-outgoing-call",+ "markdownDescription": "Enables the start_outgoing_call command without any pre-configured scope."+ },+ {+ "description": "Denies the start_outgoing_call command without any pre-configured scope.",+ "type": "string",+ "const": "deny-start-outgoing-call",+ "markdownDescription": "Denies the start_outgoing_call command without any pre-configured scope."+ },+ {+ "description": "Enables the switch_camera command without any pre-configured scope.",+ "type": "string",+ "const": "allow-switch-camera",+ "markdownDescription": "Enables the switch_camera command without any pre-configured scope."+ },+ {+ "description": "Denies the switch_camera command without any pre-configured scope.",+ "type": "string",+ "const": "deny-switch-camera",+ "markdownDescription": "Denies the switch_camera command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_call_answered command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-call-answered",+ "markdownDescription": "Enables the watch_call_answered command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_call_answered command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-call-answered",+ "markdownDescription": "Denies the watch_call_answered command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_call_ended command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-call-ended",+ "markdownDescription": "Enables the watch_call_ended command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_call_ended command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-call-ended",+ "markdownDescription": "Denies the watch_call_ended command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_connection_state command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-connection-state",+ "markdownDescription": "Enables the watch_connection_state command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_connection_state command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-connection-state",+ "markdownDescription": "Denies the watch_connection_state command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_drawer_opened command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-drawer-opened",+ "markdownDescription": "Enables the watch_drawer_opened command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_drawer_opened command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-drawer-opened",+ "markdownDescription": "Denies the watch_drawer_opened command without any pre-configured scope."+ },+ {+ "description": "Enables the watch_participant_identities command without any pre-configured scope.",+ "type": "string",+ "const": "allow-watch-participant-identities",+ "markdownDescription": "Enables the watch_participant_identities command without any pre-configured scope."+ },+ {+ "description": "Denies the watch_participant_identities command without any pre-configured scope.",+ "type": "string",+ "const": "deny-watch-participant-identities",+ "markdownDescription": "Denies the watch_participant_identities command without any pre-configured scope."}]}diff --git a/js/app/tauri/src-tauri/Cargo.toml b/js/app/tauri/src-tauri/Cargo.tomlindex d449064d32..2cc17013d6 100644--- a/js/app/tauri/src-tauri/Cargo.toml+++ b/js/app/tauri/src-tauri/Cargo.toml@@ -10,7 +10,7 @@ version = "0.1.0"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html[lib]-crate-type = ["cdylib", "rlib", "staticlib"]+crate-type = ["staticlib", "rlib"]name = "app_lib"[build-dependencies]diff --git a/js/app/tauri/src-tauri/Info.ios.plist b/js/app/tauri/src-tauri/Info.ios.plistindex 999f611302..9545c5f66c 100644--- a/js/app/tauri/src-tauri/Info.ios.plist+++ b/js/app/tauri/src-tauri/Info.ios.plist@@ -4,6 +4,8 @@<dict><key>UIBackgroundModes</key><array>+ <string>audio</string>+ <string>picture-in-picture</string><string>voip</string></array><key>LSApplicationQueriesSchemes</key>diff --git a/js/app/tauri/src-tauri/capabilities/mobile.json b/js/app/tauri/src-tauri/capabilities/mobile.jsonindex 0ba3e5bbf3..c6fa473fa6 100644--- a/js/app/tauri/src-tauri/capabilities/mobile.json+++ b/js/app/tauri/src-tauri/capabilities/mobile.json@@ -15,9 +15,21 @@"log:default","auth:allow-authenticate","device-info:default",- "pasteboard:allow-stage-pasteboard-image",- "photo-library:allow-pick-photo-library-images","call-kit:allow-get-voip-token",- "call-kit:allow-end-active-call"+ "call-kit:allow-end-active-call",+ "call-kit:allow-get-pending-answered-call",+ "call-kit:allow-watch-call-answered",+ "call-kit:allow-watch-call-ended",+ "call-kit:allow-watch-connection-state",+ "call-kit:allow-watch-drawer-opened",+ "call-kit:allow-watch-participant-identities",+ "call-kit:allow-get-active-call-state",+ "call-kit:allow-start-outgoing-call",+ "call-kit:allow-set-video-enabled",+ "call-kit:allow-set-video-overlay-mode",+ "call-kit:allow-set-call-drawer-channel-title",+ "call-kit:allow-set-call-drawer-theme",+ "call-kit:allow-set-participant-display-name",+ "call-kit:allow-switch-camera"]}diff --git a/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.pbxproj b/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.pbxprojindex d7a6da6d08..878f7c0c96 100644--- a/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.pbxproj+++ b/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.pbxproj@@ -7,6 +7,7 @@objects = {/* Begin PBXBuildFile section */+ 1292DFBC353451F01E5A0900 /* tauri-plugin-call-kit in Frameworks */ = {isa = PBXBuildFile; productRef = 31216FAD4580C9A0B4F070BF /* tauri-plugin-call-kit */; };299814393FFBF154FAD94CA8 /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F3673D372C5ABDD1AD6E7067 /* QuartzCore.framework */; };2FBDFDC47F5358109C23AF80 /* ShareExtension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = F2F6B23901C11426024E1D4E /* ShareExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };3036F7131E55779ABF15BD58 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 02B7F8347F94B067E6B27396 /* LaunchScreen.storyboard */; };@@ -64,6 +65,7 @@0534025E6A6DC9BF45F0EC3E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };07B9FBE7A5B295FC80DD38FD /* tests.rs */ = {isa = PBXFileReference; path = tests.rs; sourceTree = "<group>"; };0E2B15F176E4B041AE33EEEA /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; };+ 0E388DBA934229FAE3222596 /* ios */ = {isa = PBXFileReference; lastKnownFileType = folder; name = ios; path = ../../../callkit_plugin/ios; sourceTree = SOURCE_ROOT; };0EAE3E64C98FE3472A9133C6 /* NotificationService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationService.swift; sourceTree = "<group>"; };1631E4CFBB715FFDBF919C8C /* main.rs */ = {isa = PBXFileReference; path = main.rs; sourceTree = "<group>"; };17B52554D60D361AFE791C3E /* lib.rs */ = {isa = PBXFileReference; path = lib.rs; sourceTree = "<group>"; };@@ -75,14 +77,17 @@5116F21CDEA54A9508733EFB /* NotificationServiceExtension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = NotificationServiceExtension.entitlements; sourceTree = "<group>"; };682535EEFE1DA20BE07B123C /* main.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = main.mm; sourceTree = "<group>"; };81E326B61ED92E1D1EECF952 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };+ 857275BDA611F410D652DC52 /* noop.rs */ = {isa = PBXFileReference; path = noop.rs; sourceTree = "<group>"; };9625271C5AAE7E545027267A /* debug.rs */ = {isa = PBXFileReference; path = debug.rs; sourceTree = "<group>"; };9D39399531526740F7E44FFB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };9FACFFCB6E3743955F72464C /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; };AF1DE57E7D9CF13BB2E0E038 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };+ C99D2FD70E50E61F99B50E65 /* shared.rs */ = {isa = PBXFileReference; path = shared.rs; sourceTree = "<group>"; };CE1209BFDECB28E00189B168 /* Metal.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Metal.framework; path = System/Library/Frameworks/Metal.framework; sourceTree = SDKROOT; };D8F57162F5CC7AEDD55F173D /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; };DCE4B06F002B1CDA6E6F3C2A /* tauri_protocol.rs */ = {isa = PBXFileReference; path = tauri_protocol.rs; sourceTree = "<group>"; };DE016BCDACB745FDB90321AF /* ShareViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareViewController.swift; sourceTree = "<group>"; };+ DF0AB432F5C778F3F2D20F2A /* ios.rs */ = {isa = PBXFileReference; path = ios.rs; sourceTree = "<group>"; };E008C8DABBF95A4BBAE08B15 /* share_target.rs */ = {isa = PBXFileReference; path = share_target.rs; sourceTree = "<group>"; };F2F6B23901C11426024E1D4E /* ShareExtension.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = ShareExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; };F3673D372C5ABDD1AD6E7067 /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };@@ -96,6 +101,7 @@buildActionMask = 2147483647;files = (C869023DDFE275D42F3FBF29 /* libapp.a in Frameworks */,+ 1292DFBC353451F01E5A0900 /* tauri-plugin-call-kit in Frameworks */,31585529C029A01BE249A285 /* CoreGraphics.framework in Frameworks */,E68F6CFDAED6503ABB4044A5 /* Metal.framework in Frameworks */,9D59FB167BB4E699DA17D1E9 /* MetalKit.framework in Frameworks */,@@ -154,6 +160,9 @@75535DC8237A09A15D793259 /* share_target */ = {isa = PBXGroup;children = (+ DF0AB432F5C778F3F2D20F2A /* ios.rs */,+ 857275BDA611F410D652DC52 /* noop.rs */,+ C99D2FD70E50E61F99B50E65 /* shared.rs */,07B9FBE7A5B295FC80DD38FD /* tests.rs */,);path = share_target;@@ -167,6 +176,14 @@path = Sources;sourceTree = "<group>";};+ 7C491BBB7C8D3D6FD3965CCB /* Packages */ = {+ isa = PBXGroup;+ children = (+ 0E388DBA934229FAE3222596 /* ios */,+ );+ name = Packages;+ sourceTree = "<group>";+ };83291B4320BCCBF029F53A03 /* NotificationServiceExtension */ = {isa = PBXGroup;children = (@@ -200,6 +217,7 @@2867E55E70187711EE923EBD /* app_iOS */,BAFB695BB8415511FEC74542 /* Externals */,83291B4320BCCBF029F53A03 /* NotificationServiceExtension */,+ 7C491BBB7C8D3D6FD3965CCB /* Packages */,1C4105EF6E39BF7F1E4019F3 /* ShareExtension */,78CBE3E5873199C0066F12DF /* Sources */,855775165ACE55D883F89EB3 /* src */,@@ -234,18 +252,25 @@path = app;sourceTree = "<group>";};- "TEMP_E7B71914-BE81-4A93-AD09-CC8988C6EBE3" /* arm64 */ = {+ "TEMP_3A50DCA4-FDEA-4D4D-904A-20A8215EAE45" /* x86_64 */ = {isa = PBXGroup;children = ();- path = arm64;+ path = x86_64;sourceTree = "<group>";};- "TEMP_FDEDC763-2672-41E7-B94A-E03693807B94" /* x86_64 */ = {+ "TEMP_8A5DE614-AE5B-4A39-AD6F-31B049BCE93C" /* debug */ = {isa = PBXGroup;children = ();- path = x86_64;+ path = debug;+ sourceTree = "<group>";+ };+ "TEMP_D5C20B7B-2E8D-4541-AD80-5A0585916C0A" /* arm64 */ = {+ isa = PBXGroup;+ children = (+ );+ path = arm64;sourceTree = "<group>";};/* End PBXGroup section */@@ -303,6 +328,7 @@);name = app_iOS;packageProductDependencies = (+ 31216FAD4580C9A0B4F070BF /* tauri-plugin-call-kit */,);productName = app_iOS;productReference = FBC720DFA1D01F55B0A32344 /* app_iOS.app */;@@ -341,6 +367,9 @@);mainGroup = 87648061424F20D5D4871E9E;minimizedProjectReferenceProxies = 1;+ packageReferences = (+ CD7161A5D818C2B0EEDFFB0A /* XCLocalSwiftPackageReference "../../../callkit_plugin/ios" */,+ );preferredProjectObjectVersion = 77;projectDirPath = "";projectRoot = "";@@ -467,11 +496,14 @@CODE_SIGN_STYLE = Automatic;DEVELOPMENT_TEAM = TY74Q77JBD;ENABLE_BITCODE = NO;+ ENABLE_DEBUG_DYLIB = NO;"EXCLUDED_ARCHS[sdk=iphoneos*]" = x86_64;FRAMEWORK_SEARCH_PATHS = ("$(inherited)","\".\"",);+ "FRAMEWORK_SEARCH_PATHS[arch=arm64]" = "$(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION)";+ "FRAMEWORK_SEARCH_PATHS[arch=x86_64]" = "$(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION)";INFOPLIST_FILE = app_iOS/Info.plist;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)",@@ -581,11 +613,14 @@CODE_SIGN_STYLE = Automatic;DEVELOPMENT_TEAM = TY74Q77JBD;ENABLE_BITCODE = NO;+ ENABLE_DEBUG_DYLIB = NO;"EXCLUDED_ARCHS[sdk=iphoneos*]" = x86_64;FRAMEWORK_SEARCH_PATHS = ("$(inherited)","\".\"",);+ "FRAMEWORK_SEARCH_PATHS[arch=arm64]" = "$(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION)";+ "FRAMEWORK_SEARCH_PATHS[arch=x86_64]" = "$(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION)";INFOPLIST_FILE = app_iOS/Info.plist;LD_RUNPATH_SEARCH_PATHS = ("$(inherited)",@@ -751,6 +786,20 @@defaultConfigurationName = debug;};/* End XCConfigurationList section */++/* Begin XCLocalSwiftPackageReference section */+ CD7161A5D818C2B0EEDFFB0A /* XCLocalSwiftPackageReference "../../../callkit_plugin/ios" */ = {+ isa = XCLocalSwiftPackageReference;+ relativePath = ../../../callkit_plugin/ios;+ };+/* End XCLocalSwiftPackageReference section */++/* Begin XCSwiftPackageProductDependency section */+ 31216FAD4580C9A0B4F070BF /* tauri-plugin-call-kit */ = {+ isa = XCSwiftPackageProductDependency;+ productName = "tauri-plugin-call-kit";+ };+/* End XCSwiftPackageProductDependency section */};rootObject = A9B1B09F1872768368ACECE2 /* Project object */;}diff --git a/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvednew file mode 100644index 0000000000..695b67a744--- /dev/null+++ b/js/app/tauri/src-tauri/gen/apple/app.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -0,0 +1,50 @@+{+ "pins" : [+ {+ "identity" : "client-sdk-swift",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/livekit/client-sdk-swift.git",+ "state" : {+ "revision" : "f70911172031fe40042266ed3bc35171224c2ef0",+ "version" : "2.13.0"+ }+ },+ {+ "identity" : "livekit-uniffi-xcframework",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/livekit/livekit-uniffi-xcframework.git",+ "state" : {+ "revision" : "61229f4032131311b997ddb1bc1cb8f5afbe30c8",+ "version" : "0.0.5"+ }+ },+ {+ "identity" : "swift-protobuf",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/apple/swift-protobuf.git",+ "state" : {+ "revision" : "f6506eaa86ed2e01cb0ae14a75035b7fdbf0918f",+ "version" : "1.38.0"+ }+ },+ {+ "identity" : "swift-rs",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/Brendonovich/swift-rs",+ "state" : {+ "revision" : "f64a4514de07f450ec5b6aa297624cd3479d9579",+ "version" : "1.0.7"+ }+ },+ {+ "identity" : "webrtc-xcframework",+ "kind" : "remoteSourceControl",+ "location" : "https://github.com/livekit/webrtc-xcframework.git",+ "state" : {+ "revision" : "f6017e189972b86f90e0ec406b1629828bc75748",+ "version" : "144.7559.3"+ }+ }+ ],+ "version" : 2+}diff --git a/js/app/tauri/src-tauri/gen/apple/app_iOS/Info.plist b/js/app/tauri/src-tauri/gen/apple/app_iOS/Info.plistindex 4dad4ce258..a23d77569a 100644--- a/js/app/tauri/src-tauri/gen/apple/app_iOS/Info.plist+++ b/js/app/tauri/src-tauri/gen/apple/app_iOS/Info.plist@@ -46,6 +46,12 @@<string>INSendMessageIntent</string><string>NSUserActivityTypeBrowsingWeb</string></array>+ <key>UIBackgroundModes</key>+ <array>+ <string>audio</string>+ <string>picture-in-picture</string>+ <string>voip</string>+ </array><key>UILaunchStoryboardName</key><string>LaunchScreen</string><key>UIRequiredDeviceCapabilities</key>@@ -64,9 +70,5 @@<string>UIInterfaceOrientationLandscapeLeft</string><string>UIInterfaceOrientationLandscapeRight</string></array>- <key>UIBackgroundModes</key>- <array>- <string>voip</string>- </array></dict></plist>\ No newline at end of filediff --git a/js/app/tauri/src-tauri/gen/apple/project.yml b/js/app/tauri/src-tauri/gen/apple/project.ymlindex 9b8441fcf3..85698da55d 100644--- a/js/app/tauri/src-tauri/gen/apple/project.yml+++ b/js/app/tauri/src-tauri/gen/apple/project.yml@@ -3,6 +3,9 @@ options:bundleIdPrefix: com.macro.app.proddeploymentTarget:iOS: 14.0+packages:+ CallKitPlugin:+ path: ../../../callkit_plugin/iosfileGroups: [../../src]configs:debug: debug@@ -36,6 +39,7 @@ targets:- path: Externalsexcludes:- "**/*.a"+ - "**/*.framework"- path: app_iOS- path: assetsbuildPhase: resources@@ -68,6 +72,10 @@ targets:NSPhotoLibraryUsageDescription: "This app needs access to your photo library to upload attachments."LSApplicationQueriesSchemes:- macro+ UIBackgroundModes:+ - audio+ - picture-in-picture+ - voipentitlements:path: app_iOS/app_iOS.entitlementsproperties:@@ -87,8 +95,11 @@ targets:settings:base:ENABLE_BITCODE: false+ ENABLE_DEBUG_DYLIB: falseARCHS: [arm64]VALID_ARCHS: arm64+ FRAMEWORK_SEARCH_PATHS[arch=x86_64]: $(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION)+ FRAMEWORK_SEARCH_PATHS[arch=arm64]: $(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION)LIBRARY_SEARCH_PATHS[arch=x86_64]: $(inherited) $(PROJECT_DIR)/Externals/x86_64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME) $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)LIBRARY_SEARCH_PATHS[arch=arm64]: $(inherited) $(PROJECT_DIR)/Externals/arm64/$(CONFIGURATION) $(SDKROOT)/usr/lib/swift $(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME) $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES: true@@ -101,6 +112,8 @@ targets:embed: true- framework: libapp.aembed: false+ - package: CallKitPlugin+ product: tauri-plugin-call-kit- sdk: CoreGraphics.framework- sdk: Metal.framework- sdk: MetalKit.framework@@ -172,4 +185,4 @@ targets:CODE_SIGN_ALLOW_ENTITLEMENTS_MODIFICATION: YESARCHS: [arm64]VALID_ARCHS: arm64- EXCLUDED_ARCHS[sdk=iphoneos*]: x86_64\ No newline at end of file+ EXCLUDED_ARCHS[sdk=iphoneos*]: x86_64