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]: call kit plugin (#3095)
Peter Chinman8acdaed06f4f
diff --git a/infra/stacks/cloud-storage-service/cloud-storage-service.ts b/infra/stacks/cloud-storage-service/cloud-storage-service.tsindex 3c8f90c19f..1e4df6c2e1 100644--- a/infra/stacks/cloud-storage-service/cloud-storage-service.ts+++ b/infra/stacks/cloud-storage-service/cloud-storage-service.ts@@ -38,6 +38,7 @@ type CreateCloudStorageServiceServiceArgs = {secretKeyArns: (pulumi.Output<string> | string)[];queueArns: (pulumi.Output<string> | string)[];callRecordingCrudPolicyArn: pulumi.Output<string> | string;+ snsPlatformArns: (pulumi.Output<string> | string)[];tags: { [key: string]: string };};@@ -70,6 +71,7 @@ export class CloudStorageService extends pulumi.ComponentResource {secretKeyArns,queueArns,callRecordingCrudPolicyArn,+ snsPlatformArns,tags,}: CreateCloudStorageServiceServiceArgs,opts?: pulumi.ComponentResourceOptions@@ -155,6 +157,31 @@ export class CloudStorageService extends pulumi.ComponentResource {{ parent: this });+ const snsPolicy = new aws.iam.Policy(+ `${BASE_NAME}-sns-policy`,+ {+ name: `${BASE_NAME}-sns-policy-${stack}`,+ policy: {+ Version: '2012-10-17',+ Statement: [+ {+ Action: [+ 'sns:CreatePlatformEndpoint',+ 'sns:DeleteEndpoint',+ 'sns:GetEndpointAttributes',+ 'sns:SetEndpointAttributes',+ 'sns:Publish',+ ],+ Resource: snsPlatformArns,+ Effect: 'Allow',+ },+ ],+ },+ tags: this.tags,+ },+ { parent: this }+ );+this.role = new aws.iam.Role(`${BASE_NAME}-role`,{@@ -219,6 +246,15 @@ export class CloudStorageService extends pulumi.ComponentResource {});+ new aws.iam.RolePolicyAttachment(+ `${BASE_NAME}-role-sns-att-${stack}`,+ {+ role: this.role,+ policyArn: snsPolicy.arn,+ },+ { parent: this, dependsOn: [snsPolicy, this.role] }+ );+// ecr imageconst image = new EcrImage(`${BASE_NAME}-ecr-image-${stack}`,diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 0c1eedd633..1af5d5365f 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -186,6 +186,19 @@ const contactsQueueArn: pulumi.Output<string> = contactsServiceStackconst { notificationIngressQueueName, notificationIngressQueueArn } =getMacroNotify();+const notificationServiceStack = new pulumi.StackReference(+ 'notification-service-stack',+ { name: `macro-inc/notification-service/${stack}` }+);+const snsApnsVoipPlatformArn: pulumi.Output<string> = notificationServiceStack+ .getOutput('notificationApnsVoipPlatformArn')+ .apply((arn) => arn as string);++const appleBundleId = config.require('apple_bundle_id');+const APPLE_BUNDLE_ID = aws.secretsmanager+ .getSecretVersionOutput({ secretId: appleBundleId })+ .apply((secret) => secret.secretString);+// To re-use this secret name after a destroy, you will need to delete the secret without recovery to prevent conflict:// aws secretsmanager delete-secret --secret-id ${CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME} --force-delete-without-recoveryconst CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME = `linksharing-private-key-${stack}`;@@ -379,6 +392,7 @@ const cloudStorageService = new CloudStorageService(calEventTypeContentNamesKeyArn,],callRecordingCrudPolicyArn,+ snsPlatformArns: [snsApnsVoipPlatformArn],containerEnvVars: [{name: 'CALL_RECORDING_S3_BUCKET',@@ -596,6 +610,14 @@ const cloudStorageService = new CloudStorageService(name: 'META_ACCESS_TOKEN',value: pulumi.interpolate`${META_ACCESS_TOKEN}`,},+ {+ name: 'APPLE_BUNDLE_ID',+ value: pulumi.interpolate`${APPLE_BUNDLE_ID}`,+ },+ {+ name: 'SNS_APNS_VOIP_PLATFORM_ARN',+ value: pulumi.interpolate`${snsApnsVoipPlatformArn}`,+ },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/infra/stacks/notification-service/index.ts b/infra/stacks/notification-service/index.tsindex 19b64bb0eb..5e511541f9 100644--- a/infra/stacks/notification-service/index.ts+++ b/infra/stacks/notification-service/index.ts@@ -136,6 +136,20 @@ const notificationApnsPlatform = new aws.sns.PlatformApplication(});+const notificationApnsVoipPlatform = new aws.sns.PlatformApplication(+ 'notification-apns-voip-platform',+ {+ name: `notification-apns-voip-platform-${stack}`,+ platform: stack === 'prod' ? 'APNS_VOIP' : 'APNS_VOIP_SANDBOX',+ applePlatformTeamId: APPLE_TEAM_ID,+ applePlatformBundleId: pulumi.interpolate`${APPLE_BUNDLE_ID}.voip`,+ platformPrincipal: APNS_KEY_ID,+ platformCredential: APNS_PRIVATE_KEY,+ eventDeliveryFailureTopicArn: pushNotificationEventHandlerTopicArn,+ eventEndpointDeletedTopicArn: pushNotificationEventHandlerTopicArn,+ }+);+const notificationFcmPlatform = new aws.sns.PlatformApplication('notification-fcm-platform',{@@ -154,8 +168,10 @@ export const notificationIngressQueueArn = notificationIngressQueue.queue.arn;export const notificationIngressQueueName = notificationIngressQueue.queue.name;export const notificationSnsPlatformArns = [notificationApnsPlatform.arn,+ notificationApnsVoipPlatform.arn,notificationFcmPlatform.arn,];+export const notificationApnsVoipPlatformArn = notificationApnsVoipPlatform.arn;const MACRO_API_TOKENS = getMacroApiToken();@@ -242,6 +258,10 @@ const notificationService = new NotificationService('notification-service', {name: 'SNS_FCM_PLATFORM_ARN',value: pulumi.interpolate`${notificationFcmPlatform.arn}`,},+ {+ name: 'SNS_APNS_VOIP_PLATFORM_ARN',+ value: pulumi.interpolate`${notificationApnsVoipPlatform.arn}`,+ },{name: 'SENDER_BASE_ADDRESS',value: 'notification.macro.com',diff --git a/js/app/packages/channel/Call/index.ts b/js/app/packages/channel/Call/index.tsindex 2fa12e0e0f..890821da18 100644--- a/js/app/packages/channel/Call/index.ts+++ b/js/app/packages/channel/Call/index.ts@@ -23,6 +23,7 @@ export { CallEventSync } from './CallEventSync';export { CallStartedNotifier } from './CallStartedNotifier';export { joinChannelCall } from './join-channel-call';export { openChannelCallTab } from './open-channel-call-tab';+export { useCallKitSetup } from './use-callkit';export {InCallPanel,InCallParticipantsListPopover,diff --git a/js/app/packages/channel/Call/use-call.ts b/js/app/packages/channel/Call/use-call.tsindex 35aedc0115..992df86f75 100644--- a/js/app/packages/channel/Call/use-call.ts+++ b/js/app/packages/channel/Call/use-call.ts@@ -1,11 +1,12 @@+import { throwOnErr } from '@core/util/maybeResult';import { useLeaveCallMutation } from '@queries/call/call';import { queryClient } from '@queries/client';-import { useMutation } from '@tanstack/solid-query';import { callServiceClient } from '@service-call/client';-import { throwOnErr } from '@core/util/maybeResult';+import { useMutation } from '@tanstack/solid-query';import { RoomEvent } from 'livekit-client';-import { createSignal, onCleanup } from 'solid-js';+import { createEffect, createSignal, onCleanup } from 'solid-js';import { useCallContext } from './CallContext';+import { endCallKitCall, registerCallKitCallEndedHandler } from './use-callkit';type UseCallOptions = {/** Called after successfully joining a call. */@@ -20,6 +21,11 @@ type JoinCallContext = {const JOIN_TIMEOUT_MS = 15_000;+// Module-level guard: only one leave can be in flight at a time across all+// useCall() instances. Prevents a user-initiated leave and a concurrent+// CallKit call-ended event from both proceeding to disconnect+leaveMutation.+let leaveInFlight = false;+/*** Hook that orchestrates joining/leaving calls by combining* the API mutations with the LiveKit room connection.@@ -56,6 +62,19 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {onCleanup(() => cleanupDisconnectListener?.());+ createEffect(() => {+ if (!callCtx.isInCall() || callCtx.activeChannelId() !== channelId())+ return;++ const unregister = registerCallKitCallEndedHandler(() =>+ leaveCall({ endNativeCall: false }).catch((e) =>+ console.error('callkit: failed to leave ended call', e)+ )+ );++ onCleanup(unregister);+ });+/** Cleared in `joinCall` `finally` + safety timer so Try again never stays disabled if TanStack pending glitches. */const [joinUiPending, setJoinUiPending] = createSignal(false);@@ -139,17 +158,34 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {}};- async function leaveCall() {+ async function leaveCall(leaveOptions?: { endNativeCall?: boolean }) {+ if (leaveInFlight) return;+ leaveInFlight = true;const id = channelId();// Detach before disconnect so the RoomEvent.Disconnected handler// doesn't double-fire onLeave.cleanupDisconnectListener?.();cleanupDisconnectListener = null;+ // 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 {- await callCtx.disconnect();- options?.onLeave?.();+ if (leaveOptions?.endNativeCall !== false) {+ try {+ await endCallKitCall();+ } catch (e) {+ console.error('callkit: failed to dismiss call sheet', e);+ }+ }+ try {+ await callCtx.disconnect();+ options?.onLeave?.();+ } finally {+ await leaveMutation.mutateAsync(id);+ }} finally {- await leaveMutation.mutateAsync(id);+ leaveInFlight = false;}}diff --git a/js/app/packages/channel/Call/use-callkit.ts b/js/app/packages/channel/Call/use-callkit.tsnew file mode 100644index 0000000000..6aee6f426a--- /dev/null+++ b/js/app/packages/channel/Call/use-callkit.ts@@ -0,0 +1,130 @@+import { isPlatform, isTauri } from '@core/util/platform';+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 { joinChannelCall } from './join-channel-call';++// 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 CallEndedPayload = { callId: string };+type CallEndedHandler = (payload: CallEndedPayload) => void | Promise<void>;++const callEndedHandlers: CallEndedHandler[] = [];++/**+ * Registers channel-scoped cleanup for native CallKit end events.+ *+ * `useCallKitSetup` owns the single global Tauri listener, while `useCall()`+ * registers the active channel's leave handler here. If multiple channel UI+ * surfaces are mounted, the most recently registered active handler wins; when+ * it unmounts, the previous active handler becomes available again.+ */+export function registerCallKitCallEndedHandler(+ handler: CallEndedHandler+): () => void {+ callEndedHandlers.push(handler);+ return () => {+ const index = callEndedHandlers.lastIndexOf(handler);+ if (index !== -1) callEndedHandlers.splice(index, 1);+ };+}++function getActiveCallEndedHandler(): CallEndedHandler | undefined {+ return callEndedHandlers[callEndedHandlers.length - 1];+}++/**+ * Sets up CallKit / PushKit integration for iOS.+ *+ * - Registers VoIP tokens with the backend as they arrive from PushKit.+ * - When the user answers via the native incoming-call sheet, navigates to the+ * channel and joins the call via the existing deep-link flow.+ *+ * Must be mounted once at app startup on iOS (no-op on all other platforms).+ */+export function useCallKitSetup() {+ onMount(() => {+ if (!isTauri() || !isPlatform('ios')) return;++ let cleaned = false;+ const unlistens: Array<() => void> = [];+ onCleanup(() => {+ cleaned = true;+ unlistens.forEach((u) => u());+ });++ // 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);+ });+ }++ track(+ listen<VoipTokenPayload>(+ 'plugin:call-kit:voip-token-updated',+ async (event) => {+ const { token } = event.payload;+ await notificationServiceClient+ .registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP })+ .catch((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)+ );+ })+ );++ // Drain any VoIP token that arrived from PushKit before the listener above+ // was registered (common on first launch).+ invoke<{ token: string | null }>('plugin:call-kit|get_voip_token')+ .then(({ token }) => {+ if (!token) return;+ return notificationServiceClient+ .registerDevice({ token, deviceType: DEVICE_TYPE_IOS_VOIP })+ .catch((err) =>+ console.error('callkit: failed to register cached VoIP token', err)+ );+ })+ .catch((err) => console.error('callkit: get_voip_token failed', err));+ });+}++/**+ * Tells CallKit to end the active call session.+ *+ * Call this from `leaveCall()` so the native system call UI is dismissed when+ * the user leaves from within the app rather than from the CallKit sheet.+ */+export async function endCallKitCall(): Promise<void> {+ if (!isTauri() || !isPlatform('ios')) return;+ await invoke('plugin:call-kit|end_active_call').catch((err) =>+ console.error('callkit: failed to end active call', err)+ );+}diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/deviceType.ts b/js/app/packages/service-clients/service-notification/generated/schemas/deviceType.tsindex 05b9e06b11..a27e55c588 100644--- a/js/app/packages/service-clients/service-notification/generated/schemas/deviceType.ts+++ b/js/app/packages/service-clients/service-notification/generated/schemas/deviceType.ts@@ -11,4 +11,5 @@ export type DeviceType = (typeof DeviceType)[keyof typeof DeviceType];export const DeviceType = {ios: 'ios',android: 'android',+ iosvoip: 'iosvoip',} as const;diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.jsonindex a6fcd698e4..bf00327002 100644--- a/js/app/packages/service-clients/service-notification/openapi.json+++ b/js/app/packages/service-clients/service-notification/openapi.json@@ -1388,7 +1388,7 @@},"DeviceType": {"type": "string",- "enum": ["ios", "android"]+ "enum": ["ios", "android", "iosvoip"]},"DocumentMentionMetadata": {"type": "object",diff --git a/js/app/packages/tauri/src/TauriProvider.tsx b/js/app/packages/tauri/src/TauriProvider.tsxindex acf673aa4d..398df0b62c 100644--- a/js/app/packages/tauri/src/TauriProvider.tsx+++ b/js/app/packages/tauri/src/TauriProvider.tsx@@ -1,4 +1,4 @@-import { isTauri } from '@core/util/platform';+import { isPlatform, isTauri } from '@core/util/platform';import { PlatformNotificationProvider } from '@notifications';import type { RouteSectionProps } from '@solidjs/router';import { type OsType, type as osType } from '@tauri-apps/plugin-os';@@ -19,6 +19,7 @@ import { invoke } from '@tauri-apps/api/core';import { listen } from '@tauri-apps/api/event';import { useTauriNavigationEffect } from './navigation';import { MaybePushNotificationRegistration } from './PushNotification';+import { useCallKitSetup } from '@channel/Call';import { ShareTargetProvider } from './ShareTargetProvider';type NotAndroid = 'not-android';@@ -66,6 +67,8 @@ function TauriProvider(props: { children: JSX.Element }) {grantBundleUpdate();}+ if (isTauri() && isPlatform('ios')) useCallKitSetup();+const value: TauriContextValue = {runtimeInsets: insets,os: osType(),diff --git a/js/app/tauri/Cargo.lock b/js/app/tauri/Cargo.lockindex f3c265c0fe..edaa05d7cc 100644--- a/js/app/tauri/Cargo.lock+++ b/js/app/tauri/Cargo.lock@@ -106,6 +106,7 @@ dependencies = ["tauri","tauri-build","tauri-plugin-auth",+ "tauri-plugin-call-kit","tauri-plugin-deep-link","tauri-plugin-device-info","tauri-plugin-haptics",@@ -5404,6 +5405,14 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "tauri-plugin-call-kit"+version = "0.1.0"+dependencies = [+ "tauri",+ "tauri-plugin",+]+[[package]]name = "tauri-plugin-deep-link"version = "2.4.5"diff --git a/js/app/tauri/Cargo.toml b/js/app/tauri/Cargo.tomlindex ee808c9e95..aab772040e 100644--- a/js/app/tauri/Cargo.toml+++ b/js/app/tauri/Cargo.toml@@ -1,5 +1,6 @@[workspace]members = [+ "callkit_plugin","input_accessory_plugin","logger","macro_bundle_updater_plugin",diff --git a/js/app/tauri/callkit_plugin/.gitignore b/js/app/tauri/callkit_plugin/.gitignorenew file mode 100644index 0000000000..a2ba4dd574--- /dev/null+++ b/js/app/tauri/callkit_plugin/.gitignore@@ -0,0 +1,6 @@+# Swift Package Manager build artifacts+ios/.build/+ios/Package.resolved++# Tauri-generated Swift API (placed here by `cargo tauri ios build`)+.tauri/diff --git a/js/app/tauri/callkit_plugin/Cargo.toml b/js/app/tauri/callkit_plugin/Cargo.tomlnew file mode 100644index 0000000000..ad3af53adc--- /dev/null+++ b/js/app/tauri/callkit_plugin/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "tauri-plugin-call-kit"+version = "0.1.0"+edition = "2024"+links = "tauri-plugin-call-kit"++[build-dependencies]+tauri-plugin = { version = "2.4", features = ["build"] }++[dependencies]+tauri = { workspace = true }++[target.'cfg(target_os = "ios")'.dependencies]+tauri = { workspace = true, features = ["wry"] }diff --git a/js/app/tauri/callkit_plugin/build.rs b/js/app/tauri/callkit_plugin/build.rsnew file mode 100644index 0000000000..d72a9dc168--- /dev/null+++ b/js/app/tauri/callkit_plugin/build.rs@@ -0,0 +1,6 @@+fn main() {+ tauri_plugin::Builder::new(&[])+ .ios_path("ios")+ .try_build()+ .unwrap();+}diff --git a/js/app/tauri/callkit_plugin/ios/.gitignore b/js/app/tauri/callkit_plugin/ios/.gitignorenew file mode 100644index 0000000000..1d84acb376--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/.gitignore@@ -0,0 +1,3 @@+.build/+.swiftpm/+*.xcodeproj/diff --git a/js/app/tauri/callkit_plugin/ios/Package.swift b/js/app/tauri/callkit_plugin/ios/Package.swiftnew file mode 100644index 0000000000..437e9836ca--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Package.swift@@ -0,0 +1,29 @@+// swift-tools-version:5.3+import PackageDescription++let package = Package(+ name: "tauri-plugin-call-kit",+ platforms: [+ .macOS(.v10_13),+ .iOS(.v14),+ ],+ products: [+ .library(+ name: "tauri-plugin-call-kit",+ type: .static,+ targets: ["tauri-plugin-call-kit"]+ )+ ],+ dependencies: [+ .package(name: "Tauri", path: "../.tauri/tauri-api")+ ],+ targets: [+ .target(+ name: "tauri-plugin-call-kit",+ dependencies: [+ .byName(name: "Tauri")+ ],+ path: "Sources"+ )+ ]+)diff --git a/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift b/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swiftnew file mode 100644index 0000000000..bf5064b27f--- /dev/null+++ b/js/app/tauri/callkit_plugin/ios/Sources/CallKitPlugin.swift@@ -0,0 +1,158 @@+import CallKit+import PushKit+import Tauri+import WebKit++class CallKitPlugin: Plugin, CXProviderDelegate, PKPushRegistryDelegate {+ private var provider: CXProvider!+ private let callController = CXCallController()+ private var registry: PKPushRegistry!++ // Keyed by call UUID — holds the channelId so it's available when CXAnswerCallAction fires.+ private var pendingCalls: [UUID: String] = [:]++ // The UUID of the most recently reported incoming call, used by endActiveCall.+ private var activeCallUUID: UUID?++ // Last VoIP token received from PushKit; may arrive before the JS listener is ready.+ private var cachedVoipToken: String?++ 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()+ }+ return+ }++ // 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)+ }++ pendingCalls[uuid] = channelId+ activeCallUUID = uuid++ let update = CXCallUpdate()+ update.remoteHandle = CXHandle(type: .generic, value: channelId)+ update.localizedCallerName = callerName+ update.hasVideo = false++ // 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 }+ }+ completion()+ }+ }++ // MARK: - CXProviderDelegate++ public func providerDidReset(_ provider: CXProvider) {+ pendingCalls.removeAll()+ activeCallUUID = nil+ }++ public func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {+ guard let channelId = pendingCalls[action.callUUID] else {+ action.fail()+ return+ }+ 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 }+ }++ // MARK: - Tauri commands++ /// 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])+ }++ /// 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 {+ 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+ }+ invoke.resolve()+ }+ }+}++@_cdecl("init_plugin_call_kit")+func initPlugin() -> Plugin {+ return CallKitPlugin()+}diff --git a/js/app/tauri/callkit_plugin/src/lib.rs b/js/app/tauri/callkit_plugin/src/lib.rsnew file mode 100644index 0000000000..5031d5603a--- /dev/null+++ b/js/app/tauri/callkit_plugin/src/lib.rs@@ -0,0 +1,28 @@+//! Tauri plugin that integrates iOS CallKit and PushKit for a native+//! incoming-call UI.+//!+//! On iOS the plugin registers a Swift `CXProvider`/`PKPushRegistry`+//! implementation (`init_plugin_call_kit`) that displays the system+//! incoming-call screen, handles answer/end actions, and delivers VoIP push+//! tokens to the JS layer. On all other platforms the plugin is a no-op.+#![deny(missing_docs)]++#[cfg(target_os = "ios")]+tauri::ios_plugin_binding!(init_plugin_call_kit);++/// Builds and returns the `call-kit` Tauri plugin.+///+/// On iOS, registers the Swift `CallKitPlugin` via `init_plugin_call_kit`,+/// which wires up `CXProvider`, `PKPushRegistry`, and the Tauri event bridge.+/// On all other platforms the setup closure is a no-op.+///+/// Pass the result directly to [`tauri::Builder::plugin`].+pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {+ tauri::plugin::Builder::new("call-kit")+ .setup(|_app, _api| {+ #[cfg(target_os = "ios")]+ _api.register_ios_plugin(init_plugin_call_kit)?;+ Ok(())+ })+ .build()+}diff --git a/js/app/tauri/src-tauri/Cargo.toml b/js/app/tauri/src-tauri/Cargo.tomlindex 450b46fea1..2787a530b7 100644--- a/js/app/tauri/src-tauri/Cargo.toml+++ b/js/app/tauri/src-tauri/Cargo.toml@@ -70,6 +70,7 @@ tauri-plugin-auth = { git = "https://github.com/macro-inc/tauri-plugins", rev =tauri-plugin-haptics = "2"[target.'cfg(target_os = "ios")'.dependencies]+tauri-plugin-call-kit = { path = "../callkit_plugin" }tauri-plugin-input-accessory = { path = "../input_accessory_plugin" }# Used to call NSFileManager from Rust to get the App Group container path.# This version is already in the dependency tree via wry/tao.diff --git a/js/app/tauri/src-tauri/Info.ios.plist b/js/app/tauri/src-tauri/Info.ios.plistindex 54753189ad..999f611302 100644--- a/js/app/tauri/src-tauri/Info.ios.plist+++ b/js/app/tauri/src-tauri/Info.ios.plist@@ -2,6 +2,10 @@<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict>+ <key>UIBackgroundModes</key>+ <array>+ <string>voip</string>+ </array><key>LSApplicationQueriesSchemes</key><array><string>macro</string>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 fdc77d8181..4dad4ce258 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@@ -64,5 +64,9 @@<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/src/lib.rs b/js/app/tauri/src-tauri/src/lib.rsindex 2f16f076aa..789f1b6a34 100644--- a/js/app/tauri/src-tauri/src/lib.rs+++ b/js/app/tauri/src-tauri/src/lib.rs@@ -97,7 +97,8 @@ pub fn run() {{builder = builder.plugin(tauri_plugin_haptics::init())- .plugin(tauri_plugin_input_accessory::init());+ .plugin(tauri_plugin_input_accessory::init())+ .plugin(tauri_plugin_call_kit::init());}// register the rest of the common pluginsdiff --git a/rust/cloud-storage/.sqlx/query-19c878ce5817c5643e48a6159fce81a2f964defcb7b190460f2b16ac67078766.json b/rust/cloud-storage/.sqlx/query-19c878ce5817c5643e48a6159fce81a2f964defcb7b190460f2b16ac67078766.jsonindex afeebdd674..7df56bcc2a 100644--- a/rust/cloud-storage/.sqlx/query-19c878ce5817c5643e48a6159fce81a2f964defcb7b190460f2b16ac67078766.json+++ b/rust/cloud-storage/.sqlx/query-19c878ce5817c5643e48a6159fce81a2f964defcb7b190460f2b16ac67078766.json@@ -18,7 +18,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json b/rust/cloud-storage/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.jsonindex 01cece9642..ee1916f8f5 100644--- a/rust/cloud-storage/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json+++ b/rust/cloud-storage/.sqlx/query-270cd8ae6b47508cb7e4e920bd76cb0f6177d685bddedb06f1892d0014af6f01.json@@ -18,7 +18,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json b/rust/cloud-storage/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.jsonindex ad14cfedba..dead84e7bf 100644--- a/rust/cloud-storage/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json+++ b/rust/cloud-storage/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json@@ -22,7 +22,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json b/rust/cloud-storage/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.jsonindex e5d913399d..2ae6f0e18e 100644--- a/rust/cloud-storage/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json+++ b/rust/cloud-storage/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json@@ -15,7 +15,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-d185f3b4ca09c5a6372f6a64c4e6e5e12937814433dc5499b0dfdbe882c76192.json b/rust/cloud-storage/.sqlx/query-d185f3b4ca09c5a6372f6a64c4e6e5e12937814433dc5499b0dfdbe882c76192.jsonindex 0b63e72e63..37b3c65667 100644--- a/rust/cloud-storage/.sqlx/query-d185f3b4ca09c5a6372f6a64c4e6e5e12937814433dc5499b0dfdbe882c76192.json+++ b/rust/cloud-storage/.sqlx/query-d185f3b4ca09c5a6372f6a64c4e6e5e12937814433dc5499b0dfdbe882c76192.json@@ -22,7 +22,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-d5db55179b8f46b8788f1cc573b0734a33e800cd3fd990498c76c991b48931a8.json b/rust/cloud-storage/.sqlx/query-d5db55179b8f46b8788f1cc573b0734a33e800cd3fd990498c76c991b48931a8.jsonindex bb751d673e..ad5a0976fe 100644--- a/rust/cloud-storage/.sqlx/query-d5db55179b8f46b8788f1cc573b0734a33e800cd3fd990498c76c991b48931a8.json+++ b/rust/cloud-storage/.sqlx/query-d5db55179b8f46b8788f1cc573b0734a33e800cd3fd990498c76c991b48931a8.json@@ -15,7 +15,8 @@"kind": {"Enum": ["ios",- "android"+ "android",+ "iosvoip"]}}diff --git a/rust/cloud-storage/.sqlx/query-dedb4996ddd1f4a5a44ce96d8ab9e7ad85d35c823d233e6d9b53534c5aaf94b0.json b/rust/cloud-storage/.sqlx/query-dedb4996ddd1f4a5a44ce96d8ab9e7ad85d35c823d233e6d9b53534c5aaf94b0.jsonnew file mode 100644index 0000000000..6e0e82479b--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-dedb4996ddd1f4a5a44ce96d8ab9e7ad85d35c823d233e6d9b53534c5aaf94b0.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n NULLIF(mui.first_name, 'N/A') AS first_name,\n NULLIF(mui.last_name, 'N/A') AS last_name\n FROM macro_user_info mui\n JOIN \"User\" u ON mui.macro_user_id = u.macro_user_id\n WHERE u.id = $1\n LIMIT 1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "first_name",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "last_name",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "dedb4996ddd1f4a5a44ce96d8ab9e7ad85d35c823d233e6d9b53534c5aaf94b0"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 945f451564..0e31fee8fb 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3194,6 +3194,7 @@ dependencies = ["aws-sdk-dynamodb","aws-sdk-s3","aws-sdk-secretsmanager",+ "aws-sdk-sns","aws-sdk-sqs","axum","axum-extra",diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex f25622f1a5..abd48b34c2 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -257,6 +257,7 @@ pub async fn build_tool_service_context_from_env(PlatformArnConfig {apns_platform_arn: String::new(),fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),},);let notification_tool_context =diff --git a/rust/cloud-storage/call/src/domain/ports.rs b/rust/cloud-storage/call/src/domain/ports.rsindex f4a24a3fa6..a2fca49f3d 100644--- a/rust/cloud-storage/call/src/domain/ports.rs+++ b/rust/cloud-storage/call/src/domain/ports.rs@@ -171,6 +171,13 @@ pub trait CallRepository: Send + Sync + 'static {user_id: MacroUserIdStr<'a>,) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+ /// Get the display name (first + last) for a user. Returns `None` if neither+ /// field is set or both are the sentinel "N/A".+ fn get_user_display_name<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;+/// Fetch a full [`CallRecord`] by call id. Looks in both the active/// `calls` table and the archived `call_records` table; returns `None`/// if neither has a matching row. The returned record includes thediff --git a/rust/cloud-storage/call/src/domain/service.rs b/rust/cloud-storage/call/src/domain/service.rsindex 6c3cf35acf..c8dd30ce29 100644--- a/rust/cloud-storage/call/src/domain/service.rs+++ b/rust/cloud-storage/call/src/domain/service.rs@@ -10,15 +10,18 @@ use entity_access::domain::models::{use entity_access::domain::ports::EntityAccessService;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::apple::VoipPushPayload;use notification::domain::models::apple::{APNSPushNotification, Alert, AlertDictionary, Aps, PushNotificationData,};use notification::domain::models::{NotifCollapseKey, Notification, NotificationExtIos, SendNotificationRequestBuilder,};+use notification::domain::ports::VoipPushSender;use notification::domain::service::NotificationIngress;use serde::{Deserialize, Serialize};use std::collections::HashSet;+use uuid::Uuid;use crate::domain::models::{EditCallRecordRequest, EditCallTranscriptRequest};@@ -44,6 +47,7 @@ pub struct CallServiceImpl<S: RecordingStorage,Sm: CallSummarizer = NoopCallSummarizer,I: CallSearchIndexer = NoOpCallSearchIndexer,+ V: VoipPushSender = (),> {repo: R,rtc_client: C,@@ -56,6 +60,7 @@ pub struct CallServiceImpl<egress_s3_config: Option<EgressS3Config>,internal_call_secret: Option<String>,summarizer: Option<Sm>,+ voip_push_sender: V,}impl<@@ -66,7 +71,7 @@ impl<N: NotificationIngress,S: RecordingStorage,Sm: CallSummarizer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer>+> CallServiceImpl<R, C, Cn, E, N, S, Sm, NoOpCallSearchIndexer, ()>{/// Create a new call service.pub fn new(@@ -90,6 +95,7 @@ impl<egress_s3_config: None,internal_call_secret: None,summarizer: None,+ voip_push_sender: (),}}}@@ -103,7 +109,8 @@ impl<S: RecordingStorage,Sm: CallSummarizer,I: CallSearchIndexer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I>+ V: VoipPushSender,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>{/// Enable auto-recording with the given S3 configuration.pub fn with_egress(mut self, s3_config: EgressS3Config) -> Self {@@ -124,11 +131,33 @@ impl<self}+ /// Attach a VoIP push sender so incoming-call PushKit notifications are+ /// delivered when a new call is created.+ pub fn with_voip_push_sender<V2: VoipPushSender>(+ self,+ sender: V2,+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V2> {+ CallServiceImpl {+ repo: self.repo,+ rtc_client: self.rtc_client,+ connection_service: self.connection_service,+ entity_access_service: self.entity_access_service,+ notification_ingress: self.notification_ingress,+ recording_storage: self.recording_storage,+ search_indexer: self.search_indexer,+ server_url: self.server_url,+ egress_s3_config: self.egress_s3_config,+ internal_call_secret: self.internal_call_secret,+ summarizer: self.summarizer,+ voip_push_sender: sender,+ }+ }+/// Swap the search indexer.pub fn with_search_indexer<I2: CallSearchIndexer>(self,indexer: I2,- ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2> {+ ) -> CallServiceImpl<R, C, Cn, E, N, S, Sm, I2, V> {CallServiceImpl {repo: self.repo,rtc_client: self.rtc_client,@@ -141,6 +170,7 @@ impl<egress_s3_config: self.egress_s3_config,internal_call_secret: self.internal_call_secret,summarizer: self.summarizer,+ voip_push_sender: self.voip_push_sender,}}@@ -222,6 +252,20 @@ impl<}}+fn exclude_voip_recipients<'a>(+ recipient_ids: HashSet<MacroUserIdStr<'a>>,+ voip_recipient_ids: &HashSet<MacroUserIdStr<'static>>,+) -> HashSet<MacroUserIdStr<'a>> {+ recipient_ids+ .into_iter()+ .filter(|recipient_id| {+ !voip_recipient_ids+ .iter()+ .any(|voip_recipient_id| voip_recipient_id.as_ref() == recipient_id.as_ref())+ })+ .collect()+}+#[derive(Serialize, Deserialize, Clone)]struct CallStartedNotification {sender_profile_picture_url: Option<String>,@@ -280,7 +324,8 @@ impl<S: RecordingStorage,Sm: CallSummarizer + Clone,I: CallSearchIndexer,-> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I>+ V: VoipPushSender,+> CallService for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>{fn validate_internal_call(&self, token: &str) -> bool {self.internal_call_secret@@ -380,7 +425,7 @@ impl<).await;- // Send push notification to channel members (best-effort).+ // Send push notification and VoIP push to channel members (best-effort).let _: Result<(), anyhow::Error> = async {let channel_name = self.repo@@ -404,23 +449,52 @@ impl<.ok().flatten();- let req = SendNotificationRequestBuilder {- notification_entity: EntityType::Channel- .with_entity_string(channel_id_str),- notification: CallStartedNotification {- sender_profile_picture_url,- channel_name,- },- sender_id: Some(user_id.copied()),- recipient_ids,- }- .into_request()- .with_apns();-- self.notification_ingress- .send_notification(req)+ let caller_name = self+ .repo+ .get_user_display_name(user_id.copied()).await- .map_err(|e| anyhow::anyhow!(e))?;+ .ok()+ .flatten()+ .unwrap_or_else(|| user_id.email_str().to_string());++ // Send VoIP push for the native iOS incoming-call sheet first.+ // Recipients with successful VoIP delivery do not need the regular+ // APNS alert banner as well.+ let recipient_vec: Vec<MacroUserIdStr<'_>> =+ recipient_ids.iter().cloned().collect();+ let voip_payload = VoipPushPayload {+ call_id: call.id.to_string(),+ channel_id: channel_id_str.clone(),+ channel_name: channel_name.clone().unwrap_or_default(),+ caller_name,+ };+ let voip_recipient_ids = self+ .voip_push_sender+ .send_voip_push(&recipient_vec, &voip_payload)+ .await;++ let apns_recipient_ids =+ exclude_voip_recipients(recipient_ids, &voip_recipient_ids);++ if !apns_recipient_ids.is_empty() {+ let req = SendNotificationRequestBuilder {+ notification_entity: EntityType::Channel+ .with_entity_string(channel_id_str.clone()),+ notification: CallStartedNotification {+ sender_profile_picture_url,+ channel_name: channel_name.clone(),+ },+ sender_id: Some(user_id.copied()),+ recipient_ids: apns_recipient_ids,+ }+ .into_request()+ .with_apns();++ self.notification_ingress+ .send_notification(req)+ .await+ .map_err(|e| anyhow::anyhow!(e))?;+ }Ok(())}@@ -1090,7 +1164,8 @@ impl<S: RecordingStorage,Sm: CallSummarizer + Clone,I: CallSearchIndexer,-> CallServiceImpl<R, C, Cn, E, N, S, Sm, I>+ V: VoipPushSender,+> CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V>{/// Fire-and-forget spawn of [`CallService::summarize_call`] for `call_id`.///diff --git a/rust/cloud-storage/call/src/domain/service/test.rs b/rust/cloud-storage/call/src/domain/service/test.rsindex 2baef8a01a..cb5248a6a7 100644--- a/rust/cloud-storage/call/src/domain/service/test.rs+++ b/rust/cloud-storage/call/src/domain/service/test.rs@@ -1,4 +1,12 @@-use super::extract_recording_key;+use std::collections::HashSet;++use macro_user_id::user_id::MacroUserIdStr;++use super::{exclude_voip_recipients, extract_recording_key};++fn user(email: &'static str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).unwrap()+}#[test]fn extract_key_from_full_s3_url() {@@ -20,3 +28,27 @@ fn extract_key_from_bare_calls_path() {let url = "calls/abc-123/recording.mp4";assert_eq!(extract_recording_key(url), "abc-123/recording.mp4");}++#[test]+fn exclude_voip_recipients_keeps_users_without_voip_delivery() {+ let alice = user("[email protected]");+ let bob = user("[email protected]");+ let recipients = HashSet::from([alice.clone(), bob.clone()]);+ let voip_recipients = HashSet::from([alice]);++ let filtered = exclude_voip_recipients(recipients, &voip_recipients);++ assert_eq!(filtered, HashSet::from([bob]));+}++#[test]+fn exclude_voip_recipients_returns_empty_when_all_users_received_voip() {+ let alice = user("[email protected]");+ let bob = user("[email protected]");+ let recipients = HashSet::from([alice.clone(), bob.clone()]);+ let voip_recipients = HashSet::from([alice, bob]);++ let filtered = exclude_voip_recipients(recipients, &voip_recipients);++ assert!(filtered.is_empty());+}diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rsindex d2b66b3a74..7e7394e0e1 100644--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs@@ -1238,6 +1238,34 @@ impl CallRepository for PgCallRepo {.map(|opt| opt.flatten())}+ #[tracing::instrument(err, skip(self))]+ async fn get_user_display_name<'a>(+ &self,+ user_id: MacroUserIdStr<'a>,+ ) -> Result<Option<String>, Self::Err> {+ let row = sqlx::query!(+ r#"+ SELECT+ NULLIF(mui.first_name, 'N/A') AS first_name,+ NULLIF(mui.last_name, 'N/A') AS last_name+ FROM macro_user_info mui+ JOIN "User" u ON mui.macro_user_id = u.macro_user_id+ WHERE u.id = $1+ LIMIT 1+ "#,+ user_id.as_ref(),+ )+ .fetch_optional(&self.pool)+ .await?;++ Ok(row.and_then(|r| match (r.first_name, r.last_name) {+ (None, None) => None,+ (None, Some(last)) => Some(last),+ (Some(first), None) => Some(first),+ (Some(first), Some(last)) => Some(format!("{first} {last}")),+ }))+ }+#[tracing::instrument(err, skip(self))]async fn resolve_channel_name<'a>(&self,diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 5bc9e39585..f9e1da530c 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -199,6 +199,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::ArPlatformArnConfig {apns_platform_arn: String::new(),fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),},);let notification_tool_context =diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex a8a83e3509..fe692418f9 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -189,6 +189,7 @@ async fn main() -> anyhow::Result<()> {PlatformArnConfig {apns_platform_arn: String::new(),fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),},);let notification_tool_context =diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 4b7974a51f..84a3e0987a 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -25,6 +25,7 @@ anyhow = { workspace = true }aws-sdk-dynamodb = { workspace = true }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }+aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["macros", "multipart", "tower-log"] }axum-extra = { workspace = true }diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rsindex 57f5fdb90b..6cbdf4ff5b 100644--- a/rust/cloud-storage/document_storage_service/src/api/context.rs+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs@@ -190,6 +190,14 @@ pub(crate) type DssChannelsState =pub(crate) type CallConnectionService =ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>;+/// Type alias for the VoIP push sender (optional at runtime via `Option`).+pub(crate) type DssVoipPushSender = Option<+ notification::domain::service::VoipPushServiceImpl<+ notification::outbound::repository::DbNotificationRepository<sqlx::PgPool>,+ aws_sdk_sns::Client,+ >,+>;+/// Type alias for the call service.pub(crate) type DssCallService = CallServiceImpl<PgCallRepo,@@ -200,6 +208,7 @@ pub(crate) type DssCallService = CallServiceImpl<Option<call::outbound::s3_recording_storage::S3RecordingStorage>,call::outbound::ai_call_summarizer::AiCallSummarizer,crate::service::call_search_indexer::SqsCallSearchIndexer,+ DssVoipPushSender,>;/// Type alias for the call router state.diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rsindex 4b07ba9ceb..9215a650c6 100644--- a/rust/cloud-storage/document_storage_service/src/main.rs+++ b/rust/cloud-storage/document_storage_service/src/main.rs@@ -462,6 +462,39 @@ async fn main() -> anyhow::Result<()> {call_service_builder = call_service_builder.with_egress(config);}+ // VoIP push is optional: enabled only when both env vars are present.+ // APPLE_BUNDLE_ID: the app bundle ID (e.g. "com.macro.app.prod")+ // SNS_APNS_VOIP_PLATFORM_ARN: SNS platform app ARN for APNS_VOIP+ //+ // Option<VoipPushServiceImpl<...>> is used as the type parameter so the+ // type stays stable regardless of whether VoIP push is configured.+ let voip_sender = if let (Ok(bundle_id), Ok(voip_arn)) = (+ std::env::var("APPLE_BUNDLE_ID"),+ std::env::var("SNS_APNS_VOIP_PLATFORM_ARN"),+ ) {+ if voip_arn.is_empty() {+ tracing::warn!("voip push disabled: SNS_APNS_VOIP_PLATFORM_ARN is set but empty");+ None+ } else {+ let voip_repo =+ notification::outbound::repository::DbNotificationRepository::new(db.clone());+ let voip_mobile = notification::outbound::mobile::MobilePushAdapter {+ push_service: aws_sdk_sns::Client::new(&aws_config),+ apns_bundle_id: bundle_id.clone(),+ voip_bundle_id: Some(format!("{}.voip", bundle_id)),+ };+ tracing::info!(bundle_id, voip_arn, "voip push enabled");+ Some(notification::domain::service::VoipPushServiceImpl::new(+ voip_repo,+ voip_mobile,+ ))+ }+ } else {+ tracing::info!("voip push disabled: APPLE_BUNDLE_ID or SNS_APNS_VOIP_PLATFORM_ARN not set");+ None+ };+ let call_service_builder = call_service_builder.with_voip_push_sender(voip_sender);+let call_search_indexer = crate::service::call_search_indexer::SqsCallSearchIndexer::new(Arc::new(sqs_client.clone()),);diff --git a/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.down.sqlnew file mode 100644index 0000000000..a4078b2e40--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.down.sql@@ -0,0 +1,33 @@+-- Rollback: remove 'iosvoip' from notification_device_type_option.+--+-- PREREQUISITE: all rows with device_type = 'iosvoip' must be deleted before+-- running this, otherwise the USING cast below will fail.+--+-- PostgreSQL has no ALTER TYPE ... DROP VALUE, so the only safe approach is:+-- 1. delete/migrate any 'iosvoip' rows+-- 2. create a replacement enum without the value+-- 3. alter the column with an explicit USING cast+-- 4. drop the old enum and rename the replacement+--+-- This script will raise an error and roll back if any 'iosvoip' rows remain.++DO $$+BEGIN+ IF EXISTS (+ SELECT 1 FROM notification_user_device_registration WHERE device_type = 'iosvoip'+ ) THEN+ RAISE EXCEPTION+ 'Cannot remove iosvoip: rows with device_type = ''iosvoip'' still exist in notification_user_device_registration';+ END IF;+END;+$$;++CREATE TYPE notification_device_type_option_new AS ENUM ('ios', 'android');++ALTER TABLE notification_user_device_registration+ ALTER COLUMN device_type TYPE notification_device_type_option_new+ USING device_type::text::notification_device_type_option_new;++DROP TYPE notification_device_type_option;++ALTER TYPE notification_device_type_option_new RENAME TO notification_device_type_option;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.sql b/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.sqlnew file mode 100644index 0000000000..4dc5b187ea--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260501000001_add_iosvoip_device_type.sql@@ -0,0 +1,5 @@+-- NOTE: PostgreSQL does not support removing enum values within a transaction,+-- so this migration is not atomically reversible. See the companion .down.sql+-- for the manual rollback procedure, which requires all 'iosvoip' rows to be+-- deleted before it can run safely.+ALTER TYPE notification_device_type_option ADD VALUE IF NOT EXISTS 'iosvoip';diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex 9aa90affd3..1565a2b151 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -273,6 +273,7 @@ async fn build_tool_context(PlatformArnConfig {apns_platform_arn: String::new(),fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),},);let notification_tool_context =diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rsindex 62966c10be..6fea68add4 100644--- a/rust/cloud-storage/memory/src/context.rs+++ b/rust/cloud-storage/memory/src/context.rs@@ -179,6 +179,7 @@ pub async fn build_tool_service_context(PlatformArnConfig {apns_platform_arn: String::new(),fcm_platform_arn: String::new(),+ apns_voip_platform_arn: String::new(),},);let notification_tool_context =diff --git a/rust/cloud-storage/model_notifications/src/device.rs b/rust/cloud-storage/model_notifications/src/device.rsindex 262279be93..e79ac10177 100644--- a/rust/cloud-storage/model_notifications/src/device.rs+++ b/rust/cloud-storage/model_notifications/src/device.rs@@ -13,4 +13,10 @@ use utoipa::ToSchema;pub enum DeviceType {Ios,Android,+ /// iOS VoIP device (PushKit / CallKit). Registered and delivered via the+ /// APNS_VOIP SNS platform application — separate from the regular APNS one.+ #[serde(rename = "iosvoip")]+ #[sqlx(rename = "iosvoip")]+ #[strum(serialize = "iosvoip")]+ IosVoip,}diff --git a/rust/cloud-storage/notification/src/domain/models/apple.rs b/rust/cloud-storage/notification/src/domain/models/apple.rsindex 7c3584cccb..937809f8bf 100644--- a/rust/cloud-storage/notification/src/domain/models/apple.rs+++ b/rust/cloud-storage/notification/src/domain/models/apple.rs@@ -156,6 +156,23 @@ pub struct APNSPushNotification<T> {pub push_notification_data: T,}+/// Payload for a VoIP push notification (PushKit / CallKit).+///+/// VoIP pushes must NOT contain an `aps` key — the entire payload is custom data+/// delivered verbatim to `pushRegistry(_:didReceiveIncomingPushWith:)`.+#[derive(Serialize, Deserialize, Debug, Clone)]+#[serde(rename_all = "camelCase")]+pub struct VoipPushPayload {+ /// UUID string that identifies the call (used as the CallKit call UUID).+ pub call_id: String,+ /// Channel ID that the call belongs to.+ pub channel_id: String,+ /// Human-readable channel name displayed in the CallKit sheet.+ pub channel_name: String,+ /// Display name of the caller shown in the CallKit incoming-call UI.+ pub caller_name: String,+}+/// the value we send as the payload in the ios notification/// This data is accessible to the client#[derive(Serialize, Deserialize, Debug, Clone)]diff --git a/rust/cloud-storage/notification/src/domain/models/device.rs b/rust/cloud-storage/notification/src/domain/models/device.rsindex 4988d3a980..44661f1adc 100644--- a/rust/cloud-storage/notification/src/domain/models/device.rs+++ b/rust/cloud-storage/notification/src/domain/models/device.rs@@ -18,6 +18,11 @@ pub enum DeviceType {Ios,/// Android (FCM).Android,+ /// iOS VoIP (PushKit / CallKit). Uses the APNS_VOIP SNS platform application.+ #[serde(rename = "iosvoip")]+ #[sqlx(rename = "iosvoip")]+ #[strum(serialize = "iosvoip")]+ IosVoip,}/// Request to register or unregister a device for push notifications.diff --git a/rust/cloud-storage/notification/src/domain/models/mobile.rs b/rust/cloud-storage/notification/src/domain/models/mobile.rsindex 0ff43ed081..a0e69de3e4 100644--- a/rust/cloud-storage/notification/src/domain/models/mobile.rs+++ b/rust/cloud-storage/notification/src/domain/models/mobile.rs@@ -5,7 +5,7 @@ use sha2::{Digest, Sha256};use crate::domain::models::{android::FCMMessage,- apple::{APNSPushNotification, Alert},+ apple::{APNSPushNotification, Alert, VoipPushPayload},};/// SNS target platform for push notifications.@@ -13,6 +13,8 @@ use crate::domain::models::{pub enum SnsTarget<'a, T> {/// iOS target via APNS.Ios(&'a APNSPushNotification<T>),+ /// iOS VoIP target via APNS_VOIP.+ Voip(&'a VoipPushPayload),/// Android target via FCM.Android(&'a FCMMessage<T>),}@@ -32,6 +34,17 @@ pub(crate) enum SnsPayload<'a, T> {#[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]apns_sandbox: &'a APNSPushNotification<T>,},+ /// iOS VoIP payload with APNS_VOIP and APNS_VOIP_SANDBOX keys.+ Voip {+ /// Default message text.+ default: String,+ /// Production APNS VoIP payload.+ #[serde(rename = "APNS_VOIP", serialize_with = "stringified_json")]+ apns_voip: &'a VoipPushPayload,+ /// Sandbox APNS VoIP payload.+ #[serde(rename = "APNS_VOIP_SANDBOX", serialize_with = "stringified_json")]+ apns_voip_sandbox: &'a VoipPushPayload,+ },/// Android payload with GCM key.Android {/// Default message text.@@ -72,6 +85,7 @@ impl<T> SnsTarget<'_, T> {Alert::Dictionary(alert_dictionary) => alert_dictionary.title.clone(),}).unwrap_or(String::new()),+ SnsTarget::Voip(payload) => format!("Incoming call in {}", payload.channel_name),SnsTarget::Android(fcmmessage) => fcmmessage.android.notification.clone(),}}@@ -83,6 +97,11 @@ impl<T> SnsTarget<'_, T> {apns: apnspush_notification,apns_sandbox: apnspush_notification,},+ SnsTarget::Voip(payload) => SnsPayload::Voip {+ default: self.default_string(),+ apns_voip: payload,+ apns_voip_sandbox: payload,+ },SnsTarget::Android(fcmmessage) => SnsPayload::Android {default: self.default_string(),gcm: fcmmessage,@@ -172,4 +191,6 @@ pub enum DeviceEndpoint {Android(String),/// iOS device endpoint (APNS).Ios(String),+ /// iOS VoIP device endpoint (APNS_VOIP / PushKit).+ IosVoip(String),}diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex e703e92863..777804d10d 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -22,8 +22,10 @@ use crate::domain::models::email_notification_digest::ports::{ClaimResult, Digesuse crate::domain::models::request::NotificationListFilters;use crate::domain::models::{DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,- SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,- apple::APNSPushNotification, mobile::MessageAttributes,+ SendNotificationRequestBuilder, UserNotificationRow,+ android::FCMMessage,+ apple::{APNSPushNotification, VoipPushPayload},+ mobile::MessageAttributes,};/// Port for sending mobile push notifications (iOS/Android via SNS).@@ -375,3 +377,44 @@ pub trait NotificationIngressQueue: Send + Sync + 'static {receipt_handle: &str,) -> impl Future<Output = Result<(), Report>> + Send;}++/// Port for sending VoIP push notifications (PushKit / CallKit) to iOS devices.+///+/// VoIP pushes bypass the regular notification pipeline — they are delivered+/// immediately without DB persistence and wake the app via PushKit so that+/// CallKit can display the native incoming-call UI.+pub trait VoipPushSender: Send + Sync + 'static {+ /// Send a VoIP push to all registered VoIP device endpoints of the given users.+ ///+ /// Errors are logged but do not propagate. The returned set contains users+ /// that received at least one successful VoIP push delivery.+ fn send_voip_push(+ &self,+ recipient_ids: &[MacroUserIdStr<'_>],+ payload: &VoipPushPayload,+ ) -> impl std::future::Future<Output = HashSet<MacroUserIdStr<'static>>> + Send;+}++impl VoipPushSender for () {+ async fn send_voip_push(+ &self,+ _: &[MacroUserIdStr<'_>],+ _: &VoipPushPayload,+ ) -> HashSet<MacroUserIdStr<'static>> {+ HashSet::new()+ }+}++impl<V: VoipPushSender> VoipPushSender for Option<V> {+ async fn send_voip_push(+ &self,+ recipient_ids: &[MacroUserIdStr<'_>],+ payload: &VoipPushPayload,+ ) -> HashSet<MacroUserIdStr<'static>> {+ if let Some(inner) = self {+ inner.send_voip_push(recipient_ids, payload).await+ } else {+ HashSet::new()+ }+ }+}diff --git a/rust/cloud-storage/notification/src/domain/service.rs b/rust/cloud-storage/notification/src/domain/service.rsindex f0c6a9cdf1..14924f9420 100644--- a/rust/cloud-storage/notification/src/domain/service.rs+++ b/rust/cloud-storage/notification/src/domain/service.rs@@ -10,6 +10,7 @@ mod ingress;mod push_notification_event;#[cfg(test)]mod test;+mod voip;use thiserror::Error;@@ -22,6 +23,7 @@ pub use ingress::PlatformArnConfig;pub use ingress::SqsNotificationIngress;pub use push_notification_event::PushNotificationEventHandler;pub use push_notification_event::PushNotificationEventService;+pub use voip::VoipPushServiceImpl;/// Error returned when sending a notification fails.#[derive(Debug, Error)]diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rsindex 9bf56c8596..fa9c9b8bb1 100644--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs@@ -332,6 +332,7 @@ fn test_config() -> PlatformArnConfig {PlatformArnConfig {apns_platform_arn: "arn:apns".to_string(),fcm_platform_arn: "arn:fcm".to_string(),+ apns_voip_platform_arn: "arn:apns-voip".to_string(),}}diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rsindex 7ce393d66d..d44f56c2ee 100644--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs@@ -333,7 +333,7 @@ where.into_iter().filter_map(|e| match e {DeviceEndpoint::Ios(arn) => Some(arn),- DeviceEndpoint::Android(_) => None,+ DeviceEndpoint::Android(_) | DeviceEndpoint::IosVoip(_) => None,}).collect();if ios.is_empty() {@@ -434,6 +434,8 @@ pub struct PlatformArnConfig {pub apns_platform_arn: String,/// SNS platform ARN for Android (FCM).pub fcm_platform_arn: String,+ /// SNS platform ARN for iOS VoIP (APNS_VOIP).+ pub apns_voip_platform_arn: String,}/// Service for reading and updating notifications.@@ -519,7 +521,7 @@ where.into_iter().filter_map(|e| match e {DeviceEndpoint::Ios(arn) => Some(arn),- DeviceEndpoint::Android(_) => None,+ DeviceEndpoint::Android(_) | DeviceEndpoint::IosVoip(_) => None,}).collect();if ios.is_empty() {@@ -683,9 +685,10 @@ wheredevice_token: &str,device_type: &DeviceType,) -> Result<(), Report> {- let platform_arn = match device_type {- DeviceType::Ios => &self.platform_config.apns_platform_arn,- DeviceType::Android => &self.platform_config.fcm_platform_arn,+ let platform_arn: &str = match device_type {+ DeviceType::Ios => self.platform_config.apns_platform_arn.as_str(),+ DeviceType::Android => self.platform_config.fcm_platform_arn.as_str(),+ DeviceType::IosVoip => self.platform_config.apns_voip_platform_arn.as_str(),};// Get endpoint if exists, otherwise create new onediff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 9d5a4fea65..63855d5d6e 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -698,6 +698,7 @@ fn test_platform_config() -> PlatformArnConfig {PlatformArnConfig {apns_platform_arn: "arn:aws:sns:us-east-1:000:app/APNS/test".to_string(),fcm_platform_arn: "arn:aws:sns:us-east-1:000:app/GCM/test".to_string(),+ apns_voip_platform_arn: "arn:aws:sns:us-east-1:000:app/APNS_VOIP/test".to_string(),}}diff --git a/rust/cloud-storage/notification/src/domain/service/voip.rs b/rust/cloud-storage/notification/src/domain/service/voip.rsnew file mode 100644index 0000000000..27a25926d3--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/voip.rs@@ -0,0 +1,76 @@+//! VoIP push notification service.+//!+//! Sends PushKit VoIP pushes directly (no queue, no DB persistence) so that+//! CallKit can display the native incoming-call UI on iOS.++#[cfg(test)]+mod test;++use std::collections::HashSet;++use macro_user_id::user_id::MacroUserIdStr;++use crate::domain::models::apple::VoipPushPayload;+use crate::domain::models::mobile::DeviceEndpoint;+use crate::domain::ports::{NotificationRepository, VoipPushSender};+use crate::outbound::mobile::MobilePushAdapter;+use crate::outbound::mobile::MobilePushOps;++/// Concrete implementation of [`VoipPushSender`].+///+/// Looks up VoIP device endpoints from the repository, then dispatches each+/// push directly via SNS APNS_VOIP — no queue, no persistence.+pub struct VoipPushServiceImpl<R, P> {+ repository: R,+ mobile: MobilePushAdapter<P>,+}++impl<R, P> VoipPushServiceImpl<R, P> {+ /// Create a new [`VoipPushServiceImpl`].+ pub fn new(repository: R, mobile: MobilePushAdapter<P>) -> Self {+ Self { repository, mobile }+ }+}++impl<R, P> VoipPushSender for VoipPushServiceImpl<R, P>+where+ R: NotificationRepository,+ P: MobilePushOps + Send + Sync + 'static,+{+ async fn send_voip_push(+ &self,+ recipient_ids: &[MacroUserIdStr<'_>],+ payload: &VoipPushPayload,+ ) -> HashSet<MacroUserIdStr<'static>> {+ let device_map = match self.repository.get_device_endpoints(recipient_ids).await {+ Ok(m) => m,+ Err(e) => {+ tracing::error!(error=?e, "voip push: failed to fetch device endpoints");+ return HashSet::new();+ }+ };++ let mut delivered_user_ids = HashSet::new();+ for (user_id, endpoints) in &device_map {+ for endpoint in endpoints {+ let DeviceEndpoint::IosVoip(arn) = endpoint else {+ continue;+ };+ match self.mobile.send_voip_push(arn, payload).await {+ Ok(_) => {+ delivered_user_ids.insert(user_id.clone());+ }+ Err(e) => {+ tracing::error!(+ error=?e,+ user_id=%user_id,+ "voip push: SNS delivery failed"+ );+ }+ }+ }+ }++ delivered_user_ids+ }+}diff --git a/rust/cloud-storage/notification/src/domain/service/voip/test.rs b/rust/cloud-storage/notification/src/domain/service/voip/test.rsnew file mode 100644index 0000000000..30104ffd03--- /dev/null+++ b/rust/cloud-storage/notification/src/domain/service/voip/test.rs@@ -0,0 +1,357 @@+use std::collections::HashMap;+use std::sync::{Arc, Mutex};++use aws_sdk_sns::types::MessageAttributeValue;+use macro_user_id::user_id::MacroUserIdStr;+use rootcause::Report;+use serde::Serialize;++use crate::domain::models::apple::VoipPushPayload;+use crate::domain::models::mobile::{DeviceEndpoint, SnsTarget};+use crate::domain::ports::{NotificationRepository, VoipPushSender};+use crate::outbound::mobile::{MobilePushAdapter, MobilePushOps};++use super::VoipPushServiceImpl;++// ─── Helpers ─────────────────────────────────────────────────────────────────++fn user(email: &'static str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email(email).unwrap()+}++fn payload() -> VoipPushPayload {+ VoipPushPayload {+ call_id: "11111111-1111-1111-1111-111111111111".to_string(),+ channel_id: "ch-1".to_string(),+ channel_name: "general".to_string(),+ caller_name: "Alice".to_string(),+ }+}++// ─── Mock: NotificationRepository ────────────────────────────────────────────++struct MockRepo {+ endpoints: Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, &'static str>,+}++impl MockRepo {+ fn with_endpoints(map: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>) -> Self {+ Self { endpoints: Ok(map) }+ }++ fn failing() -> Self {+ Self {+ endpoints: Err("db error"),+ }+ }+}++impl NotificationRepository for MockRepo {+ async fn get_device_endpoints<'a>(+ &self,+ _: &[MacroUserIdStr<'a>],+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {+ self.endpoints+ .clone()+ .map_err(|e| rootcause::report!("{e}"))+ }++ async fn get_device_endpoint(&self, _: &str) -> Result<Option<String>, Report> {+ unimplemented!()+ }+ async fn upsert_device(+ &self,+ _: MacroUserIdStr<'_>,+ _: &str,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn delete_device_by_token(+ &self,+ _: &str,+ _: &crate::domain::models::device::DeviceType,+ ) -> Result<String, Report> {+ unimplemented!()+ }+ async fn delete_device_by_endpoint(&self, _: &str) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_muted_users<'a>(+ &self,+ _: &[MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<MacroUserIdStr<'static>>, Report> {+ unimplemented!()+ }+ async fn get_unsubscribed_users<'a>(+ &self,+ _: &str,+ _: &[MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<MacroUserIdStr<'static>>, Report> {+ unimplemented!()+ }+ async fn create_notification<'a, T: Serialize + Send + Sync>(+ &self,+ _: crate::domain::models::SendNotificationRequestBuilder<+ 'a,+ crate::domain::models::TaggedContent<T>,+ >,+ _: uuid::Uuid,+ _: &str,+ _: Option<&str>,+ ) -> Result<Option<Vec<crate::domain::models::UserNotificationRow<std::sync::Arc<T>>>>, Report>+ {+ unimplemented!()+ }+ async fn update_sent_status<'a>(+ &self,+ _: uuid::Uuid,+ _: &[MacroUserIdStr<'a>],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn mark_notifications_seen(+ &self,+ _: MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn mark_notifications_done(+ &self,+ _: &MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: bool,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_basic_notifications(+ &self,+ _: &[uuid::Uuid],+ ) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: MacroUserIdStr<'_>,+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notifications_by_event_item_ids<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ _: u32,+ _: models_pagination::Query<uuid::Uuid, models_pagination::CreatedAt, ()>,+ _: crate::domain::models::request::NotificationListFilters,+ ) -> Result<Vec<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn get_user_notification_by_id<T: serde::de::DeserializeOwned + Send>(+ &self,+ _: MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<Option<crate::domain::models::UserNotificationRow<T>>, Report> {+ unimplemented!()+ }+ async fn delete_user_notification(+ &self,+ _: MacroUserIdStr<'_>,+ _: uuid::Uuid,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn bulk_delete_user_notifications(+ &self,+ _: MacroUserIdStr<'_>,+ _: &[uuid::Uuid],+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn delete_all_user_notifications(&self, _: MacroUserIdStr<'_>) -> Result<(), Report> {+ unimplemented!()+ }+ async fn get_users_with_type_disabled<'a>(+ &self,+ _: &str,+ _: &[MacroUserIdStr<'a>],+ ) -> Result<std::collections::HashSet<MacroUserIdStr<'static>>, Report> {+ unimplemented!()+ }+ async fn get_disabled_notification_types(+ &self,+ _: MacroUserIdStr<'_>,+ ) -> Result<Vec<crate::domain::models::DisabledNotificationType>, Report> {+ unimplemented!()+ }+ async fn disable_notification_type(+ &self,+ _: MacroUserIdStr<'_>,+ _: &str,+ ) -> Result<(), Report> {+ unimplemented!()+ }+ async fn enable_notification_type(&self, _: MacroUserIdStr<'_>, _: &str) -> Result<(), Report> {+ unimplemented!()+ }+}++// ─── Mock: MobilePushOps ──────────────────────────────────────────────────────++struct MockPush {+ calls: Arc<Mutex<Vec<String>>>,+ should_fail: bool,+}++impl MockPush {+ fn new(calls: Arc<Mutex<Vec<String>>>) -> Self {+ Self {+ calls,+ should_fail: false,+ }+ }++ fn failing() -> Self {+ Self {+ calls: Arc::new(Mutex::new(Vec::new())),+ should_fail: true,+ }+ }+}++impl MobilePushOps for MockPush {+ async fn push_notification<T: Serialize + Send + Sync>(+ &self,+ endpoint_arn: &str,+ _: &SnsTarget<'_, T>,+ _: HashMap<String, MessageAttributeValue>,+ ) -> Result<String, Report> {+ if self.should_fail {+ return Err(rootcause::report!("SNS error"));+ }+ self.calls.lock().unwrap().push(endpoint_arn.to_string());+ Ok("msg-id".to_string())+ }+}++fn make_service(repo: MockRepo, push: MockPush) -> VoipPushServiceImpl<MockRepo, MockPush> {+ let adapter = MobilePushAdapter {+ push_service: push,+ apns_bundle_id: "com.example.app".to_string(),+ voip_bundle_id: Some("com.example.app.voip".to_string()),+ };+ VoipPushServiceImpl::new(repo, adapter)+}++fn tracked_push() -> (MockPush, Arc<Mutex<Vec<String>>>) {+ let calls = Arc::new(Mutex::new(Vec::new()));+ (MockPush::new(Arc::clone(&calls)), calls)+}++// ─── Tests ────────────────────────────────────────────────────────────────────++#[tokio::test]+async fn dispatches_to_ios_voip_endpoint() {+ let (push, calls) = tracked_push();+ let svc = make_service(+ MockRepo::with_endpoints(HashMap::from([(+ user("[email protected]"),+ vec![DeviceEndpoint::IosVoip("arn:voip-alice".to_string())],+ )])),+ push,+ );++ let result = svc+ .send_voip_push(&[user("[email protected]")], &payload())+ .await;++ assert_eq!(*calls.lock().unwrap(), vec!["arn:voip-alice"]);+ assert!(result.contains(&user("[email protected]")));+}++#[tokio::test]+async fn skips_non_voip_endpoints() {+ let (push, calls) = tracked_push();+ let svc = make_service(+ MockRepo::with_endpoints(HashMap::from([(+ user("[email protected]"),+ vec![+ DeviceEndpoint::Ios("arn:apns-bob".to_string()),+ DeviceEndpoint::Android("arn:fcm-bob".to_string()),+ ],+ )])),+ push,+ );++ let result = svc+ .send_voip_push(&[user("[email protected]")], &payload())+ .await;++ assert!(calls.lock().unwrap().is_empty());+ assert!(result.is_empty());+}++#[tokio::test]+async fn sends_to_multiple_recipients() {+ let (push, calls) = tracked_push();+ let svc = make_service(+ MockRepo::with_endpoints(HashMap::from([+ (+ user("[email protected]"),+ vec![DeviceEndpoint::IosVoip("arn:voip-alice".to_string())],+ ),+ (+ user("[email protected]"),+ vec![DeviceEndpoint::IosVoip("arn:voip-bob".to_string())],+ ),+ ])),+ push,+ );++ let result = svc+ .send_voip_push(+ &[user("[email protected]"), user("[email protected]")],+ &payload(),+ )+ .await;++ let mut recorded = calls.lock().unwrap().clone();+ recorded.sort();+ assert_eq!(recorded, vec!["arn:voip-alice", "arn:voip-bob"]);+ assert!(result.contains(&user("[email protected]")));+ assert!(result.contains(&user("[email protected]")));+}++#[tokio::test]+async fn repo_error_does_not_panic() {+ let (push, calls) = tracked_push();+ let svc = make_service(MockRepo::failing(), push);++ let result = svc+ .send_voip_push(&[user("[email protected]")], &payload())+ .await;++ assert!(calls.lock().unwrap().is_empty());+ assert!(result.is_empty());+}++#[tokio::test]+async fn sns_failure_does_not_panic() {+ let svc = make_service(+ MockRepo::with_endpoints(HashMap::from([(+ user("[email protected]"),+ vec![DeviceEndpoint::IosVoip("arn:voip-alice".to_string())],+ )])),+ MockPush::failing(),+ );++ let result = svc+ .send_voip_push(&[user("[email protected]")], &payload())+ .await;++ assert!(result.is_empty());+}diff --git a/rust/cloud-storage/notification/src/outbound/mobile.rs b/rust/cloud-storage/notification/src/outbound/mobile.rsindex 14911177f7..5c13876d49 100644--- a/rust/cloud-storage/notification/src/outbound/mobile.rs+++ b/rust/cloud-storage/notification/src/outbound/mobile.rs@@ -6,7 +6,7 @@ use serde::Serialize;use std::collections::HashMap;use crate::domain::models::android::FCMMessage;-use crate::domain::models::apple::APNSPushNotification;+use crate::domain::models::apple::{APNSPushNotification, VoipPushPayload};use crate::domain::models::mobile::{MessageAttributes, PushType, SnsTarget};use crate::domain::ports::NotificationSender;@@ -15,25 +15,19 @@ use crate::domain::ports::NotificationSender;/// This adapter sends push notifications to mobile devices via APNS (iOS)/// and FCM (Android) through SNS.pub struct MobilePushAdapter<P> {- push_service: P,- apns_bundle_id: String,-}--impl<P> MobilePushAdapter<P> {- /// Create a new mobile push adapter.- pub fn new(push_service: P, apns_bundle_id: String) -> Self {- Self {- push_service,- apns_bundle_id,- }- }+ /// Push service implementation used to send SNS messages.+ pub push_service: P,+ /// APNS topic / bundle ID for regular iOS push notifications.+ pub apns_bundle_id: String,+ /// Set to `<bundle_id>.voip` when VoIP push is configured.+ pub voip_bundle_id: Option<String>,}/// Trait for mobile push service operations via SNS.////// This allows the adapter to work with different SNS client implementations.pub trait MobilePushOps {- /// Send a push notification to the specified endpoint ARN.+ /// Send a push notification to the specified endpoint ARN using a typed SNS target.////// Returns the SNS message ID on success.fn push_notification<T: Serialize + Send + Sync>(@@ -52,7 +46,6 @@ impl MobilePushOps for aws_sdk_sns::Client {attributes: HashMap<String, MessageAttributeValue>,) -> Result<String, Report> {let payload = message.as_json()?;-let output = self.publish().target_arn(endpoint_arn)@@ -100,7 +93,31 @@ impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePush}}-/// Build SNS message attributes from our domain attributes.+impl<P: MobilePushOps + Send + Sync + 'static> MobilePushAdapter<P> {+ /// Send a VoIP push notification via APNS_VOIP.+ ///+ /// Bypasses the normal notification pipeline — sent immediately without+ /// DB persistence. Wakes the app via PushKit so CallKit can report an+ /// incoming call.+ #[tracing::instrument(err, skip(self, payload))]+ pub async fn send_voip_push(+ &self,+ endpoint_arn: &str,+ payload: &VoipPushPayload,+ ) -> Result<String, Report> {+ let voip_bundle_id = self.voip_bundle_id.as_deref().ok_or_else(|| {+ rootcause::report!("voip_bundle_id not configured on MobilePushAdapter")+ })?;++ let target: SnsTarget<'_, ()> = SnsTarget::Voip(payload);+ let attrs = build_voip_sns_attributes(voip_bundle_id);+ self.push_service+ .push_notification(endpoint_arn, &target, attrs)+ .await+ }+}++/// Build SNS message attributes for a regular APNS notification.fn build_sns_attributes(apns_bundle_id: &str,attributes: &MessageAttributes,@@ -145,3 +162,41 @@ fn build_sns_attributes(),])}++/// Build SNS message attributes for a VoIP (APNS_VOIP) notification.+fn build_voip_sns_attributes(voip_bundle_id: &str) -> HashMap<String, MessageAttributeValue> {+ HashMap::from([+ (+ "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),+ MessageAttributeValue::builder()+ .data_type("String")+ .string_value(voip_bundle_id)+ .build()+ .expect("valid attribute"),+ ),+ (+ "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),+ MessageAttributeValue::builder()+ .data_type("String")+ .string_value("voip")+ .build()+ .expect("valid attribute"),+ ),+ (+ "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),+ MessageAttributeValue::builder()+ .data_type("String")+ .string_value("10")+ .build()+ .expect("valid attribute"),+ ),+ (+ "AWS.SNS.MOBILE.APNS.TTL".to_string(),+ MessageAttributeValue::builder()+ .data_type("String")+ .string_value("0")+ .build()+ .expect("valid attribute"),+ ),+ ])+}diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rsindex 44493bb012..5ac53a01c3 100644--- a/rust/cloud-storage/notification/src/outbound/repository.rs+++ b/rust/cloud-storage/notification/src/outbound/repository.rs@@ -246,6 +246,8 @@ fn push_cursor_filter(enum DbDeviceType {Ios,Android,+ #[sqlx(rename = "iosvoip")]+ IosVoip,}/// Database-backed implementation of the notification repository port.@@ -491,6 +493,7 @@ impl NotificationDbOps for PgPool {let device = match row.device_type {DbDeviceType::Ios => DeviceEndpoint::Ios(row.device_endpoint),DbDeviceType::Android => DeviceEndpoint::Android(row.device_endpoint),+ DbDeviceType::IosVoip => DeviceEndpoint::IosVoip(row.device_endpoint),};resultdiff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rsindex e5b53f3e54..a41de79cf7 100644--- a/rust/cloud-storage/notification_sandbox/src/main.rs+++ b/rust/cloud-storage/notification_sandbox/src/main.rs@@ -138,10 +138,11 @@ async fn main() -> Result<(), Report> {SnsMode::Real {sns_client,endpoint_arn: _,- } => SandboxMobileSender::Real(MobilePushAdapter::new(- sns_client.clone(),- "com.macro.app.prod".to_string(),- )),+ } => SandboxMobileSender::Real(MobilePushAdapter {+ push_service: sns_client.clone(),+ apns_bundle_id: "com.macro.app.prod".to_string(),+ voip_bundle_id: None,+ }),};let email_adapter = EmailAdapter::new(aws_sdk_sesv2::Client::new(&aws_config),diff --git a/rust/cloud-storage/notification_service/src/config.rs b/rust/cloud-storage/notification_service/src/config.rsindex 233c355504..e695e28d8f 100644--- a/rust/cloud-storage/notification_service/src/config.rs+++ b/rust/cloud-storage/notification_service/src/config.rs@@ -49,6 +49,9 @@ pub struct Config {/// The sns android platform arnpub sns_fcm_platform_arn: String,+ /// The sns ios VoIP platform arn (APNS_VOIP).+ pub sns_apns_voip_platform_arn: String,+/// The sender base address// Explicitly allowed as it's used to ensure we have a correct sender base address in the lazy env var abovepub sender_base_address: String,@@ -91,6 +94,9 @@ impl Config {let sns_fcm_platform_arn = std::env::var("SNS_FCM_PLATFORM_ARN").context("SNS_FCM_PLATFORM_ARN must be provided")?;+ let sns_apns_voip_platform_arn = std::env::var("SNS_APNS_VOIP_PLATFORM_ARN")+ .context("SNS_APNS_VOIP_PLATFORM_ARN must be provided")?;+let sender_base_address =std::env::var("SENDER_BASE_ADDRESS").context("SENDER_BASE_ADDRESS must be provided")?;@@ -113,6 +119,7 @@ impl Config {notification_queue_wait_time_seconds,sns_apns_platform_arn,sns_fcm_platform_arn,+ sns_apns_voip_platform_arn,sender_base_address,push_notification_event_handler_queue,})diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rsindex 13f4676ac0..e8a001711f 100644--- a/rust/cloud-storage/notification_service/src/main.rs+++ b/rust/cloud-storage/notification_service/src/main.rs@@ -146,6 +146,7 @@ pub async fn main() -> anyhow::Result<()> {let platform_config = ::notification::domain::service::PlatformArnConfig {apns_platform_arn: config.sns_apns_platform_arn.clone(),fcm_platform_arn: config.sns_fcm_platform_arn.clone(),+ apns_voip_platform_arn: config.sns_apns_voip_platform_arn.clone(),};let reader_service = ::notification::domain::service::NotificationReaderService::new(notification_repository,@@ -169,10 +170,11 @@ pub async fn main() -> anyhow::Result<()> {vars.connection_gateway_url.as_ref().to_string(),));- let mobile_adapter = MobilePushAdapter::new(- aws_sdk_sns::Client::new(&aws_config),- vars.apple_bundle_id.as_ref().to_string(),- );+ let mobile_adapter = MobilePushAdapter {+ push_service: aws_sdk_sns::Client::new(&aws_config),+ apns_bundle_id: vars.apple_bundle_id.as_ref().to_string(),+ voip_bundle_id: None,+ };let ses_client = aws_sdk_sesv2::Client::new(&aws_config);let email_adapter = EmailAdapter::new(ses_client, crate::env::SENDER_ADDRESS.clone());