Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(android): native calls (#7294)

Peter Chinman0280dc60b526
diff --git a/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json b/.sqlx/query-286fee2c4c050737310cc3a1296c3ce4d2781f988817fd08ceda4e997813b33e.json
similarity index 62%
rename from .sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json
rename to .sqlx/query-286fee2c4c050737310cc3a1296c3ce4d2781f988817fd08ceda4e997813b33e.json
index 2ae6f0e18e..7f36990536 100644
--- a/.sqlx/query-b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb.json
+++ b/.sqlx/query-286fee2c4c050737310cc3a1296c3ce4d2781f988817fd08ceda4e997813b33e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, updated_at = NOW()\n ",
+ "query": "\n INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type, native_call_capable)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, native_call_capable = $6, updated_at = NOW()\n ",
"describe": {
"columns": [],
"parameters": {
@@ -20,10 +20,11 @@
]
}
}
- }
+ },
+ "Bool"
]
},
"nullable": []
},
- "hash": "b3f9f3696438bd2ad8754650d87d7bbf32e70d3d173a748a07eacdb4e42841eb"
+ "hash": "286fee2c4c050737310cc3a1296c3ce4d2781f988817fd08ceda4e997813b33e"
}
diff --git a/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json b/.sqlx/query-8e30d17f3c84875f7c5f6fe08845f19889ba3415327c925e10791be21180659d.json
similarity index 69%
rename from .sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json
rename to .sqlx/query-8e30d17f3c84875f7c5f6fe08845f19889ba3415327c925e10791be21180659d.json
index dead84e7bf..4f491b2552 100644
--- a/.sqlx/query-a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1.json
+++ b/.sqlx/query-8e30d17f3c84875f7c5f6fe08845f19889ba3415327c925e10791be21180659d.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT user_id, device_endpoint, device_type as \"device_type: DbDeviceType\"\n FROM notification_user_device_registration\n WHERE user_id = ANY($1)\n ",
+ "query": "\n SELECT user_id, device_endpoint, device_type as \"device_type: DbDeviceType\", native_call_capable\n FROM notification_user_device_registration\n WHERE user_id = ANY($1)\n ",
"describe": {
"columns": [
{
@@ -28,6 +28,11 @@
}
}
}
+ },
+ {
+ "ordinal": 3,
+ "name": "native_call_capable",
+ "type_info": "Bool"
}
],
"parameters": {
@@ -36,10 +41,11 @@
]
},
"nullable": [
+ false,
false,
false,
false
]
},
- "hash": "a0046a263c572915a8e14a8ac70479f1ba89549f1930f571bf278fcfe259cfd1"
+ "hash": "8e30d17f3c84875f7c5f6fe08845f19889ba3415327c925e10791be21180659d"
}
diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsx
index 7b553d414d..19bebc3806 100644
--- a/apps/web/src/features/channel/Call/CallContext.tsx
+++ b/apps/web/src/features/channel/Call/CallContext.tsx
@@ -57,7 +57,8 @@ import {
useMaybeNativeCallState,
} from './native-call-state';
import {
- isNativeIosCallKitEnabled,
+ isNativeCallEnabled,
+ prepareNativeCallJoin,
registerCallKitCallEndedHandler,
} from './use-callkit';
@@ -1576,6 +1577,7 @@ function createCallState() {
const lifecycle = createCallLifecycle({
shouldRequestToken: callSession.shouldRequestToken,
+ prepareToken: prepareNativeCallJoin,
requestToken: requestCallToken,
connect: (token) =>
callSession.connectWithToken(token, {
@@ -1649,7 +1651,7 @@ function createCallState() {
});
const unsubscribeNative =
- isNativeIosCallKitEnabled() && nativeCall
+ isNativeCallEnabled() && nativeCall
? bindNativeCallLifecycle(nativeCall, lifecycle)
: undefined;
diff --git a/apps/web/src/features/channel/Call/CallControls/CallControls.tsx b/apps/web/src/features/channel/Call/CallControls/CallControls.tsx
index 4ec5528874..829427f038 100644
--- a/apps/web/src/features/channel/Call/CallControls/CallControls.tsx
+++ b/apps/web/src/features/channel/Call/CallControls/CallControls.tsx
@@ -1,5 +1,7 @@
+import { isPlatform } from '@core/util/platform';
import { type Accessor, Show } from 'solid-js';
import { useMaybeNativeCallState } from '../native-call-state';
+import { setNativeCallKitVideoOverlayMode } from '../use-callkit';
import { CallControlsDefaultAndPanelRow } from './CallControlsDefaultAndPanelRow';
export type CallControlsProps = {
@@ -18,8 +20,23 @@ export function CallControls(props: CallControlsProps) {
const nativeCall = useMaybeNativeCallState();
return (
- <Show when={readWhen(props.when) && !nativeCall?.snapshot()}>
- <CallControlsDefaultAndPanelRow onLeave={props.onLeave} />
+ <Show when={readWhen(props.when)}>
+ <Show when={isPlatform('android') && nativeCall?.snapshot()}>
+ <div class="flex gap-2">
+ <button
+ type="button"
+ onClick={() => void setNativeCallKitVideoOverlayMode('expanded')}
+ >
+ Open call controls
+ </button>
+ <button type="button" onClick={() => void props.onLeave()}>
+ End call
+ </button>
+ </div>
+ </Show>
+ <Show when={!nativeCall?.snapshot()}>
+ <CallControlsDefaultAndPanelRow onLeave={props.onLeave} />
+ </Show>
</Show>
);
}
diff --git a/apps/web/src/features/channel/Call/CallSessionController.ts b/apps/web/src/features/channel/Call/CallSessionController.ts
index 68341d6a32..7a4c82d771 100644
--- a/apps/web/src/features/channel/Call/CallSessionController.ts
+++ b/apps/web/src/features/channel/Call/CallSessionController.ts
@@ -3,7 +3,7 @@ import type { CallTokenResponse } from '@service-call/client';
import type { NativeCallState } from './native-call-state';
import {
endCallKitCall,
- isNativeIosCallKitEnabled,
+ isNativeCallEnabled,
startNativeCallKitOutgoingCall,
syncNativeCallStateAfterLeave,
} from './use-callkit';
@@ -60,7 +60,7 @@ export function createCallSessionController(
options: CallSessionControllerOptions
): CallSessionController {
const browser = createJsLivekitSessionController(options);
- if (isNativeIosCallKitEnabled()) {
+ if (isNativeCallEnabled()) {
if (!options.nativeCall) {
throw new Error(
'Native call state is required for iOS CallKit call sessions'
diff --git a/apps/web/src/features/channel/Call/call-lifecycle.ts b/apps/web/src/features/channel/Call/call-lifecycle.ts
index f094299e0f..770cc727f4 100644
--- a/apps/web/src/features/channel/Call/call-lifecycle.ts
+++ b/apps/web/src/features/channel/Call/call-lifecycle.ts
@@ -163,6 +163,7 @@ function shouldRejoin(reason?: DisconnectReason) {
/** One coordinator per call provider; views only submit intent and observe it. */
export function createCallLifecycle(options: {
shouldRequestToken: (channelId: string) => boolean;
+ prepareToken?: (channelId: string) => Promise<() => Promise<void>>;
requestToken: (channelId: string) => Promise<CallTokenResponse>;
connect: (token: CallTokenResponse) => Promise<void>;
disconnect: (options?: CallSessionDisconnectOptions) => Promise<void>;
@@ -213,13 +214,19 @@ export function createCallLifecycle(options: {
joining: ({ request }, dispatch) => {
let active = true;
let settled = false;
+ let finishPreparation: (() => Promise<void>) | undefined;
+ const releasePreparation = () => {
+ const cleanup = finishPreparation;
+ finishPreparation = undefined;
+ if (cleanup) void cleanup().catch(options.reportError);
+ };
const fail = (error: unknown) => {
if (!active) return;
settled = true;
request.reject(error);
dispatch({ t: 'fail', error });
};
- const timeout = setTimeout(
+ let timeout = setTimeout(
() => fail(new Error('Connection timed out')),
JOIN_TIMEOUT_MS
);
@@ -264,6 +271,20 @@ export function createCallLifecycle(options: {
request.channelId
);
if (needsConnection || renewMembership) {
+ if (options.prepareToken) {
+ // Permission prompts precede the lease and connection deadline.
+ clearTimeout(timeout);
+ const cleanup = await options.prepareToken(request.channelId);
+ if (!active) {
+ await cleanup();
+ return;
+ }
+ finishPreparation = cleanup;
+ timeout = setTimeout(
+ () => fail(new Error('Connection timed out')),
+ JOIN_TIMEOUT_MS
+ );
+ }
const [token] = await Promise.all([
options.requestToken(request.channelId),
delay,
@@ -313,11 +334,14 @@ export function createCallLifecycle(options: {
}
} catch (error) {
fail(error);
+ } finally {
+ releasePreparation();
}
}
void connect();
return () => {
active = false;
+ releasePreparation();
clearTimeout(timeout);
clearTimeout(delayTimer);
finishDelay();
diff --git a/apps/web/src/features/channel/Call/call-tabs.ts b/apps/web/src/features/channel/Call/call-tabs.ts
index f698154639..335d8b9508 100644
--- a/apps/web/src/features/channel/Call/call-tabs.ts
+++ b/apps/web/src/features/channel/Call/call-tabs.ts
@@ -2,10 +2,10 @@ import {
type ChannelTabId,
DEFAULT_CHANNEL_TAB,
} from '@channel/Channel/channel-tabs';
-import { isNativeIosCallKitEnabled } from './use-callkit';
+import { isNativeCallEnabled } from './use-callkit';
export function getCallJoinTab(): ChannelTabId {
- return isNativeIosCallKitEnabled() ? DEFAULT_CHANNEL_TAB : 'call';
+ return isNativeCallEnabled() ? DEFAULT_CHANNEL_TAB : 'call';
}
export function getCallLeaveTab(): ChannelTabId {
diff --git a/apps/web/src/features/channel/Call/callkit-drawer-theme.ts b/apps/web/src/features/channel/Call/callkit-drawer-theme.ts
index a72e930cb3..fef1a8d296 100644
--- a/apps/web/src/features/channel/Call/callkit-drawer-theme.ts
+++ b/apps/web/src/features/channel/Call/callkit-drawer-theme.ts
@@ -1,10 +1,10 @@
-import { ENABLE_CALLKIT } from '@core/constant/featureFlags';
-import { isPlatform, isTauri } from '@core/util/platform';
+import { isPlatform } from '@core/util/platform';
import { createLazyMemo } from '@solid-primitives/memo';
import { invoke } from '@tauri-apps/api/core';
import { resolvedThemeColors } from '@theme/signals/themeSignals';
import Color from 'colorjs.io';
import type { Accessor } from 'solid-js';
+import { isNativeCallEnabled } from './native-call-platform';
export type RgbaColor = {
red: number;
@@ -39,19 +39,24 @@ export function createCallKitDrawerTheme(): Accessor<CallKitDrawerTheme> {
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) =>
+ if (!isNativeCallEnabled()) return;
+ await invoke(
+ 'plugin:call-kit|set_call_drawer_theme',
+ isPlatform('android')
+ ? { 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)
);
}
diff --git a/apps/web/src/features/channel/Call/native-call-platform.ts b/apps/web/src/features/channel/Call/native-call-platform.ts
new file mode 100644
index 0000000000..ced300b7ff
--- /dev/null
+++ b/apps/web/src/features/channel/Call/native-call-platform.ts
@@ -0,0 +1,22 @@
+import { ENABLE_CALLKIT } from '@core/constant/featureFlags';
+import { isPlatform, isTauri } from '@core/util/platform';
+import { version } from '@tauri-apps/plugin-os';
+
+declare global {
+ interface Window {
+ /** Advertised by binaries that register the Android call-kit plugin. */
+ __MACRO_ANDROID_CALL_KIT__?: boolean;
+ }
+}
+
+export function isNativeCallEnabled(): boolean {
+ if (!ENABLE_CALLKIT || !isTauri()) return false;
+ if (isPlatform('ios')) return true;
+ // OTA frontend bundles also run in older APKs and on Android 7. Keep those
+ // clients on browser media rather than invoking unavailable Telecom commands.
+ return (
+ isPlatform('android') &&
+ window.__MACRO_ANDROID_CALL_KIT__ === true &&
+ Number.parseInt(version(), 10) >= 8
+ );
+}
diff --git a/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts
index f2eea6203e..455f0eeb9a 100644
--- a/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts
+++ b/apps/web/src/features/channel/Call/tests/call-lifecycle.test.ts
@@ -29,7 +29,7 @@ const token: CallTokenResponse = {
} satisfies CallTokenResponse;
const cleanups: (() => void)[] = [];
-function setup() {
+function setup(extra: Partial<Parameters<typeof createCallLifecycle>[0]> = {}) {
let disconnected: (reason?: DisconnectReason) => void = () => {};
let nativeEnded: () => void = () => {};
const unwatch = vi.fn();
@@ -55,7 +55,7 @@ function setup() {
onLeft: vi.fn(),
reportError: vi.fn(),
} satisfies Parameters<typeof createCallLifecycle>[0];
- const lifecycle = createCallLifecycle(ports);
+ const lifecycle = createCallLifecycle({ ...ports, ...extra });
cleanups.push(lifecycle.dispose);
return {
lifecycle,
@@ -96,6 +96,106 @@ describe('shared call lifecycle', () => {
expect(vi.getTimerCount()).toBe(0);
});
+ it('prepares native ring handoff before requesting membership and releases it after commit', async () => {
+ const preparation = deferred<() => Promise<void>>();
+ const cleanup = vi.fn(async () => {});
+ const prepareToken = vi.fn(() => preparation.promise);
+ const { lifecycle, ports } = setup({ prepareToken });
+ const joined = lifecycle.join(call.channelId);
+ expect(prepareToken).toHaveBeenCalledWith(call.channelId);
+ expect(ports.requestToken).not.toHaveBeenCalled();
+ preparation.resolve(cleanup);
+ await vi.advanceTimersByTimeAsync(300);
+ await joined;
+ expect(ports.requestToken).toHaveBeenCalledOnce();
+ expect(ports.connect).toHaveBeenCalledOnce();
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('releases native handoff immediately when a pending token request is cancelled', async () => {
+ const cleanup = vi.fn(async () => {});
+ const pendingToken = deferred<CallTokenResponse>();
+ const { lifecycle, ports } = setup({ prepareToken: async () => cleanup });
+ ports.requestToken.mockReturnValueOnce(pendingToken.promise);
+ const joined = lifecycle.join(call.channelId);
+ const rejected = expect(joined).rejects.toThrow('cancelled');
+ await vi.advanceTimersByTimeAsync(0);
+ lifecycle.dispose();
+ expect(cleanup).toHaveBeenCalledOnce();
+ pendingToken.resolve(token);
+ await rejected;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ports.connect).not.toHaveBeenCalled();
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('cleans a preparation that resolves after the join was cancelled', async () => {
+ const preparation = deferred<() => Promise<void>>();
+ const cleanup = vi.fn(async () => {});
+ const { lifecycle, ports } = setup({
+ prepareToken: () => preparation.promise,
+ });
+ const rejected = expect(lifecycle.join(call.channelId)).rejects.toThrow(
+ 'cancelled'
+ );
+ lifecycle.dispose();
+ preparation.resolve(cleanup);
+ await rejected;
+ await vi.advanceTimersByTimeAsync(0);
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(ports.requestToken).not.toHaveBeenCalled();
+ });
+
+ it('allows permission preparation to outlast the connection deadline', async () => {
+ const preparation = deferred<() => Promise<void>>();
+ const cleanup = vi.fn(async () => {});
+ const { lifecycle, ports } = setup({
+ prepareToken: () => preparation.promise,
+ });
+ ports.rollbackJoin.mockClear();
+ const joined = lifecycle.join(call.channelId);
+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS + 5_000);
+ expect(ports.rollbackJoin).not.toHaveBeenCalled();
+ expect(ports.requestToken).not.toHaveBeenCalled();
+ preparation.resolve(cleanup);
+ await joined;
+ expect(ports.connect).toHaveBeenCalledOnce();
+ expect(cleanup).toHaveBeenCalledOnce();
+ });
+
+ it('starts the connection deadline after permission preparation', async () => {
+ const preparation = deferred<() => Promise<void>>();
+ const cleanup = vi.fn(async () => {});
+ const { lifecycle, ports } = setup({
+ prepareToken: () => preparation.promise,
+ });
+ ports.requestToken.mockReturnValueOnce(
+ deferred<CallTokenResponse>().promise
+ );
+ const rejected = expect(lifecycle.join(call.channelId)).rejects.toThrow(
+ 'Connection timed out'
+ );
+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS + 5_000);
+ preparation.resolve(cleanup);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ports.requestToken).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(JOIN_TIMEOUT_MS);
+ await rejected;
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(ports.connect).not.toHaveBeenCalled();
+ });
+
+ it('aborts native handoff when requesting membership fails', async () => {
+ const cleanup = vi.fn(async () => {});
+ const { lifecycle, ports } = setup({ prepareToken: async () => cleanup });
+ ports.requestToken.mockRejectedValueOnce(new Error('Backend unavailable'));
+ await expect(lifecycle.join(call.channelId)).rejects.toThrow(
+ 'Backend unavailable'
+ );
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(ports.connect).not.toHaveBeenCalled();
+ });
+
it('publishes an answer only after the connection completes', async () => {
const { lifecycle, ports } = setup();
const connection = deferred<void>();
diff --git a/apps/web/src/features/channel/Call/tests/call-session-controller.test.ts b/apps/web/src/features/channel/Call/tests/call-session-controller.test.ts
index 5146208903..6f2955e06e 100644
--- a/apps/web/src/features/channel/Call/tests/call-session-controller.test.ts
+++ b/apps/web/src/features/channel/Call/tests/call-session-controller.test.ts
@@ -9,7 +9,7 @@ const native = vi.hoisted(() => ({
end: vi.fn(async () => undefined),
}));
vi.mock('../use-callkit', () => ({
- isNativeIosCallKitEnabled: () => native.enabled,
+ isNativeCallEnabled: () => native.enabled,
startNativeCallKitOutgoingCall: native.start,
endCallKitCall: native.end,
syncNativeCallStateAfterLeave: vi.fn(async () => undefined),
diff --git a/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts b/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts
new file mode 100644
index 0000000000..9c6fdca831
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/callkit-answered-recovery.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { useCallKitSetup } from '../use-callkit';
+
+const bridge = vi.hoisted(() => ({
+ watchers: new Map<string, (payload: unknown) => void>(),
+ pending: null as { channelId: string; nativeMedia: boolean } | null,
+ cleanups: [] as (() => void)[],
+ open: vi.fn(async () => {}),
+ join: vi.fn(async () => {}),
+}));
+vi.mock('solid-js', async (original) => ({
+ ...(await original<typeof import('solid-js')>()),
+ onMount: (callback: () => void) => callback(),
+ onCleanup: (callback: () => void) => bridge.cleanups.push(callback),
+}));
+vi.mock('@app/signal/splitLayout', () => ({
+ whenSplitManagerReady: async () => {},
+}));
+vi.mock('@core/auth/push-registration-lifecycle', () => ({
+ registerPushRegistrationLifecycle: () => () => {},
+}));
+vi.mock('@tauri-apps/plugin-os', () => ({ version: () => '16' }));
+vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLKIT: true }));
+vi.mock('@core/context/channels', () => ({ useChannelsContext: vi.fn() }));
+vi.mock('@core/util/platform', () => ({
+ isTauri: () => true,
+ isPlatform: (platform: string) => platform === 'android',
+}));
+vi.mock('@queries/auth', () => ({ useUserNamesQuery: vi.fn() }));
+vi.mock('@queries/call/call', () => ({
+ invalidateActiveCallQueries: async () => {},
+}));
+vi.mock('@service-notification/client', () => ({
+ notificationServiceClient: {},
+}));
+vi.mock('../join-channel-call', () => ({ joinChannelCall: bridge.join }));
+vi.mock('../open-channel-call-tab', () => ({
+ openChannelCallTab: bridge.open,
+}));
+vi.mock('../use-callkit-theme-sync', () => ({ useCallKitThemeSync: vi.fn() }));
+vi.mock('../native-call-state', () => ({
+ useNativeCallState: () => ({
+ setBootstrapChannelId: vi.fn(),
+ setParticipantIdentities: vi.fn(),
+ setSnapshot: vi.fn(),
+ snapshot: () => null,
+ bootstrapChannelId: () => null,
+ }),
+}));
+vi.mock('@tauri-apps/api/core', () => ({
+ Channel: class {
+ constructor(readonly receive: (payload: unknown) => void) {}
+ },
+ addPluginListener: vi.fn(),
+ invoke: async (
+ command: string,
+ args?: { channel: { receive: (payload: unknown) => void } }
+ ) => {
+ if (args?.channel) bridge.watchers.set(command, args.channel.receive);
+ if (command.endsWith('|get_pending_answered_call')) {
+ const answer = bridge.pending;
+ bridge.pending = null;
+ return answer ?? { channelId: null, nativeMedia: true };
+ }
+ return { state: null };
+ },
+}));
+
+async function settle() {
+ await vi.advanceTimersByTimeAsync(0);
+}
+function answer(channelId = 'channel-1', nativeMedia = true) {
+ const payload = { channelId, nativeMedia };
+ bridge.pending = payload;
+ bridge.watchers.get('plugin:call-kit|watch_call_answered')!(payload);
+}
+function resume() {
+ document.dispatchEvent(new Event('visibilitychange'));
+}
+
+beforeEach(() => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ vi.useFakeTimers();
+ bridge.pending = null;
+ bridge.watchers.clear();
+ bridge.open.mockClear();
+ bridge.join.mockClear();
+ vi.stubGlobal(
+ 'document',
+ Object.assign(new EventTarget(), { visibilityState: 'visible' })
+ );
+});
+afterEach(() => {
+ delete window.__MACRO_ANDROID_CALL_KIT__;
+ bridge.cleanups.splice(0).forEach((cleanup) => cleanup());
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+});
+
+describe('native answered-call recovery', () => {
+ it.each([true, false])(
+ 'consumes a live answer with nativeMedia=%s before a later resume',
+ async (nativeMedia) => {
+ useCallKitSetup();
+ await settle();
+ answer('channel-1', nativeMedia);
+ await settle();
+ const navigation = nativeMedia ? bridge.open : bridge.join;
+ expect(navigation).toHaveBeenCalledExactlyOnceWith('channel-1');
+ expect(bridge.pending).toBeNull();
+ await vi.advanceTimersByTimeAsync(3000);
+ resume();
+ await settle();
+ expect(navigation).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('recovers a cold-start answer and a subsequent answer missed while suspended', async () => {
+ bridge.pending = { channelId: 'channel-1', nativeMedia: true };
+ useCallKitSetup();
+ await settle();
+ expect(bridge.open).toHaveBeenCalledExactlyOnceWith('channel-1');
+ await vi.advanceTimersByTimeAsync(3000);
+ bridge.pending = { channelId: 'channel-2', nativeMedia: true };
+ resume();
+ await settle();
+ expect(bridge.open).toHaveBeenCalledTimes(2);
+ expect(bridge.open).toHaveBeenLastCalledWith('channel-2');
+ });
+
+ it('allows a new call in the same channel after the previous call ends', async () => {
+ useCallKitSetup();
+ await settle();
+ answer();
+ await settle();
+ bridge.watchers.get('plugin:call-kit|watch_call_ended')!({
+ callId: 'call-1',
+ });
+ answer();
+ await settle();
+ expect(bridge.open).toHaveBeenCalledTimes(2);
+ expect(bridge.pending).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/channel/Call/tests/callkit-drawer-theme.test.ts b/apps/web/src/features/channel/Call/tests/callkit-drawer-theme.test.ts
new file mode 100644
index 0000000000..a94b6970a7
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/callkit-drawer-theme.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ type CallKitDrawerTheme,
+ setNativeCallKitDrawerTheme,
+} from '../callkit-drawer-theme';
+
+const bridge = vi.hoisted(() => ({
+ platform: 'android',
+ native: true,
+ invoke: vi.fn(async () => {}),
+}));
+vi.mock('@tauri-apps/plugin-os', () => ({ version: () => '16' }));
+vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLKIT: true }));
+vi.mock('@core/util/platform', () => ({
+ isTauri: () => bridge.native,
+ isPlatform: (platform: string) => platform === bridge.platform,
+}));
+vi.mock('@tauri-apps/api/core', () => ({ invoke: bridge.invoke }));
+vi.mock('@theme/signals/themeReactive', () => ({ themeReactive: {} }));
+const color = { red: 0.2, green: 0.3, blue: 0.4, alpha: 1 };
+const theme: CallKitDrawerTheme = {
+ drawerBackground: color,
+ text: color,
+ messageBackground: color,
+ overlayBackground: color,
+ edgeMuted: color,
+ edge: color,
+ inkMuted: color,
+ failure: color,
+ failureInk: color,
+ success: color,
+};
+
+describe('native drawer theme bridge', () => {
+ beforeEach(() => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ bridge.platform = 'android';
+ bridge.native = true;
+ bridge.invoke.mockClear();
+ });
+ it('sends Android the theme envelope expected by its native command', async () => {
+ await setNativeCallKitDrawerTheme(theme);
+ expect(bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ 'plugin:call-kit|set_call_drawer_theme',
+ { theme }
+ );
+ });
+ it('preserves the existing iOS theme argument shape', async () => {
+ bridge.platform = 'ios';
+ await setNativeCallKitDrawerTheme(theme);
+ expect(bridge.invoke).toHaveBeenCalledExactlyOnceWith(
+ 'plugin:call-kit|set_call_drawer_theme',
+ theme
+ );
+ });
+ it('does not invoke a native command in the browser', async () => {
+ bridge.native = false;
+ await setNativeCallKitDrawerTheme(theme);
+ expect(bridge.invoke).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/features/channel/Call/tests/native-call-platform.test.ts b/apps/web/src/features/channel/Call/tests/native-call-platform.test.ts
new file mode 100644
index 0000000000..4a35cc1c44
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/native-call-platform.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { isNativeCallEnabled } from '../native-call-platform';
+
+const platform = vi.hoisted(() => ({
+ os: 'android',
+ version: '16',
+ native: true,
+ enabled: true,
+}));
+vi.mock('@core/constant/featureFlags', () => ({
+ get ENABLE_CALLKIT() {
+ return platform.enabled;
+ },
+}));
+vi.mock('@core/util/platform', () => ({
+ isTauri: () => platform.native,
+ isPlatform: (os: string) => os === platform.os,
+}));
+vi.mock('@tauri-apps/plugin-os', () => ({ version: () => platform.version }));
+
+describe('native call binary compatibility', () => {
+ beforeEach(() => {
+ platform.os = 'android';
+ platform.version = '16';
+ platform.native = true;
+ platform.enabled = true;
+ delete window.__MACRO_ANDROID_CALL_KIT__;
+ });
+ afterEach(() => {
+ delete window.__MACRO_ANDROID_CALL_KIT__;
+ });
+ it('keeps older Android APKs on browser media even with a new frontend', () => {
+ expect(isNativeCallEnabled()).toBe(false);
+ });
+ it('enables native calling only when the binary advertises the plugin', () => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ expect(isNativeCallEnabled()).toBe(true);
+ });
+ it.each(['7.0', '7.1.2', 'unknown'])(
+ 'preserves browser calling on unsupported Android %s',
+ (version) => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ platform.version = version;
+ expect(isNativeCallEnabled()).toBe(false);
+ }
+ );
+ it('supports the minimum Telecom version, Android 8', () => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ platform.version = '8.0.0';
+ expect(isNativeCallEnabled()).toBe(true);
+ });
+ it('leaves iOS native behavior independent of the Android capability', () => {
+ platform.os = 'ios';
+ expect(isNativeCallEnabled()).toBe(true);
+ });
+ it.each(['web', 'desktop'])(
+ 'keeps %s calling in the browser session',
+ (os) => {
+ window.__MACRO_ANDROID_CALL_KIT__ = true;
+ platform.os = os;
+ expect(isNativeCallEnabled()).toBe(false);
+ }
+ );
+ it('honors the existing native calling feature flag', () => {
+ platform.os = 'ios';
+ platform.enabled = false;
+ expect(isNativeCallEnabled()).toBe(false);
+ });
+});
diff --git a/apps/web/src/features/channel/Call/use-callkit.ts b/apps/web/src/features/channel/Call/use-callkit.ts
index bd888780ea..e613de9f04 100644
--- a/apps/web/src/features/channel/Call/use-callkit.ts
+++ b/apps/web/src/features/channel/Call/use-callkit.ts
@@ -2,7 +2,7 @@ import { whenSplitManagerReady } from '@app/signal/splitLayout';
import { registerPushRegistrationLifecycle } from '@core/auth/push-registration-lifecycle';
import { ENABLE_CALLKIT } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
-import { isPlatform, isTauri } from '@core/util/platform';
+import { isPlatform } from '@core/util/platform';
import { useUserNamesQuery } from '@queries/auth';
import { invalidateActiveCallQueries } from '@queries/call/call';
import type { UserName } from '@service-auth/generated/schemas/userName';
@@ -12,6 +12,7 @@ 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 { isNativeCallEnabled } from './native-call-platform';
import {
type NativeCallSnapshot,
type NativeCallState,
@@ -20,6 +21,8 @@ import {
import { openChannelCallTab } from './open-channel-call-tab';
import { useCallKitThemeSync } from './use-callkit-theme-sync';
+export { isNativeCallEnabled } from './native-call-platform';
+
// 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;
@@ -203,7 +206,7 @@ function getActiveCallEndedHandler(): CallEndedHandler | undefined {
}
export function isNativeIosCallKitEnabled(): boolean {
- return ENABLE_CALLKIT && isTauri() && isPlatform('ios');
+ return isNativeCallEnabled() && isPlatform('ios');
}
// Fresh CallKit launches can receive answer events before the router tree mounts.
@@ -247,16 +250,16 @@ async function joinChannelCallWhenReady(
}
/**
- * Sets up CallKit / PushKit integration for iOS.
+ * Sets up CallKit / PushKit integration for iOS and Android.
*
* - 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).
+ * Must be mounted once at app startup on mobile (no-op on desktop).
*/
export function useCallKitSetup() {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
const nativeCall = useNativeCallState();
@@ -316,35 +319,37 @@ export function useCallKitSetup() {
);
}
- // Token rotation: PushKit can hand us a new token at any point at runtime.
- trackListener(
- addPluginListener<VoipTokenPayload>(
- 'call-kit',
- 'voip-token-updated',
- async ({ token }) => {
- console.info('[callkit] received VoIP token update', {
- tokenLength: token.length,
- });
- await registerVoipToken(token).catch((err) =>
- console.error('[callkit] failed to register VoIP token', err)
- );
- }
- ),
- 'voip-token-updated'
- );
+ if (isPlatform('ios')) {
+ // Token rotation: PushKit can hand us a new token at any point at runtime.
+ trackListener(
+ addPluginListener<VoipTokenPayload>(
+ 'call-kit',
+ 'voip-token-updated',
+ async ({ token }) => {
+ console.info('[callkit] received VoIP token update', {
+ tokenLength: token.length,
+ });
+ await registerVoipToken(token).catch((err) =>
+ console.error('[callkit] failed to register VoIP token', err)
+ );
+ }
+ ),
+ 'voip-token-updated'
+ );
- // Cold start: drain any token that arrived from PushKit before the
- // listener above was registered.
- syncVoipRegistration().catch((err) =>
- console.error('[callkit] failed to register cached VoIP token', err)
- );
+ // Cold start: drain any token that arrived from PushKit before the
+ // listener above was registered.
+ syncVoipRegistration().catch((err) =>
+ console.error('[callkit] failed to register cached VoIP token', err)
+ );
- // Account switch: rebind on login and remove on logout so the previous account's calls stop ringing this device. Registrations are idempotent upserts, so overlap between these three triggers is harmless.
- const removeVoipLifecycle = registerPushRegistrationLifecycle({
- syncRegistration: syncVoipRegistration,
- unregisterForLogout: unregisterVoipForLogout,
- });
- onCleanup(removeVoipLifecycle);
+ // Account switch: rebind on login and remove on logout so the previous account's calls stop ringing this device. Registrations are idempotent upserts, so overlap between these three triggers is harmless.
+ const removeVoipLifecycle = registerPushRegistrationLifecycle({
+ syncRegistration: syncVoipRegistration,
+ unregisterForLogout: unregisterVoipForLogout,
+ });
+ onCleanup(removeVoipLifecycle);
+ }
const handleCallAnswered = (
{ channelId, nativeMedia }: CallAnsweredPayload,
@@ -376,10 +381,15 @@ export function useCallKitSetup() {
registerChannelWatcher<CallAnsweredPayload>(
'watch_call_answered',
'call answered',
- (payload) => handleCallAnswered(payload, 'channel')
+ (payload) => {
+ handleCallAnswered(payload, 'channel');
+ // Native retains the same answer for suspended/cold-start recovery.
+ // Consume it now so a later foreground drain cannot navigate again.
+ drainPendingAnsweredCall(payload);
+ }
);
- const drainPendingAnsweredCall = () => {
+ function drainPendingAnsweredCall(handled?: CallAnsweredPayload) {
invoke<GetPendingAnsweredCallResponse>(
'plugin:call-kit|get_pending_answered_call'
)
@@ -389,6 +399,12 @@ export function useCallKitSetup() {
nativeMedia,
});
if (!channelId) return;
+ if (
+ handled?.channelId === channelId &&
+ (handled.nativeMedia ?? false) === (nativeMedia ?? false)
+ ) {
+ return;
+ }
handleCallAnswered(
{ channelId, nativeMedia: nativeMedia ?? false },
'pending'
@@ -397,7 +413,7 @@ export function useCallKitSetup() {
.catch((err) =>
console.error('[callkit] get_pending_answered_call failed', err)
);
- };
+ }
drainPendingAnsweredCall();
@@ -485,6 +501,7 @@ export function useCallKitSetup() {
// the foreground so an ended call can never keep rendering as active.
const handleVisibilityChange = () => {
if (document.visibilityState !== 'visible') return;
+ drainPendingAnsweredCall();
syncNativeCallState(nativeCall).catch((err) =>
console.error('[callkit] foreground native call state sync failed', err)
);
@@ -593,7 +610,7 @@ export async function syncNativeCallStateAfterLeave(
nativeCall: NativeCallState,
stateBeforeLeave: NativeCallStateBeforeLeave
): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
await syncNativeCallState(nativeCall, {
clearOnlyIfUnchangedSince: stateBeforeLeave,
});
@@ -739,7 +756,7 @@ function useCallKitParticipantDisplayNameSync() {
}
export function CallKitSync() {
- if (!isNativeIosCallKitEnabled()) return null;
+ if (!isNativeCallEnabled()) return null;
useCallKitNativeMetadataSync();
useCallKitParticipantDisplayNameSync();
@@ -844,23 +861,50 @@ function fallbackParticipantName(identity: string): string {
* the user leaves from within the app rather than from the CallKit sheet.
*/
export async function endCallKitCall(): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
await invoke('plugin:call-kit|end_active_call').catch((err) =>
console.error('[callkit] failed to end active call', err)
);
}
+const pendingAndroidJoins = new Map<string, string>();
+
+/** Pause ring resolution before the join API marks this user as answered. */
+export async function prepareNativeCallJoin(
+ channelId: string
+): Promise<() => Promise<void>> {
+ if (!isNativeCallEnabled() || !isPlatform('android')) return async () => {};
+ const { lease } = await invoke<{ lease: string }>(
+ 'plugin:call-kit|prepare_join',
+ { channelId }
+ );
+ pendingAndroidJoins.set(channelId, lease);
+ let cleaned = false;
+ return async () => {
+ if (cleaned) return;
+ cleaned = true;
+ if (pendingAndroidJoins.get(channelId) === lease)
+ pendingAndroidJoins.delete(channelId);
+ await invoke('plugin:call-kit|abort_join', { lease });
+ };
+}
+
export async function startNativeCallKitOutgoingCall(
args: StartOutgoingCallArgs,
nativeCall: Pick<NativeCallState, 'setBootstrapChannelId'>
): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) 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);
+ await invoke('plugin:call-kit|start_outgoing_call', {
+ ...args,
+ ...(isPlatform('android')
+ ? { joinLease: pendingAndroidJoins.get(args.channelId) ?? null }
+ : {}),
+ });
markNativeCallActivity();
nativeCall.setBootstrapChannelId(args.channelId);
}
@@ -868,7 +912,7 @@ export async function startNativeCallKitOutgoingCall(
export async function setNativeCallKitVideoOverlayMode(
mode: NativeCallSnapshot['videoOverlayMode']
): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
await invoke('plugin:call-kit|set_video_overlay_mode', { mode }).catch(
(err) =>
console.error('[callkit] failed to set native video overlay mode', err)
@@ -878,7 +922,7 @@ export async function setNativeCallKitVideoOverlayMode(
async function setNativeCallKitChannelTitle(
channelTitle: string | null
): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
await invoke('plugin:call-kit|set_call_drawer_channel_title', {
channelTitle,
}).catch((err) =>
@@ -890,7 +934,7 @@ async function setNativeCallKitParticipantDisplayName(
identity: string,
displayName: string | null
): Promise<void> {
- if (!isNativeIosCallKitEnabled()) return;
+ if (!isNativeCallEnabled()) return;
await invoke('plugin:call-kit|set_participant_display_name', {
identity,
displayName,
diff --git a/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx b/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
index 3aae7ba0c1..6356ed8590 100644
--- a/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
+++ b/apps/web/src/features/channel/Channel/use-channel-tab-items.tsx
@@ -1,5 +1,5 @@
import { useCall } from '@channel/Call/use-call';
-import { isNativeIosCallKitEnabled } from '@channel/Call/use-callkit';
+import { isNativeCallEnabled } from '@channel/Call/use-callkit';
import type { TabItem } from '@core/component/Tabs';
import { ENABLE_CALLS } from '@core/constant/featureFlags';
import { useChannel, useChannelType } from '@core/context/channels';
@@ -14,7 +14,7 @@ import {
} from './channel-tabs';
export const canUseInlineCallTab = () => {
- return !isNativeIosCallKitEnabled();
+ return !isNativeCallEnabled();
};
// Native iOS CallKit owns the call surface, so the embedded Call tab should
diff --git a/apps/web/src/lib/queries/notification/device-registration.ts b/apps/web/src/lib/queries/notification/device-registration.ts
index 5876922f6f..55dfe6570b 100644
--- a/apps/web/src/lib/queries/notification/device-registration.ts
+++ b/apps/web/src/lib/queries/notification/device-registration.ts
@@ -1,7 +1,10 @@
import { notificationServiceClient } from '@service-notification/client';
+import type { DeviceRequest } from '@service-notification/generated/schemas/deviceRequest';
import { fetchUserInfo } from '../auth/user-info';
-type Device = { deviceType: 'android' | 'ios'; token: string };
+type Device = DeviceRequest & {
+ deviceType: 'android' | 'ios';
+};
export function registerPushDevice(device: Device) {
return notificationServiceClient.registerDevice(device);
diff --git a/apps/web/src/lib/service-clients/service-notification/generated/schemas/deviceRequest.ts b/apps/web/src/lib/service-clients/service-notification/generated/schemas/deviceRequest.ts
index badbe4f81f..770bd3902f 100644
--- a/apps/web/src/lib/service-clients/service-notification/generated/schemas/deviceRequest.ts
+++ b/apps/web/src/lib/service-clients/service-notification/generated/schemas/deviceRequest.ts
@@ -12,6 +12,8 @@ import type { DeviceType } from './deviceType';
export interface DeviceRequest {
/** The device platform type (iOS or Android). */
deviceType: DeviceType;
+ /** Whether this Android binary supports native Telecom incoming calls. */
+ nativeCallCapable?: boolean;
/** The device push notification token. */
token: string;
}
diff --git a/apps/web/src/lib/service-clients/service-notification/openapi.json b/apps/web/src/lib/service-clients/service-notification/openapi.json
index 22abce106a..8d2113ab05 100644
--- a/apps/web/src/lib/service-clients/service-notification/openapi.json
+++ b/apps/web/src/lib/service-clients/service-notification/openapi.json
@@ -1678,6 +1678,10 @@
"$ref": "#/components/schemas/DeviceType",
"description": "The device platform type (iOS or Android)."
},
+ "nativeCallCapable": {
+ "type": "boolean",
+ "description": "Whether this Android binary supports native Telecom incoming calls."
+ },
"token": {
"type": "string",
"description": "The device push notification token."
diff --git a/apps/web/src/lib/tauri/PushNotification.test.tsx b/apps/web/src/lib/tauri/PushNotification.test.tsx
new file mode 100644
index 0000000000..8233f06593
--- /dev/null
+++ b/apps/web/src/lib/tauri/PushNotification.test.tsx
@@ -0,0 +1,98 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { MaybePushNotificationRegistration } from './PushNotification';
+
+const registration = vi.hoisted(() => ({
+ os: 'android',
+ version: '16',
+ sync: undefined as (() => Promise<void>) | undefined,
+ register: vi.fn(async () => ({ isErr: () => false })),
+}));
+vi.mock('@core/constant/featureFlags', () => ({ ENABLE_CALLKIT: true }));
+vi.mock('@core/util/platform', () => ({
+ isTauri: () => true,
+ isPlatform: (os: string) => registration.os === os,
+}));
+vi.mock('@tauri-apps/plugin-os', () => ({
+ version: () => registration.version,
+}));
+vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => true }));
+vi.mock('@core/auth/push-registration-lifecycle', () => ({
+ registerPushRegistrationLifecycle: (hooks: {
+ syncRegistration: () => Promise<void>;
+ }) => {
+ registration.sync = hooks.syncRegistration;
+ return () => {};
+ },
+ syncPushRegistrations: async () => {},
+}));
+vi.mock('@queries/notification/device-registration', () => ({
+ fetchPushRecipient: async () => 'macro|[email protected]',
+ registerPushDevice: registration.register,
+ unregisterPushDevice: async () => ({ isErr: () => false }),
+}));
+vi.mock('@solid-primitives/storage', () => ({
+ makePersisted: (signal: unknown) => signal,
+}));
+vi.mock('@tauri-apps/plugin-notification', () => ({
+ removeAllActive: async () => {},
+}));
+vi.mock('@notifications', () => ({
+ PlatformNotificationProvider: () => null,
+ triggerNotificationNavigation: vi.fn(),
+}));
+vi.mock('./TauriProvider', () => ({
+ useExpectTauri: () => ({ os: registration.os }),
+}));
+vi.mock('./notification', () => ({
+ createTauriNotificationInterface: vi.fn(),
+}));
+vi.mock('./push-api', () => ({
+ createPushApi: () => ({
+ checkPermissions: async () => ({ status: 'granted' }),
+ register: async () => ({ token: 'test-device-token' }),
+ configureRecipient: async () => {},
+ watch: async () => {},
+ unwatch: async () => {},
+ }),
+}));
+
+let dispose: (() => void) | undefined;
+beforeEach(() => {
+ registration.os = 'android';
+ registration.version = '16';
+ registration.sync = undefined;
+ registration.register.mockClear();
+ delete window.__MACRO_ANDROID_CALL_KIT__;
+});
+afterEach(() => {
+ dispose?.();
+ delete window.__MACRO_ANDROID_CALL_KIT__;
+});
+
+describe('push registration native-call capability', () => {
+ it.each([
+ { os: 'android', version: '16', binary: true, expected: true },
+ { os: 'android', version: '16', binary: false, expected: false },
+ { os: 'android', version: '7.1.2', binary: true, expected: false },
+ { os: 'ios', version: '18', binary: false, expected: undefined },
+ ])(
+ 'registers $os $version with binary capability $binary',
+ async ({ os, version, binary, expected }) => {
+ registration.os = os;
+ registration.version = version;
+ if (binary) window.__MACRO_ANDROID_CALL_KIT__ = true;
+ createRoot((cleanup) => {
+ dispose = cleanup;
+ MaybePushNotificationRegistration({ children: null });
+ });
+ expect(registration.sync).toBeDefined();
+ await registration.sync!();
+ expect(registration.register).toHaveBeenCalledExactlyOnceWith({
+ deviceType: os,
+ token: 'test-device-token',
+ ...(expected === undefined ? {} : { nativeCallCapable: expected }),
+ });
+ }
+ );
+});
diff --git a/apps/web/src/lib/tauri/PushNotification.tsx b/apps/web/src/lib/tauri/PushNotification.tsx
index 093dd642dc..cb3277141d 100644
--- a/apps/web/src/lib/tauri/PushNotification.tsx
+++ b/apps/web/src/lib/tauri/PushNotification.tsx
@@ -1,3 +1,4 @@
+import { isNativeCallEnabled } from '@channel/Call/native-call-platform';
import {
registerPushRegistrationLifecycle,
syncPushRegistrations,
@@ -88,7 +89,13 @@ function usePushNotifications(
const recipient = await fetchRecipient();
if (recipient === undefined) return 'denied';
if (aborted(epoch)) return 'denied';
- const res = await registerPushDevice({ deviceType, token });
+ const res = await registerPushDevice({
+ deviceType,
+ token,
+ ...(deviceType === 'android'
+ ? { nativeCallCapable: isNativeCallEnabled() }
+ : {}),
+ });
if (res.isErr()) {
// Transient failures must not erase a previously granted permission.
console.error('failed to register device for push', res.error);
diff --git a/apps/web/src/lib/tauri/TauriProvider.tsx b/apps/web/src/lib/tauri/TauriProvider.tsx
index c84d8cf560..266997537f 100644
--- a/apps/web/src/lib/tauri/TauriProvider.tsx
+++ b/apps/web/src/lib/tauri/TauriProvider.tsx
@@ -106,7 +106,7 @@ function TauriProvider(props: { children: JSX.Element }) {
setNativeAppUpdateRequiredDialogOpen(true);
});
- if (isTauri() && isPlatform('ios')) useCallKitSetup();
+ useCallKitSetup();
const value: TauriContextValue = {
os: osType(),
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 4f9fbbcce9..fe07994a61 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -6802,6 +6802,8 @@ dependencies = [
name = "tauri-plugin-call-kit"
version = "0.1.0"
dependencies = [
+ "serde",
+ "serde_json",
"tauri",
"tauri-plugin",
]
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushService.kt b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushService.kt
index 9402bd174e..9ca3757912 100644
--- a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushService.kt
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushService.kt
@@ -5,7 +5,15 @@ import com.google.firebase.messaging.RemoteMessage
class PushService : FirebaseMessagingService() {
override fun onMessageReceived(message: RemoteMessage) {
- PushStore.receive(this, message.data, message.sentTime)
+ if (message.data["type"] == "call") {
+ // Explicit in-package broadcast keeps the FCM workstream independent
+ // of the native call plugin and never hands credentials to the WebView.
+ sendBroadcast(android.content.Intent("com.macro.call.PUSH")
+ .setClassName(packageName, "com.macro.call.CallReceiver")
+ .putExtra("recipientId", message.data["recipientId"])
+ .putExtra("payload", message.data["payload"])
+ .putExtra("sentTime", message.sentTime))
+ } else PushStore.receive(this, message.data, message.sentTime)
}
override fun onNewToken(token: String) {
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushStore.kt b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushStore.kt
index d859f45116..490e5aa6c7 100644
--- a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushStore.kt
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushStore.kt
@@ -52,6 +52,9 @@ internal object PushStore {
fun configure(context: Context, recipient: String?) {
val preferences = prefs(context)
if (recipient != preferences.getString("recipient", null) || recipient == null) {
+ context.sendBroadcast(Intent("com.macro.call.RESET")
+ .setClassName(context.packageName, "com.macro.call.CallReceiver")
+ .putExtra("previousRecipient", preferences.getString("recipient", null)))
generation++
val old = records(context)
old.keys().forEach { NotificationManagerCompat.from(context).cancel(it, 0) }
diff --git a/apps/web/tauri/callkit_plugin/Cargo.toml b/apps/web/tauri/callkit_plugin/Cargo.toml
index ad3af53adc..b30186724c 100644
--- a/apps/web/tauri/callkit_plugin/Cargo.toml
+++ b/apps/web/tauri/callkit_plugin/Cargo.toml
@@ -12,3 +12,7 @@ tauri = { workspace = true }
[target.'cfg(target_os = "ios")'.dependencies]
tauri = { workspace = true, features = ["wry"] }
+
+[target.'cfg(target_os = "android")'.dependencies]
+serde = { workspace = true, features = ["derive"] }
+serde_json = "1"
diff --git a/apps/web/tauri/callkit_plugin/android/build.gradle.kts b/apps/web/tauri/callkit_plugin/android/build.gradle.kts
new file mode 100644
index 0000000000..a2914308c4
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/build.gradle.kts
@@ -0,0 +1,30 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+android {
+ namespace = "com.macro.call"
+ compileSdk = 36
+ defaultConfig {
+ minSdk = 24
+ targetSdk = 36
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+ }
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ }
+ kotlinOptions { jvmTarget = "1.8" }
+}
+dependencies {
+ implementation(project(":tauri-android"))
+ implementation("androidx.core:core-ktx:1.15.0")
+ implementation("androidx.appcompat:appcompat:1.7.1")
+ implementation("io.livekit:livekit-android:2.29.0")
+ implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
+ testImplementation("junit:junit:4.13.2")
+ testImplementation("org.json:json:20240303")
+ testImplementation("com.fasterxml.jackson.core:jackson-databind:2.15.3")
+ androidTestImplementation("androidx.test:runner:1.6.2")
+ androidTestImplementation("androidx.test.ext:junit:1.2.1")
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml b/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml
new file mode 100644
index 0000000000..a1fb1c4e3b
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/AndroidManifest.xml
@@ -0,0 +1,4 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <!-- Only the instrumentation APK may connect to the local development server. -->
+ <application android:usesCleartextTraffic="true" />
+</manifest>
diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt
new file mode 100644
index 0000000000..8578c57312
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/IncomingCallTest.kt
@@ -0,0 +1,369 @@
+package com.macro.call
+
+import android.content.Context
+import android.app.NotificationManager
+import android.os.Build
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import org.json.JSONObject
+import org.junit.After
+import org.junit.Assert.*
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.util.UUID
+import kotlinx.coroutines.CompletableDeferred
+
+/** Exercises real Telecom/foreground service wiring without backend credentials. */
+@RunWith(AndroidJUnit4::class)
+class IncomingCallTest {
+ private val instrumentation = InstrumentationRegistry.getInstrumentation()
+ private val context = instrumentation.targetContext
+
+ @Before fun registerRecipient() {
+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().putString("recipient", "call-test-user").commit()
+ if (Build.VERSION.SDK_INT >= 33) {
+ instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} android.permission.POST_NOTIFICATIONS").close()
+ }
+ instrumentation.runOnMainSync { Calls.end(context) }
+ }
+
+ @After fun cleanup() {
+ instrumentation.runOnMainSync { Calls.end(context) }
+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().clear().commit()
+ }
+
+ private fun data(id: String, recipient: String = "call-test-user") = mapOf(
+ "recipientId" to recipient,
+ "payload" to JSONObject().apply {
+ put("callId", id)
+ put("channelId", "call-test-channel")
+ put("channelName", "Emulator call")
+ put("livekitServerUrl", "wss://unused.invalid")
+ put("livekitToken", "test-token")
+ // An unavailable status endpoint must never authorize an answer.
+ put("ringStatusUrl", "https://unavailable-call-test.macro.com/status")
+ }.toString(),
+ )
+
+ @Test fun incomingTelecomConnectionDeclinesAndRejectsRedelivery() {
+ val id = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync { Calls.receive(context, data(id), System.currentTimeMillis()) }
+ val deadline = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < deadline) {
+ var connected = false
+ instrumentation.runOnMainSync {
+ connected = Calls.connection != null && context.getSystemService(NotificationManager::class.java)
+ .activeNotifications.any { it.id == CallService.NOTIFICATION_ID }
+ }
+ if (connected) break
+ Thread.sleep(100)
+ }
+ instrumentation.runOnMainSync {
+ assertEquals(id, Calls.offer?.callId)
+ assertNotNull("Telecom must create the native connection", Calls.connection)
+ val notification = context.getSystemService(NotificationManager::class.java)
+ .activeNotifications.single { it.id == CallService.NOTIFICATION_ID }.notification
+ assertTrue("Incoming notification must expose answer/decline", notification.actions.size >= 2)
+ assertNull("Ringing must not start a media room", Calls.room)
+ assertNull("Ringing must not restore an active web session", Calls.snapshot())
+ Calls.connection!!.onReject()
+ assertNull(Calls.offer)
+ assertNull(Calls.connection)
+ Calls.receive(context, data(id), System.currentTimeMillis())
+ assertNull("Declined calls must not ring again", Calls.offer)
+ }
+ }
+
+ @Test fun redeliveredStartRestoresServiceOwnershipAndCleansUpOnHangup() {
+ val id = UUID.randomUUID().toString()
+ val manager = context.getSystemService(NotificationManager::class.java)
+ instrumentation.runOnMainSync { Calls.receive(context, data(id), System.currentTimeMillis()) }
+ fun awaitCondition(message: String, condition: () -> Boolean) {
+ val deadline = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < deadline) {
+ var ready = false
+ instrumentation.runOnMainSync { ready = condition() }
+ if (ready) return
+ Thread.sleep(100)
+ }
+ fail(message)
+ }
+ awaitCondition("Call service did not start") { CallService.instance != null }
+ var service: CallService? = null
+ instrumentation.runOnMainSync {
+ service = CallService.instance
+ // Model the ownership gap after stop() clears the pointer but before
+ // Android destroys the service. Deliver a real start to that same object.
+ CallService::class.java.getDeclaredField("instance").apply { isAccessible = true }.set(null, null)
+ CallService.start(context)
+ }
+ awaitCondition("Redelivered start did not restore the live instance") { CallService.instance != null }
+ instrumentation.runOnMainSync {
+ assertSame("Android must reuse the existing service", service, CallService.instance)
+ Calls.end(context, id)
+ }
+ awaitCondition("Hangup left a foreground call notification") {
+ CallService.instance == null && manager.activeNotifications.none { it.id == CallService.NOTIFICATION_ID }
+ }
+ val mediaSession = CallService::class.java.getDeclaredField("mediaSession").apply { isAccessible = true }
+ awaitCondition("Hangup did not release the service media session") { mediaSession.get(service) == null }
+ }
+
+ @Test fun endingBeforeServiceStartDoesNotCrashOrLeaveANotification() {
+ val id = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(id), System.currentTimeMillis())
+ // Queue the foreground service and decline in the same main-thread turn,
+ // before Android can create/promote the service.
+ CallService.start(context)
+ Calls.end(context, id)
+ }
+ // Stay alive beyond Android's foreground-service deadline.
+ Thread.sleep(12_000)
+ instrumentation.runOnMainSync {
+ assertNull(Calls.offer)
+ assertNull(CallService.instance)
+ assertFalse(context.getSystemService(NotificationManager::class.java)
+ .activeNotifications.any { it.id == CallService.NOTIFICATION_ID })
+ val next = UUID.randomUUID().toString()
+ Calls.receive(context, data(next), System.currentTimeMillis())
+ assertEquals("The process must still accept subsequent calls", next, Calls.offer?.callId)
+ Calls.end(context, next)
+ }
+ }
+
+ @Test fun telecomTeardownFailureStillRemovesNotificationAndAllowsAnotherCall() {
+ val id = UUID.randomUUID().toString()
+ val manager = context.getSystemService(NotificationManager::class.java)
+ instrumentation.runOnMainSync { Calls.receive(context, data(id), System.currentTimeMillis()) }
+ fun awaitNotification(expected: Boolean) {
+ val deadline = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < deadline) {
+ if (manager.activeNotifications.any { it.id == CallService.NOTIFICATION_ID } == expected) return
+ Thread.sleep(100)
+ }
+ fail("Call notification visibility did not become $expected")
+ }
+ awaitNotification(true)
+ var injected = false
+ instrumentation.runOnMainSync {
+ assertNotNull(Calls.connection)
+ Calls.end(context, id) { injected = true; throw IllegalStateException("Simulated Telecom callback failure") }
+ assertTrue("Fault must occur during actual Telecom teardown", injected)
+ assertNull(Calls.offer)
+ assertNull(Calls.connection)
+ assertNull(Calls.snapshot())
+ }
+ awaitNotification(false)
+ instrumentation.waitForIdleSync()
+ val next = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync { Calls.receive(context, data(next), System.currentTimeMillis()) }
+ awaitNotification(true)
+ instrumentation.runOnMainSync {
+ assertEquals("Failed cleanup must not prevent the next incoming call", next, Calls.offer?.callId)
+ assertNotNull(Calls.connection)
+ Calls.end(context, next)
+ }
+ awaitNotification(false)
+ }
+
+ @Test fun unrelatedRingHangupPreservesPendingJoin() {
+ val ringId = UUID.randomUUID().toString()
+ val outgoingId = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(ringId), System.currentTimeMillis())
+ val lease = Calls.prepareJoin(context, "other-channel")
+ try {
+ Calls.end(context, ringId)
+ Calls.outgoing(context, CallOffer(outgoingId, "other-channel", "Outgoing call",
+ "wss://unused.invalid", "test-token"), lease)
+ assertEquals("Unrelated ring teardown must preserve the outgoing lease", outgoingId, Calls.offer?.callId)
+ } finally {
+ Calls.abortJoin(context, lease)
+ Calls.end(context)
+ }
+ }
+ }
+
+ @Test fun microphonePermissionPausesExpiryThenRevalidatesCancellation() {
+ val id = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(id), System.currentTimeMillis() - 59_000)
+ assertTrue(Calls.beginMicrophonePermission(id))
+ }
+ Thread.sleep(2_000)
+ instrumentation.runOnMainSync {
+ assertEquals("Permission wait must not expire an otherwise valid ring", id, Calls.offer?.callId)
+ Calls.finishMicrophonePermission(id)
+ Calls.answer(context, id) { "ended" }
+ assertNull("Permission completion must still revalidate remote cancellation", Calls.offer)
+ assertNull(Calls.room)
+ }
+ }
+
+ @Test fun duplicateAnswerIntentsPreservePendingPermissionAction() {
+ val id = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync { Calls.receive(context, data(id), System.currentTimeMillis()) }
+ val activity = instrumentation.startActivitySync(android.content.Intent(context, CallActivity::class.java)
+ .addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) as CallActivity
+ var completions = 0
+ val originalAction: () -> Unit = { completions++ }
+ val field = CallActivity::class.java.getDeclaredField("permissionAction").apply { isAccessible = true }
+ val newIntent = CallActivity::class.java.getDeclaredMethod("onNewIntent", android.content.Intent::class.java).apply { isAccessible = true }
+ instrumentation.runOnMainSync {
+ // Model a platform permission request already in flight, without changing
+ // process-wide permissions or depending on the system dialog's layout.
+ field.set(activity, originalAction)
+ CallActivity::class.java.getDeclaredField("permissionCallId").apply { isAccessible = true }.set(activity, id)
+ assertTrue(Calls.beginMicrophonePermission(id))
+ repeat(2) {
+ newIntent.invoke(activity, android.content.Intent(context, CallActivity::class.java).putExtra("answer", id))
+ assertSame("A duplicate intent must retain the original permission completion", originalAction, field.get(activity))
+ }
+ activity.onRequestPermissionsResult(99, emptyArray(), intArrayOf())
+ assertSame("Unrelated permission results must not consume this request", originalAction, field.get(activity))
+ activity.onRequestPermissionsResult(4, arrayOf(android.Manifest.permission.RECORD_AUDIO),
+ intArrayOf(android.content.pm.PackageManager.PERMISSION_GRANTED))
+ assertEquals(1, completions)
+ assertNull(field.get(activity))
+ activity.finish()
+ }
+ }
+
+ @Test fun ignoresStaleAndOtherAccountOffers() {
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(UUID.randomUUID().toString(), "another-account"), System.currentTimeMillis())
+ assertNull(Calls.offer)
+ Calls.receive(context, data(UUID.randomUUID().toString()), System.currentTimeMillis() - 61_000)
+ assertNull(Calls.offer)
+ assertNull(Calls.room)
+ }
+ }
+
+ @Test fun incomingWhileScreenOffKeepsNotificationActions() {
+ instrumentation.uiAutomation.executeShellCommand("input keyevent 223").close()
+ try {
+ incomingTelecomConnectionDeclinesAndRejectsRedelivery()
+ } finally {
+ instrumentation.uiAutomation.executeShellCommand("input keyevent 224").close()
+ }
+ }
+
+ @Test fun appJoinAdoptsRingingCallWithoutTreatingItsMembershipAsRemoteAnswer() {
+ instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} android.permission.RECORD_AUDIO").close()
+ val id = UUID.randomUUID().toString()
+ val status = CompletableDeferred<String?>()
+ lateinit var lease: String
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(id), System.currentTimeMillis())
+ Calls.answer(context, id) { status.await() }
+ lease = Calls.prepareJoin(context, "call-test-channel")
+ }
+ val deadline = System.currentTimeMillis() + 10_000
+ while (System.currentTimeMillis() < deadline) {
+ var ready = false
+ instrumentation.runOnMainSync { ready = Calls.connection != null }
+ if (ready) break
+ Thread.sleep(100)
+ }
+ instrumentation.runOnMainSync {
+ val connection = Calls.connection
+ assertNotNull("Telecom must create the ringing connection before app adoption", connection)
+ // The join API and its new token make the old verifier report answered.
+ status.complete("answered")
+ assertEquals(id, Calls.offer?.callId)
+ Calls.outgoing(context, CallOffer(id, "call-test-channel", "Joined call", "wss://unused.invalid", "new-join-token"), lease)
+ assertEquals(id, Calls.offer?.callId)
+ assertEquals("new-join-token", Calls.offer?.token)
+ assertSame("App Join must reuse the existing Telecom connection", connection, Calls.connection)
+ assertNotNull("App Join must start native media instead of declining its own answer", Calls.room)
+ assertNotNull(Calls.snapshot())
+ Calls.abortJoin(context, lease)
+ assertEquals("Committed cleanup must preserve the media session", id, Calls.offer?.callId)
+ Calls.end(context, id)
+ }
+ }
+
+ @Test fun incomingDuringPendingAppJoinCannotBeResolvedByOldRingPolling() {
+ val id = UUID.randomUUID().toString()
+ instrumentation.runOnMainSync {
+ val lease = Calls.prepareJoin(context, "call-test-channel")
+ Calls.receive(context, data(id), System.currentTimeMillis())
+ Calls.answer(context, id) { "answered" }
+ assertEquals(id, Calls.offer?.callId)
+ Calls.abortJoin(context, lease)
+ assertNull("Cancelling a pending join must release its arriving ring", Calls.offer)
+ assertThrows(IllegalStateException::class.java) {
+ Calls.outgoing(context, CallOffer(id, "call-test-channel", "Cancelled", "wss://unused.invalid", "token"), lease)
+ }
+ assertNull(Calls.room)
+ }
+ }
+
+ @Test fun nullAccountResetPreservesUnassignedJoinAndCall() {
+ instrumentation.runOnMainSync {
+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().remove("recipient").commit()
+ val lease = Calls.prepareJoin(context, "call-test-channel")
+ val id = UUID.randomUUID().toString()
+ try {
+ Calls.resetRecipient(context, null)
+ Calls.outgoing(context, CallOffer(id, "call-test-channel", "Unassigned account",
+ "wss://unused.invalid", "token"), lease)
+ assertEquals("Null reset must preserve an unassigned lease", id, Calls.offer?.callId)
+ Calls.resetRecipient(context, null)
+ assertEquals("Null reset must preserve an unassigned active call", id, Calls.offer?.callId)
+ } finally {
+ Calls.abortJoin(context, lease)
+ Calls.end(context)
+ }
+ }
+ }
+
+ @Test fun accountResetAbortsOnlyThatAccountsPendingJoin() {
+ instrumentation.runOnMainSync {
+ val oldLease = Calls.prepareJoin(context, "call-test-channel")
+ Calls.resetRecipient(context, "call-test-user")
+ assertThrows(IllegalStateException::class.java) {
+ Calls.outgoing(context, CallOffer(UUID.randomUUID().toString(), "call-test-channel", "Old account", "wss://unused.invalid", "token"), oldLease)
+ }
+ context.getSharedPreferences("macro_push", Context.MODE_PRIVATE).edit().putString("recipient", "new-account").commit()
+ val newLease = Calls.prepareJoin(context, "call-test-channel")
+ Calls.resetRecipient(context, "call-test-user")
+ Calls.receive(context, data(UUID.randomUUID().toString(), "new-account"), System.currentTimeMillis())
+ assertNotNull("Old account's late reset must not abort a new lease", Calls.offer)
+ Calls.abortJoin(context, newLease)
+ assertNull(Calls.offer)
+ }
+ }
+
+ @Test fun obsoleteAnswerCompletionCannotUnlockAnotherCallsAnswer() {
+ val oldId = UUID.randomUUID().toString()
+ val newId = UUID.randomUUID().toString()
+ val oldStatus = CompletableDeferred<String?>()
+ val newStatus = CompletableDeferred<String?>()
+ var checks = 0
+ try {
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(oldId), System.currentTimeMillis())
+ Calls.answer(context, oldId) { oldStatus.await() }
+ Calls.end(context, oldId)
+ }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ Calls.receive(context, data(newId), System.currentTimeMillis())
+ assertEquals(newId, Calls.offer?.callId)
+ Calls.answer(context, newId) { checks++; newStatus.await() }
+ oldStatus.complete("ringing")
+ Calls.answer(context, newId) { checks++; "answered" }
+ assertEquals("Old verification must not allow a duplicate answer check", 1, checks)
+ assertEquals(newId, Calls.offer?.callId)
+ assertNull(Calls.room)
+ newStatus.complete("ended")
+ assertNull(Calls.offer)
+ }
+ } finally {
+ oldStatus.complete("ended"); newStatus.complete("ended")
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt
new file mode 100644
index 0000000000..6310e89627
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/androidTest/java/com/macro/call/MediaLifecycleTest.kt
@@ -0,0 +1,238 @@
+package com.macro.call
+
+import android.Manifest
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.util.Base64
+import io.livekit.android.LiveKit
+import io.livekit.android.room.track.VideoTrack
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.platform.app.InstrumentationRegistry
+import kotlinx.coroutines.launch
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Assume.assumeNotNull
+import org.junit.Test
+import org.junit.runner.RunWith
+import java.util.UUID
+import javax.crypto.Mac
+import javax.crypto.spec.SecretKeySpec
+
+/** Optional integration test against LiveKit's isolated --dev server. */
+@RunWith(AndroidJUnit4::class)
+class MediaLifecycleTest {
+ private val instrumentation = InstrumentationRegistry.getInstrumentation()
+ private val context = instrumentation.targetContext
+
+ private fun token(identity: String = "android-emulator-test"): String {
+ fun encode(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_PADDING or Base64.NO_WRAP)
+ val header = encode("{\"alg\":\"HS256\",\"typ\":\"JWT\"}".toByteArray())
+ val payload = encode(JSONObject().apply {
+ put("iss", "devkey"); put("sub", identity)
+ put("exp", System.currentTimeMillis() / 1000 + 300)
+ put("video", JSONObject().apply { put("roomJoin", true); put("room", "android-call-test"); put("canPublish", true); put("canSubscribe", true) })
+ }.toString().toByteArray())
+ val body = "$header.$payload"
+ val mac = Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec("secret".toByteArray(), "HmacSHA256")) }
+ return "$body.${encode(mac.doFinal(body.toByteArray()))}"
+ }
+
+ private fun awaitCondition(message: String, condition: () -> Boolean) {
+ val deadline = System.currentTimeMillis() + 30_000
+ while (System.currentTimeMillis() < deadline) {
+ var ready = false
+ instrumentation.runOnMainSync { ready = condition() }
+ if (ready) return
+ Thread.sleep(100)
+ }
+ fail(message)
+ }
+
+ @Test fun nativeRoomSurvivesDuplicateStartAndReleasesCapture() {
+ val url = InstrumentationRegistry.getArguments().getString("livekitUrl")
+ assumeNotNull(url)
+ for (permission in listOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA)) {
+ instrumentation.uiAutomation.executeShellCommand("pm grant ${context.packageName} $permission").close()
+ awaitCondition("Capture permission was not granted") { context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED }
+ }
+ val offer = CallOffer(UUID.randomUUID().toString(), "media-test", "Emulator media", url!!, token())
+ val previousTheme = Calls.drawerTheme
+ val lightTheme = CallTheme(android.graphics.Color.WHITE, android.graphics.Color.rgb(30,30,30), android.graphics.Color.rgb(245,245,245),
+ 0x66000000, android.graphics.Color.rgb(230,230,230), android.graphics.Color.rgb(205,205,205), android.graphics.Color.DKGRAY,
+ android.graphics.Color.rgb(225,55,55), android.graphics.Color.rgb(20,145,95))
+ val darkTheme = lightTheme.copy(drawer = android.graphics.Color.rgb(20,20,20), text = android.graphics.Color.WHITE,
+ tile = android.graphics.Color.rgb(30,30,30), edgeMuted = android.graphics.Color.rgb(48,48,48), edge = android.graphics.Color.rgb(80,80,80), muted = android.graphics.Color.LTGRAY)
+ Calls.drawerTheme = lightTheme
+ val observer = LiveKit.create(context)
+ val extraObservers = List(3) { LiveKit.create(context) }
+ val monitor = instrumentation.addMonitor(CallActivity::class.java.name, null, false)
+ try {
+ instrumentation.runOnMainSync {
+ Calls.outgoing(context, offer)
+ context.startActivity(Intent(context, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+ val activity = instrumentation.waitForMonitorWithTimeout(monitor, 5000)
+ assertNotNull("Native call controls did not open", activity)
+ awaitCondition("Native room did not connect") { Calls.state == "connected" }
+ instrumentation.runOnMainSync { Calls.scope.launch { observer.connect(url, token("media-observer")) } }
+ awaitCondition("Remote participant did not join") { Calls.room?.remoteParticipants?.isNotEmpty() == true }
+ instrumentation.runOnMainSync {
+ extraObservers.forEachIndexed { index, extra -> Calls.scope.launch { extra.connect(url, token("tile-observer-$index")) } }
+ }
+ awaitCondition("Participant strip test peers did not join") { Calls.room?.remoteParticipants?.size == 4 }
+ val root = activity!!.findViewById<android.view.ViewGroup>(android.R.id.content).getChildAt(0) as android.widget.FrameLayout
+ fun assertDrawer(expectedTheme: CallTheme) {
+ val drawer = root.findViewWithTag<android.widget.LinearLayout>("call-drawer")
+ assertNotNull(drawer)
+ val safeHeight = root.height - root.paddingTop - root.paddingBottom
+ assertEquals("Drawer must use 92% of the safe screen", (safeHeight * 0.92f).toInt(), drawer.height)
+ assertEquals(expectedTheme.drawer, (drawer.background as android.graphics.drawable.GradientDrawable).color!!.defaultColor)
+ val controls = root.findViewWithTag<android.view.View>("call-controls")
+ val position = IntArray(2); controls.getLocationOnScreen(position)
+ val rootPosition = IntArray(2); root.getLocationOnScreen(rootPosition)
+ assertTrue("Controls must stay above Android navigation insets",
+ position[1] + controls.height <= rootPosition[1] + root.height - root.paddingBottom)
+ assertEquals(3, (controls as android.view.ViewGroup).childCount)
+ assertTrue(root.findViewWithTag<android.view.View>("call-primary").height > root.findViewWithTag<android.view.View>("call-participant-strip").height)
+ }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ assertDrawer(lightTheme)
+ val strip = root.findViewWithTag<android.widget.HorizontalScrollView>("call-participant-strip")
+ assertTrue("Participant chips must scroll horizontally", strip.canScrollHorizontally(1))
+ strip.scrollTo(100, 0)
+ assertTrue(strip.scrollX > 0)
+ }
+ fun screenshot(name: String) {
+ instrumentation.waitForIdleSync()
+ // Idle messages can complete before SurfaceFlinger presents the next frame.
+ Thread.sleep(300)
+ instrumentation.uiAutomation.takeScreenshot().let { bitmap ->
+ val file = java.io.File(context.getExternalFilesDir(null), name)
+ file.outputStream().use { bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it) }
+ bitmap.recycle()
+ // Gradle removes test app data after the run; retain synthetic UI evidence.
+ instrumentation.uiAutomation.executeShellCommand("cp ${file.absolutePath} /sdcard/Download/$name").close()
+ }
+ }
+ screenshot("call-drawer-light.png")
+ instrumentation.runOnMainSync { Calls.drawerTheme = darkTheme; Calls.publish() }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync { assertDrawer(darkTheme) }
+ screenshot("call-drawer-dark.png")
+ awaitCondition("Audio foreground service did not start") { CallService.instance != null }
+ instrumentation.runOnMainSync {
+ Calls.showIncoming(context)
+ assertTrue("Late Telecom notification must retain microphone support",
+ CallService.instance!!.foregroundServiceType and android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE != 0)
+ }
+ instrumentation.runOnMainSync {
+ val room = Calls.room
+ var injected = false
+ CallService.instance!!.handleStart(Intent().putExtra("media", true).putExtra("camera", true)) { _, types ->
+ assertTrue(types and android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA != 0)
+ injected = true
+ throw SecurityException("Simulated camera promotion denial")
+ }
+ assertTrue("Failure must occur at the foreground promotion boundary", injected)
+ assertSame("Camera promotion failure must retain the audio room", room, Calls.room)
+ assertEquals("connected", Calls.state)
+ assertEquals(offer.callId, Calls.offer?.callId)
+ assertNotNull(CallService.instance)
+ }
+ awaitCondition("Failed camera promotion must preserve the ongoing notification") {
+ context.getSystemService(android.app.NotificationManager::class.java)
+ .activeNotifications.any { it.id == CallService.NOTIFICATION_ID }
+ }
+ instrumentation.runOnMainSync {
+ val room = Calls.room
+ assertNotNull(room)
+ Calls.outgoing(context, offer)
+ assertSame("Duplicate start must retain the media room", room, Calls.room)
+ root.findViewWithTag<android.view.View>("call-control-mic").performClick()
+ }
+ awaitCondition("Native microphone did not mute") { Calls.muted }
+ instrumentation.runOnMainSync { root.findViewWithTag<android.view.View>("call-control-video").performClick() }
+ awaitCondition("Native camera did not start") { Calls.video }
+ instrumentation.runOnMainSync {
+ val room = Calls.room
+ Calls.showIncoming(context)
+ val types = CallService.instance!!.foregroundServiceType
+ assertTrue("Late Telecom notification must retain microphone support",
+ types and android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE != 0)
+ assertTrue("Late Telecom notification must retain camera support",
+ types and android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA != 0)
+ assertSame(room, Calls.room)
+ assertTrue(Calls.video)
+ }
+ awaitCondition("Remote participant did not receive video") {
+ observer.remoteParticipants.values.any { participant -> participant.trackPublications.values.any { it.track is VideoTrack } }
+ }
+ instrumentation.runOnMainSync {
+ val strip = root.findViewWithTag<android.widget.HorizontalScrollView>("call-participant-strip")
+ val chips = strip.getChildAt(0) as android.view.ViewGroup
+ val localTile = (0 until chips.childCount).map { chips.getChildAt(it) }.single { it.contentDescription == "You" }
+ localTile.performClick()
+ assertEquals("Selecting a chip must replace the primary participant", "You", root.findViewWithTag<android.view.View>("call-primary").contentDescription)
+ assertNotNull(root.findViewWithTag<android.view.View>("call-control-switch"))
+ }
+ screenshot("call-drawer-video.png")
+ instrumentation.runOnMainSync { root.findViewWithTag<android.view.View>("call-control-video").performClick() }
+ awaitCondition("Native camera did not stop") { !Calls.video }
+ instrumentation.uiAutomation.executeShellCommand("svc wifi disable").close()
+ instrumentation.uiAutomation.executeShellCommand("svc data disable").close()
+ try {
+ awaitCondition("Native room did not report network interruption") { Calls.state == "reconnecting" }
+ } finally {
+ instrumentation.uiAutomation.executeShellCommand("svc wifi enable").close()
+ instrumentation.uiAutomation.executeShellCommand("svc data enable").close()
+ }
+ awaitCondition("Native room did not reconnect") { Calls.state == "connected" }
+ instrumentation.runOnMainSync { Calls.scope.launch { Calls.camera(context, true) } }
+ awaitCondition("Native camera did not restart before PiP") { Calls.video }
+ val expandedWidth = root.width
+ instrumentation.runOnMainSync {
+ val handle = root.findViewWithTag<android.view.View>("call-drawer-handle")
+ val down = android.view.MotionEvent.obtain(0, 0, android.view.MotionEvent.ACTION_DOWN, 10f, 10f, 0)
+ val up = android.view.MotionEvent.obtain(0, 100, android.view.MotionEvent.ACTION_UP, 10f, 200f, 0)
+ handle.dispatchTouchEvent(down); handle.dispatchTouchEvent(up)
+ down.recycle(); up.recycle()
+ }
+ awaitCondition("Call controls did not enter picture in picture") { activity!!.isInPictureInPictureMode }
+ awaitCondition("PiP transition did not resize the activity") { root.width < expandedWidth }
+ // Mode callbacks precede completion of Android's pinned-task animation.
+ Thread.sleep(1_000)
+ instrumentation.runOnMainSync {
+ context.startActivity(Intent(context, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ }
+ awaitCondition("Reopening call controls did not expand the drawer") { !activity.isInPictureInPictureMode }
+ awaitCondition("Expanded drawer did not regain focus") { activity.hasWindowFocus() }
+ instrumentation.uiAutomation.executeShellCommand("input keyevent 4").close()
+ awaitCondition("Android Back must dismiss the drawer into PiP") { activity.isInPictureInPictureMode }
+ instrumentation.waitForIdleSync()
+ instrumentation.runOnMainSync {
+ assertTrue("Entering PiP must retain camera capture", Calls.video)
+ assertEquals("connected", Calls.state)
+ assertNotNull("Navigation must retain the media room", Calls.room)
+ activity!!.finish()
+ }
+ awaitCondition("Leaving the visible call surface must stop the camera") { !Calls.video }
+ instrumentation.runOnMainSync {
+ assertEquals("Background audio must remain connected", "connected", Calls.state)
+ Calls.end(context, offer.callId)
+ assertNull(Calls.room)
+ assertNull(Calls.connection)
+ assertNull(Calls.snapshot())
+ }
+ } finally {
+ instrumentation.uiAutomation.executeShellCommand("svc wifi enable").close()
+ instrumentation.uiAutomation.executeShellCommand("svc data enable").close()
+ instrumentation.removeMonitor(monitor)
+ instrumentation.runOnMainSync {
+ extraObservers.forEach { it.disconnect(); it.release() }
+ observer.disconnect(); observer.release(); Calls.end(context, offer.callId)
+ Calls.drawerTheme = previousTheme
+ }
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/AndroidManifest.xml b/apps/web/tauri/callkit_plugin/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..ecf42c363e
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />
+ <uses-permission android:name="android.permission.RECORD_AUDIO" />
+ <uses-permission android:name="android.permission.CAMERA" />
+ <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
+ <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
+ <uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <uses-permission android:name="android.permission.VIBRATE" />
+ <application>
+ <service android:name="com.macro.call.TelecomService" android:exported="true" android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE">
+ <intent-filter><action android:name="android.telecom.ConnectionService" /></intent-filter>
+ </service>
+ <service android:name="com.macro.call.CallService" android:exported="false" android:foregroundServiceType="phoneCall|microphone|camera" />
+ <receiver android:name="com.macro.call.CallReceiver" android:exported="false" />
+ <activity android:name="com.macro.call.CallActivity" android:theme="@style/MacroCallOverlay" android:enableOnBackInvokedCallback="true" android:exported="false" android:launchMode="singleTask" android:showWhenLocked="true" android:turnScreenOn="true" android:supportsPictureInPicture="true" android:configChanges="orientation|screenSize|smallestScreenSize|screenLayout" />
+ </application>
+</manifest>
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt
new file mode 100644
index 0000000000..cc324f8961
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallActivity.kt
@@ -0,0 +1,302 @@
+package com.macro.call
+
+import android.Manifest
+import android.app.Activity
+import android.app.PictureInPictureParams
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import android.os.Bundle
+import android.telecom.CallAudioState
+import android.util.Rational
+import android.view.View
+import android.view.WindowManager
+import androidx.core.view.ViewCompat
+import androidx.core.view.WindowInsetsCompat
+import androidx.core.view.WindowInsetsControllerCompat
+import androidx.core.graphics.ColorUtils
+import android.graphics.Color
+import android.graphics.drawable.GradientDrawable
+import android.view.Gravity
+import android.view.MotionEvent
+import android.widget.*
+import io.livekit.android.renderer.SurfaceViewRenderer
+import io.livekit.android.room.track.Track
+import io.livekit.android.room.track.VideoTrack
+import kotlinx.coroutines.launch
+
+/** Native media UI also owns PiP: navigating/reloading the WebView never owns the room. */
+class CallActivity : Activity() {
+ private lateinit var layout: FrameLayout
+ private var backCallback: android.window.OnBackInvokedCallback? = null
+ private var pipRequested = false
+ private var primaryId: String? = null
+ private var swipeY = 0f
+ private var stripScroll = 0
+ private var participantStrip: HorizontalScrollView? = null
+ private var theme: CallTheme? = null
+ private data class ParticipantTile(val id: String, val name: String, val track: VideoTrack?, val local: Boolean = false)
+ private val renderers = mutableListOf<Pair<VideoTrack, SurfaceViewRenderer>>()
+ private var permissionAction: (() -> Unit)? = null
+ private var permissionCallId: String? = null
+ private var rendered: List<Any?>? = null
+ private val callback: () -> Unit = { render() }
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ if (Build.VERSION.SDK_INT >= 33) {
+ backCallback = android.window.OnBackInvokedCallback { dismissDrawer() }
+ onBackInvokedDispatcher.registerOnBackInvokedCallback(android.window.OnBackInvokedDispatcher.PRIORITY_DEFAULT, backCallback!!)
+ }
+ if (Build.VERSION.SDK_INT >= 27) { setShowWhenLocked(true); setTurnScreenOn(true) }
+ else window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
+ theme = Calls.drawerTheme ?: CallTheme.load(this)
+ window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(Color.TRANSPARENT))
+ layout = FrameLayout(this)
+ layout.addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
+ if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) { rendered = null; render() }
+ }
+ ViewCompat.setOnApplyWindowInsetsListener(layout) { view, insets ->
+ val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout())
+ view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
+ rendered = null
+ render()
+ insets
+ }
+ setContentView(layout)
+ Calls.changed = callback
+ intent.getStringExtra("answer")?.let { id ->
+ permission(Manifest.permission.RECORD_AUDIO, id) { Calls.answer(this, id) }
+ }
+ render()
+ }
+ override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
+ setIntent(intent)
+ intent.getStringExtra("answer")?.let { id -> permission(Manifest.permission.RECORD_AUDIO, id) { Calls.answer(this, id) } }
+ render()
+ }
+ private fun permission(name: String, callId: String? = null, action: () -> Unit) {
+ if (permissionAction != null) {
+ if (callId != permissionCallId) callId?.let { Calls.finishMicrophonePermission(it) }
+ return
+ }
+ if (checkSelfPermission(name) == PackageManager.PERMISSION_GRANTED) {
+ callId?.let { Calls.finishMicrophonePermission(it) }
+ action()
+ return
+ }
+ if (callId != null && !Calls.beginMicrophonePermission(callId)) return
+ permissionCallId = callId
+ permissionAction = action
+ try { requestPermissions(arrayOf(name), 4) }
+ catch (_: Exception) {
+ permissionCallId?.let { Calls.finishMicrophonePermission(it) }
+ permissionCallId = null; permissionAction = null
+ Calls.error = "Could not request permission. Try again."; render()
+ }
+ }
+ override fun onRequestPermissionsResult(code: Int, permissions: Array<out String>, grants: IntArray) {
+ super.onRequestPermissionsResult(code, permissions, grants)
+ if (code != 4 || permissionAction == null) return
+ val action = permissionAction
+ val callId = permissionCallId
+ permissionAction = null; permissionCallId = null
+ callId?.let { Calls.finishMicrophonePermission(it) }
+ if (grants.firstOrNull() == PackageManager.PERMISSION_GRANTED) action?.invoke()
+ else { Calls.error = "Permission denied. Enable it in Android settings to use this control."; render() }
+ }
+ private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
+ private fun background(color: Int, radius: Int = 16, border: Int? = null) = GradientDrawable().apply {
+ setColor(color); cornerRadius = dp(radius).toFloat()
+ border?.let { setStroke(dp(1), it) }
+ }
+ private fun label(value: String, size: Float = 14f, color: Int = theme!!.text) = TextView(this).apply {
+ text = value; textSize = size; setTextColor(color); maxLines = 1; gravity = Gravity.CENTER_VERTICAL
+ ellipsize = android.text.TextUtils.TruncateAt.END
+ }
+ private fun actionButton(value: String, color: Int, action: () -> Unit) = TextView(this).apply {
+ text = value; textSize = 14f; gravity = Gravity.CENTER; setTextColor(Color.WHITE)
+ background = background(color, 12); contentDescription = value
+ setPadding(dp(16), 0, dp(16), 0); minimumHeight = dp(48)
+ isClickable = true; isFocusable = true; setOnClickListener { action() }
+ }
+ private fun icon(kind: String, name: String, active: Boolean = false, off: Boolean = false, action: () -> Unit) = ImageButton(this).apply {
+ setImageDrawable(CallControlIcon(kind, theme!!.text, off)); scaleType = ImageView.ScaleType.CENTER_INSIDE
+ setPadding(dp(14), dp(14), dp(14), dp(14)); background = background(if (active) theme!!.edgeMuted else theme!!.drawer, 12, theme!!.edge)
+ tag = "call-control-$kind"
+ contentDescription = name; isSelected = active; setOnClickListener { action() }
+ }
+ private fun detach() { renderers.forEach { (track, renderer) -> track.removeRenderer(renderer); renderer.release() }; renderers.clear() }
+ private fun tile(participant: ParticipantTile?, large: Boolean): FrameLayout = FrameLayout(this).apply {
+ background = background(theme!!.tile, 16); clipToOutline = true
+ tag = if (large) "call-primary" else "call-participant"
+ val name = participant?.name ?: "Waiting for others"
+ contentDescription = name
+ participant?.track?.let { track ->
+ val renderer = SurfaceViewRenderer(this@CallActivity)
+ renderer.setZOrderMediaOverlay(true)
+ renderer.setMirror(participant.local)
+ Calls.room?.initVideoRenderer(renderer); track.addRenderer(renderer)
+ renderers.add(track to renderer)
+ addView(renderer, FrameLayout.LayoutParams(-1, -1))
+ } ?: run {
+ val initials = participant?.name?.split(' ')?.filter { it.isNotBlank() }?.take(2)?.joinToString("") { it.take(1).uppercase() } ?: ""
+ val avatar = label(initials, if (large) 32f else 18f).apply {
+ gravity = Gravity.CENTER; background = background(theme!!.edgeMuted, 100)
+ }
+ val size = dp(if (large) 88 else 40)
+ addView(avatar, FrameLayout.LayoutParams(size, size, Gravity.CENTER))
+ }
+ addView(label(name, if (large) 14f else 11f).apply {
+ gravity = Gravity.START or Gravity.CENTER_VERTICAL; setPadding(dp(8), dp(5), dp(8), dp(5))
+ background = background(theme!!.edgeMuted, 8)
+ }, FrameLayout.LayoutParams(-2, -2, Gravity.BOTTOM or Gravity.START).apply { bottomMargin = dp(10); leftMargin = dp(10); rightMargin = dp(10) })
+ if (participant != null && !large) setOnClickListener { primaryId = participant.id; stripScroll = participantStrip?.scrollX ?: 0; rendered = null; render() }
+ if (participant?.local == true && Calls.video && large) addView(icon("switch", "Switch camera") { Calls.switchCamera() },
+ FrameLayout.LayoutParams(dp(48), dp(48), Gravity.TOP or Gravity.END).apply { topMargin = dp(8); rightMargin = dp(8) })
+ }
+ private fun render() {
+ val call = Calls.offer ?: run { finish(); return }
+ theme = Calls.drawerTheme ?: theme ?: CallTheme.load(this)
+ val light = ColorUtils.calculateLuminance(theme!!.drawer) > 0.5
+ WindowInsetsControllerCompat(window, layout).apply {
+ isAppearanceLightNavigationBars = light; isAppearanceLightStatusBars = light
+ }
+ val media = Calls.room
+ fun video(participant: io.livekit.android.room.participant.Participant): VideoTrack? {
+ val publication = participant.getTrackPublication(Track.Source.CAMERA)
+ return publication?.takeUnless { it.muted }?.track as? VideoTrack
+ }
+ val remote = media?.remoteParticipants?.values?.map { participant ->
+ val id = participant.identity?.value ?: participant.sid.value
+ ParticipantTile(id, Calls.displayNames[id] ?: participant.name?.takeIf { it.isNotBlank() } ?: id.substringAfter('|'), video(participant))
+ }.orEmpty()
+ val local = media?.localParticipant?.let { ParticipantTile(it.identity?.value ?: "local", "You", if (Calls.video) video(it) else null, true) }
+ val participants = remote + listOfNotNull(local)
+ val primary = participants.firstOrNull { it.id == primaryId } ?: remote.firstOrNull()
+ primaryId = primary?.id
+ val nextRender = listOf(call.callId, Calls.title, Calls.state, Calls.error, Calls.muted, Calls.video, Calls.audioRoute,
+ isInPictureInPictureMode, participants, primaryId, theme, layout.width, layout.height, layout.paddingBottom)
+ if (rendered == nextRender) return
+ rendered = nextRender
+ stripScroll = participantStrip?.scrollX ?: stripScroll
+ participantStrip = null
+ detach(); layout.removeAllViews()
+ layout.setBackgroundColor(if (isInPictureInPictureMode) theme!!.tile else theme!!.scrim)
+ if (isInPictureInPictureMode) {
+ layout.addView(tile(primary ?: local, true), FrameLayout.LayoutParams(-1, -1))
+ return
+ }
+ layout.setOnClickListener { dismissDrawer() }
+ val drawer = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL; background = background(theme!!.drawer, 24)
+ setPadding(dp(16), dp(10), dp(16), dp(16)); isClickable = true
+ tag = "call-drawer"
+ }
+ val available = layout.height - layout.paddingTop - layout.paddingBottom
+ layout.addView(drawer, FrameLayout.LayoutParams(-1, (available * 0.92f).toInt().coerceAtLeast(1), Gravity.BOTTOM))
+ val handleArea = FrameLayout(this).apply {
+ addView(View(this@CallActivity).apply { background = background(theme!!.edge, 3) },
+ FrameLayout.LayoutParams(dp(36), dp(4), Gravity.CENTER))
+ tag = "call-drawer-handle"
+ contentDescription = "Dismiss call drawer"; isClickable = true; setOnClickListener { dismissDrawer() }
+ setOnTouchListener { _, event ->
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN -> { swipeY = event.rawY; true }
+ MotionEvent.ACTION_UP -> { if (event.rawY - swipeY > dp(40)) dismissDrawer() else performClick(); true }
+ else -> true
+ }
+ }
+ }
+ drawer.addView(handleArea, LinearLayout.LayoutParams(-1, dp(24)))
+ val header = LinearLayout(this).apply { gravity = Gravity.CENTER_VERTICAL }
+ header.addView(label(Calls.title ?: call.title, 18f), LinearLayout.LayoutParams(0, dp(48), 1f))
+ header.addView(actionButton(if (media == null) "Decline" else "Leave", theme!!.failure) { Calls.end(this, call.callId) }, LinearLayout.LayoutParams(-2, dp(48)))
+ drawer.addView(header, LinearLayout.LayoutParams(-1, dp(56)))
+ if (Calls.error != null) drawer.addView(label(Calls.error!!, 12f, theme!!.muted).apply { maxLines = 2 }, LinearLayout.LayoutParams(-1, -2))
+ drawer.addView(tile(primary, true), LinearLayout.LayoutParams(-1, 0, 1f).apply { topMargin = dp(8) })
+ val strip = HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; tag = "call-participant-strip" }
+ val stripContent = LinearLayout(this)
+ participants.filter { it.id != primary?.id }.forEach { participant ->
+ stripContent.addView(tile(participant, false), LinearLayout.LayoutParams(dp(112), -1).apply { rightMargin = dp(10) })
+ }
+ strip.addView(stripContent, FrameLayout.LayoutParams(-2, -1))
+ participantStrip = strip
+ drawer.addView(strip, LinearLayout.LayoutParams(-1, (available * 0.14f).toInt().coerceIn(dp(56), dp(96))).apply { topMargin = dp(12); bottomMargin = dp(16) })
+ strip.post { if (participantStrip === strip) strip.scrollTo(stripScroll, 0) }
+ val controls = LinearLayout(this).apply { gravity = Gravity.CENTER; tag = "call-controls" }
+ if (media == null) controls.addView(actionButton("Answer", theme!!.success) {
+ permission(Manifest.permission.RECORD_AUDIO, call.callId) { Calls.answer(this, call.callId) }
+ }, LinearLayout.LayoutParams(dp(160), dp(52)))
+ else {
+ fun control(button: ImageButton, name: String) {
+ val column = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER }
+ column.addView(button, LinearLayout.LayoutParams(dp(56), dp(52)))
+ column.addView(label(name, 11f, theme!!.muted).apply { gravity = Gravity.START or Gravity.CENTER_VERTICAL }, LinearLayout.LayoutParams(dp(56), dp(24)))
+ controls.addView(column, LinearLayout.LayoutParams(dp(88), -2))
+ }
+ val speaker = icon("speaker", "Speaker mode", Calls.audioRoute == "Speakerphone") {
+ Calls.route(if (Calls.audioRoute == "Speakerphone") CallAudioState.ROUTE_EARPIECE else CallAudioState.ROUTE_SPEAKER)
+ }
+ speaker.setOnLongClickListener { audioRoutes(); true }
+ control(speaker, "Speaker")
+ control(icon("mic", if (Calls.muted) "Unmute" else "Mute", Calls.muted, Calls.muted) {
+ Calls.scope.launch { runCatching { Calls.microphone(Calls.muted) }.onSuccess { Calls.error = null; render() }.onFailure { Calls.error = "Could not change microphone"; render() } }
+ }, if (Calls.muted) "Unmute" else "Mute")
+ control(icon("video", if (Calls.video) "Video off" else "Video on", Calls.video, !Calls.video) {
+ val cameraRoom = media ?: return@icon
+ val enabled = !Calls.video
+ permission(Manifest.permission.CAMERA) { Calls.scope.launch { runCatching { Calls.camera(this@CallActivity, enabled, expectedRoom = cameraRoom) }.onSuccess { Calls.error = null; render() }.onFailure { Calls.error = "Could not change camera"; render() } } }
+ }, "Video")
+ }
+ drawer.addView(controls, LinearLayout.LayoutParams(-1, -2))
+ }
+ private fun audioRoutes() {
+ val routes = listOf("Earpiece" to CallAudioState.ROUTE_EARPIECE, "Speaker" to CallAudioState.ROUTE_SPEAKER,
+ "Headset" to CallAudioState.ROUTE_WIRED_HEADSET, "Bluetooth" to CallAudioState.ROUTE_BLUETOOTH)
+ android.app.AlertDialog.Builder(this).setTitle("Audio output").setItems(routes.map { it.first }.toTypedArray()) { _, index ->
+ val route = routes[index].second
+ if (route == CallAudioState.ROUTE_BLUETOOTH && Build.VERSION.SDK_INT >= 31) permission(Manifest.permission.BLUETOOTH_CONNECT) { Calls.route(route) }
+ else Calls.route(route)
+ }.show()
+ }
+ private fun dismissDrawer() {
+ if (!pip()) {
+ packageManager.getLaunchIntentForPackage(packageName)?.let { startActivity(it) }
+ finish()
+ }
+ }
+ @Deprecated("Deprecated in Android") override fun onBackPressed() { dismissDrawer() }
+ private fun pip(): Boolean {
+ if (Calls.room == null || !packageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) return false
+ pipRequested = true
+ return runCatching { enterPictureInPictureMode(PictureInPictureParams.Builder().setAspectRatio(Rational(16, 9)).build()) }
+ .getOrDefault(false).also { if (!it) pipRequested = false }
+ }
+ override fun onUserLeaveHint() { pip() }
+ override fun onPictureInPictureModeChanged(inPip: Boolean, config: android.content.res.Configuration) {
+ super.onPictureInPictureModeChanged(inPip, config); pipRequested = inPip; render()
+ }
+ override fun onStop() {
+ super.onStop()
+ // Back/swipe transitions can stop before the PiP mode callback arrives.
+ // Closing PiP still releases capture through finish/onDestroy.
+ if (isFinishing || (!pipRequested && !isInPictureInPictureMode)) stopCameraIfOwned()
+ }
+ private fun stopCameraIfOwned() {
+ if (isChangingConfigurations || Calls.changed !== callback || !Calls.video) return
+ val media = Calls.room ?: return
+ Calls.scope.launch {
+ if (Calls.room === media) runCatching { Calls.camera(this@CallActivity, false, media) }
+ }
+ }
+ override fun onDestroy() {
+ if (Build.VERSION.SDK_INT >= 33) backCallback?.let { onBackInvokedDispatcher.unregisterOnBackInvokedCallback(it) }
+ backCallback = null
+ permissionCallId?.let { Calls.finishMicrophonePermission(it) }
+ permissionCallId = null; permissionAction = null
+ stopCameraIfOwned()
+ if (Calls.changed === callback) Calls.changed = null
+ detach(); super.onDestroy()
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.kt
new file mode 100644
index 0000000000..0d1534143f
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallControlIcon.kt
@@ -0,0 +1,41 @@
+package com.macro.call
+
+import android.graphics.*
+import android.graphics.drawable.Drawable
+
+/** Small monochrome call controls, independent of the platform's button theme. */
+internal class CallControlIcon(private val kind: String, color: Int, private val off: Boolean = false) : Drawable() {
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeWidth = 1.8f; strokeCap = Paint.Cap.ROUND; strokeJoin = Paint.Join.ROUND }
+ override fun draw(canvas: Canvas) {
+ canvas.save()
+ canvas.translate(bounds.left.toFloat(), bounds.top.toFloat())
+ canvas.scale(bounds.width() / 24f, bounds.height() / 24f)
+ when (kind) {
+ "speaker" -> {
+ canvas.drawPath(Path().apply { moveTo(3f,9f); lineTo(7f,9f); lineTo(12f,5f); lineTo(12f,19f); lineTo(7f,15f); lineTo(3f,15f); close() }, paint)
+ canvas.drawArc(11f,7f,19f,17f,-60f,120f,false,paint)
+ canvas.drawArc(9f,3f,23f,21f,-50f,100f,false,paint)
+ }
+ "mic" -> {
+ canvas.drawRoundRect(9f,3f,15f,14f,3f,3f,paint)
+ canvas.drawArc(6f,7f,18f,18f,0f,180f,false,paint)
+ canvas.drawLine(12f,18f,12f,21f,paint); canvas.drawLine(9f,21f,15f,21f,paint)
+ }
+ "video" -> {
+ canvas.drawRoundRect(3f,6f,16f,18f,2f,2f,paint)
+ canvas.drawPath(Path().apply { moveTo(16f,10f); lineTo(21f,7f); lineTo(21f,17f); lineTo(16f,14f) },paint)
+ }
+ "switch" -> {
+ canvas.drawArc(4f,4f,20f,20f,30f,140f,false,paint)
+ canvas.drawArc(4f,4f,20f,20f,210f,140f,false,paint)
+ canvas.drawLine(4f,12f,4f,17f,paint); canvas.drawLine(4f,17f,9f,17f,paint)
+ canvas.drawLine(20f,12f,20f,7f,paint); canvas.drawLine(20f,7f,15f,7f,paint)
+ }
+ }
+ if (off) canvas.drawLine(3f,3f,21f,21f,paint)
+ canvas.restore()
+ }
+ override fun setAlpha(alpha: Int) { paint.alpha = alpha; invalidateSelf() }
+ override fun setColorFilter(filter: ColorFilter?) { paint.colorFilter = filter; invalidateSelf() }
+ @Deprecated("Deprecated in Android") override fun getOpacity(): Int = PixelFormat.TRANSLUCENT
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt
new file mode 100644
index 0000000000..3c35326017
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallOffer.kt
@@ -0,0 +1,32 @@
+package com.macro.call
+
+import org.json.JSONObject
+import java.net.URI
+import java.util.UUID
+
+/** Credentials stay in memory; only resolved call ids are persisted. */
+internal data class CallOffer(
+ val callId: String,
+ val channelId: String,
+ val title: String,
+ val serverUrl: String,
+ val token: String,
+ val ringUrl: String? = null,
+ val sentTime: Long = System.currentTimeMillis(),
+) {
+ companion object {
+ fun fresh(sentTime: Long, now: Long): Boolean = RingPolicy.fresh(sentTime, now)
+ fun parse(json: String, sentTime: Long): CallOffer {
+ val data = JSONObject(json)
+ val id = UUID.fromString(data.getString("callId")).toString()
+ val server = data.getString("livekitServerUrl")
+ require(URI(server).let { it.scheme == "wss" && it.host != null && it.userInfo == null })
+ val ring = data.getString("ringStatusUrl")
+ require(URI(ring).let { it.scheme == "https" && (it.host == "macro.com" || it.host?.endsWith(".macro.com") == true) && it.userInfo == null })
+ return CallOffer(id, data.getString("channelId"), data.optString("channelName", "Macro call"), server,
+ data.getString("livekitToken"), ring, sentTime).also {
+ require(it.channelId.isNotBlank() && it.token.isNotBlank())
+ }
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt
new file mode 100644
index 0000000000..ba9f0ed5bb
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallPlugin.kt
@@ -0,0 +1,149 @@
+package com.macro.call
+
+import android.Manifest
+import android.app.Activity
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.appcompat.app.AppCompatActivity
+import app.tauri.annotation.*
+import app.tauri.plugin.*
+import kotlinx.coroutines.launch
+import java.net.URI
+import java.util.UUID
+
+@InvokeArg
+internal class WatchArgs { lateinit var channel: Channel }
+@InvokeArg
+internal class OutgoingArgs {
+ lateinit var callId: String
+ lateinit var channelId: String
+ var channelTitle: String? = null
+ lateinit var serverUrl: String
+ lateinit var token: String
+ var joinLease: String? = null
+}
+@InvokeArg
+internal class PrepareJoinArgs { lateinit var channelId: String }
+@InvokeArg
+internal class AbortJoinArgs { lateinit var lease: String }
+@InvokeArg
+internal class EnabledArgs { var enabled = false }
+@InvokeArg
+internal class TitleArgs { var channelTitle: String? = null }
+@InvokeArg
+internal class NameArgs { lateinit var identity: String; var displayName: String? = null }
+@InvokeArg
+internal class ThemeArgs { var theme: Map<String, Map<String, Double>> = emptyMap() }
+@InvokeArg
+internal class ModeArgs { var mode = "hidden" }
+
+@TauriPlugin(permissions = [Permission(strings = [Manifest.permission.RECORD_AUDIO], alias = "microphone"), Permission(strings = [Manifest.permission.CAMERA], alias = "camera")])
+class CallPlugin(private val activity: Activity) : Plugin(activity) {
+ private var preparePermissionCallId: String? = null
+ private fun finishPreparePermission() {
+ preparePermissionCallId?.let { Calls.finishMicrophonePermission(it) }
+ preparePermissionCallId = null
+ }
+ private fun watch(invoke: Invoke, key: String) { Calls.watch(key, invoke.parseArgs(WatchArgs::class.java).channel); invoke.resolve() }
+ @Command fun watchCallAnswered(invoke: Invoke) { watch(invoke, "answered") }
+ @Command fun watchCallEnded(invoke: Invoke) { watch(invoke, "ended") }
+ @Command fun watchConnectionState(invoke: Invoke) { watch(invoke, "connection"); Calls.publish() }
+ @Command fun watchParticipantIdentities(invoke: Invoke) { watch(invoke, "participants"); Calls.publish() }
+ @Command fun watchDrawerOpened(invoke: Invoke) { watch(invoke, "drawer") }
+ @Command fun getActiveCallState(invoke: Invoke) { invoke.resolve(JSObject().apply { put("state", Calls.snapshot() ?: org.json.JSONObject.NULL) }) }
+ @Command fun getPendingAnsweredCall(invoke: Invoke) {
+ val channel = Calls.pendingAnswered; Calls.pendingAnswered = null
+ invoke.resolve(JSObject().apply { put("channelId", channel ?: org.json.JSONObject.NULL); put("nativeMedia", true) })
+ }
+ @Command fun prepareJoin(invoke: Invoke) {
+ if (Build.VERSION.SDK_INT < 26) { invoke.reject("Native calls require Android 8 or newer"); return }
+ try {
+ val args = invoke.parseArgs(PrepareJoinArgs::class.java)
+ require(args.channelId.isNotBlank())
+ if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
+ preparePermissionCallId = Calls.offer?.takeIf { it.channelId == args.channelId && Calls.beginMicrophonePermission(it.callId) }?.callId
+ requestPermissionForAlias("microphone", invoke, "prepareJoinPermission"); return
+ }
+ invoke.resolve(JSObject().apply { put("lease", Calls.prepareJoin(activity, args.channelId)) })
+ } catch (_: Exception) { finishPreparePermission(); invoke.reject("Unable to prepare native call join") }
+ }
+ @PermissionCallback fun prepareJoinPermission(invoke: Invoke) {
+ finishPreparePermission()
+ if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) prepareJoin(invoke)
+ else invoke.reject("Microphone permission is required for calls")
+ }
+ @Command fun abortJoin(invoke: Invoke) {
+ Calls.abortJoin(activity, invoke.parseArgs(AbortJoinArgs::class.java).lease); invoke.resolve()
+ }
+ @Command fun startOutgoingCall(invoke: Invoke) {
+ if (Build.VERSION.SDK_INT < 26) { invoke.reject("Native calls require Android 8 or newer"); return }
+ try {
+ val args = invoke.parseArgs(OutgoingArgs::class.java)
+ if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
+ // Leased joins already requested permission before membership was created.
+ // A revoked grant must fail immediately rather than wait under the deadline.
+ if (args.joinLease != null) invoke.reject("Microphone permission is required for calls")
+ else requestPermissionForAlias("microphone", invoke, "outgoingPermission")
+ return
+ }
+ require(URI(args.serverUrl).let { it.scheme == "wss" && it.host != null && it.userInfo == null })
+ require(args.channelId.isNotBlank() && args.token.isNotBlank())
+ Calls.outgoing(activity, CallOffer(UUID.fromString(args.callId).toString(), args.channelId,
+ args.channelTitle ?: "Macro call", args.serverUrl, args.token), args.joinLease)
+ invoke.resolve()
+ } catch (_: Exception) { invoke.reject("Unable to start native call") }
+ }
+ @PermissionCallback fun outgoingPermission(invoke: Invoke) {
+ if (activity.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED) startOutgoingCall(invoke)
+ else invoke.reject("Microphone permission is required for calls")
+ }
+ @Command fun endActiveCall(invoke: Invoke) { Calls.end(activity); invoke.resolve() }
+ @Command fun setVideoEnabled(invoke: Invoke) {
+ val enabled = invoke.parseArgs(EnabledArgs::class.java).enabled
+ if (enabled && activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
+ requestPermissionForAlias("camera", invoke, "cameraPermission"); return
+ }
+ Calls.scope.launch {
+ try { Calls.camera(activity, enabled); invoke.resolve() }
+ catch (_: Exception) { invoke.reject("Unable to change camera") }
+ }
+ }
+ @PermissionCallback fun cameraPermission(invoke: Invoke) {
+ if (activity.checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) setVideoEnabled(invoke)
+ else invoke.reject("Camera permission is required for video")
+ }
+ @Command fun setVideoOverlayMode(invoke: Invoke) {
+ val mode = invoke.parseArgs(ModeArgs::class.java).mode
+ if (mode !in listOf("hidden", "expanded", "minimized")) { invoke.reject("Invalid call surface mode"); return }
+ Calls.overlay = mode
+ if (mode != "hidden" && Calls.offer != null) {
+ activity.startActivity(Intent(activity, CallActivity::class.java))
+ Calls.offer?.let { Calls.emit("drawer", JSObject().apply { put("channelId", it.channelId) }) }
+ }
+ Calls.publish(); invoke.resolve()
+ }
+ @Command fun switchCamera(invoke: Invoke) { Calls.switchCamera(); invoke.resolve() }
+ @Command fun setCallDrawerTheme(invoke: Invoke) {
+ try {
+ val json = org.json.JSONObject(invoke.parseArgs(ThemeArgs::class.java).theme)
+ Calls.drawerTheme = CallTheme.parse(json)
+ activity.getSharedPreferences("macro_call_theme", android.content.Context.MODE_PRIVATE)
+ .edit().putString("theme", json.toString()).apply()
+ Calls.publish(); invoke.resolve()
+ } catch (_: Exception) { invoke.reject("Invalid call drawer theme") }
+ }
+ @Command fun setCallDrawerChannelTitle(invoke: Invoke) {
+ Calls.title = invoke.parseArgs(TitleArgs::class.java).channelTitle
+ Calls.title?.let { Calls.connection?.setCallerDisplayName(it, android.telecom.TelecomManager.PRESENTATION_ALLOWED) }
+ Calls.publish(); invoke.resolve()
+ }
+ @Command fun setParticipantDisplayName(invoke: Invoke) {
+ val args = invoke.parseArgs(NameArgs::class.java)
+ val name = args.displayName?.trim()?.takeIf { it.isNotEmpty() }
+ if (name == null) Calls.displayNames.remove(args.identity) else Calls.displayNames[args.identity] = name
+ Calls.publish(); invoke.resolve()
+ }
+ @Command fun getVoipToken(invoke: Invoke) { invoke.resolve(JSObject().apply { put("token", org.json.JSONObject.NULL) }) }
+ override fun onDestroy(activity: AppCompatActivity) { finishPreparePermission(); Calls.abortPendingJoin(activity); Calls.unwatch() }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt
new file mode 100644
index 0000000000..c6548fceb6
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallReceiver.kt
@@ -0,0 +1,27 @@
+package com.macro.call
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import kotlinx.coroutines.launch
+
+/** Explicit, unexported receiver: external apps cannot inject call credentials/actions. */
+class CallReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context, intent: Intent) {
+ val pending = goAsync()
+ Calls.scope.launch {
+ try {
+ when (intent.action) {
+ "com.macro.call.PUSH" -> {
+ val data = mapOf("recipientId" to (intent.getStringExtra("recipientId") ?: ""),
+ "payload" to (intent.getStringExtra("payload") ?: ""))
+ Calls.receive(context.applicationContext, data, intent.getLongExtra("sentTime", 0))
+ }
+ "com.macro.call.RESET" -> Calls.resetRecipient(context.applicationContext, intent.getStringExtra("previousRecipient"))
+ "answer" -> intent.getStringExtra("callId")?.let { Calls.answer(context.applicationContext, it) }
+ "end" -> intent.getStringExtra("callId")?.let { Calls.end(context.applicationContext, it) }
+ }
+ } finally { pending.finish() }
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt
new file mode 100644
index 0000000000..aad1b86581
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallService.kt
@@ -0,0 +1,136 @@
+package com.macro.call
+
+import android.app.*
+import android.content.Context
+import android.content.Intent
+import android.content.pm.ServiceInfo
+import android.os.Build
+import android.os.IBinder
+import androidx.core.app.NotificationCompat
+import androidx.core.app.Person
+import androidx.core.content.ContextCompat
+import kotlinx.coroutines.launch
+
+/** Keeps the native room alive without requiring a running WebView. */
+class CallService : Service() {
+ companion object {
+ const val NOTIFICATION_ID = 7404
+ private const val CHANNEL = "macro_calls"
+ internal var instance: CallService? = null
+ private set
+ fun start(ctx: Context, media: Boolean = false, camera: Boolean = false) {
+ instance?.let { it.updateForeground(media, camera); return }
+ ContextCompat.startForegroundService(ctx, Intent(ctx, CallService::class.java)
+ .putExtra("media", media).putExtra("camera", camera))
+ }
+ fun stop() {
+ // A queued start must promote before stopping, even if the call ended.
+ val service = instance ?: return
+ instance = null
+ service.stopForeground(STOP_FOREGROUND_REMOVE)
+ service.stopSelf()
+ }
+ fun action(ctx: Context, name: String, id: String): PendingIntent = PendingIntent.getBroadcast(
+ ctx, name.hashCode(), Intent(ctx, CallReceiver::class.java).setAction(name).putExtra("callId", id),
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ fun screen(ctx: Context): PendingIntent = PendingIntent.getActivity(ctx, 0,
+ Intent(ctx, CallActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ }
+ private var foregroundTypes = 0
+ private var callId: String? = null
+ private var mediaSession: android.media.session.MediaSession? = null
+ override fun onCreate() {
+ super.onCreate()
+ // Satisfy startForegroundService before consulting mutable call state.
+ try { updateForeground(); instance = this }
+ catch (_: Exception) { Calls.end(this); stopSelf(); return }
+ mediaSession = android.media.session.MediaSession(this, "Macro call").apply {
+ setCallback(object : android.media.session.MediaSession.Callback() {
+ override fun onStop() { callId?.let { Calls.end(this@CallService, it) } }
+ override fun onPlay() { Calls.scope.launch { runCatching { Calls.microphone(true) } } }
+ override fun onPause() { Calls.scope.launch { runCatching { Calls.microphone(false) } } }
+ override fun onMediaButtonEvent(intent: Intent): Boolean {
+ val event = intent.getParcelableExtra<android.view.KeyEvent>(Intent.EXTRA_KEY_EVENT) ?: return false
+ val supported = listOf(android.view.KeyEvent.KEYCODE_HEADSETHOOK, android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
+ android.view.KeyEvent.KEYCODE_MEDIA_PLAY, android.view.KeyEvent.KEYCODE_MEDIA_PAUSE, android.view.KeyEvent.KEYCODE_MEDIA_STOP)
+ if (event.keyCode !in supported) return false
+ if (event.action != android.view.KeyEvent.ACTION_UP) return true
+ val id = callId ?: return true
+ when (event.keyCode) {
+ android.view.KeyEvent.KEYCODE_MEDIA_STOP -> Calls.end(this@CallService, id)
+ android.view.KeyEvent.KEYCODE_MEDIA_PAUSE -> Calls.scope.launch { runCatching { Calls.microphone(false) } }
+ else -> if (Calls.room == null) Calls.answer(this@CallService, id)
+ else Calls.scope.launch { runCatching { Calls.microphone(event.keyCode == android.view.KeyEvent.KEYCODE_MEDIA_PLAY || Calls.muted) } }
+ }
+ return true
+ }
+ })
+ setPlaybackState(android.media.session.PlaybackState.Builder()
+ .setActions(android.media.session.PlaybackState.ACTION_PLAY or android.media.session.PlaybackState.ACTION_PAUSE or android.media.session.PlaybackState.ACTION_STOP)
+ .setState(android.media.session.PlaybackState.STATE_PLAYING, 0, 1f).build())
+ isActive = true
+ }
+ }
+ override fun onBind(intent: Intent?): IBinder? = null
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = handleStart(intent)
+ internal fun handleStart(intent: Intent?, promote: (Notification, Int) -> Unit = ::promoteForeground): Int {
+ // Android can redeliver a start to this object after stopSelf was requested.
+ instance = this
+ val call = Calls.offer ?: run {
+ updateForeground(promote = promote)
+ stop(); return START_NOT_STICKY
+ }
+ callId = call.callId
+ try {
+ updateForeground(Calls.room != null || intent?.getBooleanExtra("media", false) == true,
+ intent?.getBooleanExtra("camera", false) == true, promote)
+ } catch (_: Exception) {
+ if (foregroundTypes and ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE != 0 && Calls.room != null) {
+ Calls.error = "Could not update call capture. Please try again."
+ val media = Calls.room
+ Calls.scope.launch { runCatching { Calls.camera(this@CallService, false, media) }; Calls.publish() }
+ } else { Calls.end(this, call.callId); stop() }
+ }
+ return START_NOT_STICKY
+ }
+ private fun promoteForeground(notification: Notification, types: Int) {
+ if (Build.VERSION.SDK_INT >= 29) startForeground(NOTIFICATION_ID, notification, types)
+ else startForeground(NOTIFICATION_ID, notification)
+ }
+ private fun updateForeground(media: Boolean = false, camera: Boolean = false,
+ promote: (Notification, Int) -> Unit = ::promoteForeground) {
+ val call = Calls.offer
+ val manager = getSystemService(NotificationManager::class.java)
+ manager.createNotificationChannel(NotificationChannel(CHANNEL, "Calls", NotificationManager.IMPORTANCE_HIGH).apply {
+ setSound(android.media.RingtoneManager.getDefaultUri(android.media.RingtoneManager.TYPE_RINGTONE),
+ android.media.AudioAttributes.Builder().setUsage(android.media.AudioAttributes.USAGE_NOTIFICATION_RINGTONE).build())
+ enableVibration(true)
+ })
+ val ringing = call != null && Calls.room == null
+ val builder = NotificationCompat.Builder(this, CHANNEL)
+ .setSmallIcon(android.R.drawable.sym_call_incoming).setContentTitle(Calls.title ?: call?.title ?: "Macro call")
+ .setCategory(NotificationCompat.CATEGORY_CALL).setOngoing(true).setOnlyAlertOnce(true)
+ .setSilent(!ringing)
+ .setContentIntent(screen(this)).setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
+ .setFullScreenIntent(if (ringing) screen(this) else null, ringing)
+ if (call != null) {
+ val person = Person.Builder().setName((Calls.title ?: call.title).ifBlank { "Macro call" }).setImportant(true).build()
+ builder.setStyle(if (ringing) NotificationCompat.CallStyle.forIncomingCall(person,
+ action(this, "end", call.callId), action(this, "answer", call.callId))
+ else NotificationCompat.CallStyle.forOngoingCall(person, action(this, "end", call.callId)))
+ }
+ val notification = builder.build().apply { if (ringing) this.flags = this.flags or Notification.FLAG_INSISTENT }
+ var types = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
+ if (media || Calls.room != null) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
+ if (camera || Calls.video) types = types or ServiceInfo.FOREGROUND_SERVICE_TYPE_CAMERA
+ promote(notification, types)
+ foregroundTypes = types
+ }
+ override fun onDestroy() {
+ if (instance === this) instance = null
+ mediaSession?.release(); mediaSession = null
+ callId?.let { Calls.end(this, it) }
+ super.onDestroy()
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTheme.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTheme.kt
new file mode 100644
index 0000000000..264ec33169
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/CallTheme.kt
@@ -0,0 +1,31 @@
+package com.macro.call
+
+import android.content.Context
+import android.content.res.Configuration
+import android.graphics.Color
+import org.json.JSONObject
+
+/** The same resolved semantic colors used by the iOS drawer, retained for cold rings. */
+internal data class CallTheme(val drawer: Int, val text: Int, val tile: Int, val scrim: Int,
+ val edgeMuted: Int, val edge: Int, val muted: Int, val failure: Int, val success: Int) {
+ companion object {
+ fun load(context: Context): CallTheme {
+ val dark = context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
+ val fallback = if (dark) CallTheme(Color.rgb(16,16,16), Color.WHITE, Color.rgb(25,25,25), 0x99000000.toInt(),
+ Color.rgb(46,46,46), Color.rgb(80,80,80), Color.LTGRAY, Color.rgb(235,65,65), Color.rgb(30,175,115))
+ else CallTheme(Color.WHITE, Color.rgb(25,25,25), Color.rgb(245,245,245), 0x66000000,
+ Color.rgb(230,230,230), Color.rgb(205,205,205), Color.DKGRAY, Color.rgb(225,55,55), Color.rgb(20,145,95))
+ return runCatching { parse(JSONObject(context.getSharedPreferences("macro_call_theme", Context.MODE_PRIVATE)
+ .getString("theme", null) ?: return fallback)) }.getOrDefault(fallback)
+ }
+ fun parse(json: JSONObject): CallTheme {
+ fun color(key: String): Int {
+ val rgba = json.getJSONObject(key)
+ fun channel(name: String) = (rgba.getDouble(name).also { require(it.isFinite() && it in 0.0..1.0) } * 255).toInt()
+ return Color.argb(channel("alpha"), channel("red"), channel("green"), channel("blue"))
+ }
+ return CallTheme(color("drawerBackground"), color("text"), color("messageBackground"), color("overlayBackground"),
+ color("edgeMuted"), color("edge"), color("inkMuted"), color("failure"), color("success"))
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt
new file mode 100644
index 0000000000..2fff41c04e
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/Calls.kt
@@ -0,0 +1,403 @@
+package com.macro.call
+
+import android.Manifest
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.media.AudioManager
+import android.net.Uri
+import android.os.Bundle
+import android.os.SystemClock
+import android.telecom.*
+import androidx.core.content.ContextCompat
+import app.tauri.plugin.Channel
+import app.tauri.plugin.JSObject
+import io.livekit.android.LiveKit
+import io.livekit.android.events.RoomEvent
+import io.livekit.android.events.collect
+import io.livekit.android.room.Room
+import io.livekit.android.room.track.LocalVideoTrack
+import io.livekit.android.room.track.RemoteAudioTrack
+import io.livekit.android.room.track.Track
+import kotlinx.coroutines.*
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+import org.json.JSONArray
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+
+/** Main-thread owner shared by Telecom, FCM, service, Activity and the WebView. */
+internal object Calls {
+ val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
+ var offer: CallOffer? = null
+ private set
+ var connection: Connection? = null
+ var room: Room? = null
+ private set
+ var state = "disconnected"
+ private set
+ var muted = false
+ private set
+ var video = false
+ private set
+ var error: String? = null
+ var overlay = "hidden"
+ var pendingAnswered: String? = null
+ var changed: (() -> Unit)? = null
+ private var session: Job? = null
+ private var poller: Job? = null
+ private var held = false
+ private var answering = false
+ private var accepted = false
+ private var microphonePermissionStartedAt: Long? = null
+ private var microphonePermissionPausedMs = 0L
+ private data class JoinLease(val id: String, val channelId: String, val recipient: String?, var callId: String? = null)
+ private var joinLease: JoinLease? = null
+ private var leaseTimeout: Job? = null
+ private var focusLost = false
+ private var telecomMuted = false
+ private var telecomFocusLost = false
+ private var desiredAudioType: String? = null
+ private val audioMutex = Mutex()
+ private val videoMutex = Mutex()
+ var recipient: String? = null
+ private set
+ var drawerTheme: CallTheme? = null
+ var audioRoute: String? = null
+ private set
+ var title: String? = null
+ val displayNames = mutableMapOf<String, String>()
+ private val watchers = mutableMapOf<String, Channel>()
+ private val accountId = "macro_calls"
+
+ private fun account(ctx: Context): PhoneAccountHandle {
+ val handle = PhoneAccountHandle(ComponentName(ctx, TelecomService::class.java), accountId)
+ ctx.getSystemService(TelecomManager::class.java).registerPhoneAccount(
+ PhoneAccount.builder(handle, "Macro").setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
+ .setSupportedUriSchemes(listOf("macro-call")).build()
+ )
+ return handle
+ }
+ fun watch(name: String, channel: Channel) { watchers[name] = channel }
+ fun unwatch() { watchers.clear() }
+ fun emit(name: String, payload: JSObject) { watchers[name]?.send(payload) }
+ fun snapshot(): JSObject? = offer?.takeIf { accepted }?.let {
+ JSObject().apply {
+ put("callId", it.callId); put("channelId", it.channelId); put("connectionState", state)
+ put("isAudioMuted", muted || interrupted()); put("isVideoMuted", !video); put("videoOverlayMode", overlay)
+ put("participantIdentities", identities())
+ }
+ }
+ private fun identities(): JSONArray = JSONArray().apply {
+ room?.localParticipant?.identity?.value?.let { put(it) }
+ room?.remoteParticipants?.values?.forEach { it.identity?.value?.let { id -> put(id) } }
+ }
+ private fun interrupted(): Boolean = held || focusLost || telecomFocusLost
+ private fun syncRemoteAudio() {
+ room?.remoteParticipants?.values?.forEach { participant ->
+ participant.trackPublications.values.forEach { publication ->
+ (publication.track as? RemoteAudioTrack)?.setVolume(if (interrupted()) 0.0 else 1.0)
+ }
+ }
+ }
+ fun publish() {
+ syncRemoteAudio()
+ val payload = snapshot() ?: JSObject()
+ payload.put("state", if (accepted) state else "disconnected")
+ emit("connection", payload)
+ emit("participants", JSObject().apply { put("identities", identities()) })
+ changed?.invoke()
+ }
+ fun prepareJoin(ctx: Context, channelId: String): String {
+ check(joinLease == null) { "A call join is already pending" }
+ val lease = JoinLease(java.util.UUID.randomUUID().toString(), channelId,
+ ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null),
+ offer?.takeIf { !accepted && it.channelId == channelId }?.callId)
+ joinLease = lease
+ if (lease.callId != null) { poller?.cancel(); poller = null }
+ leaseTimeout = scope.launch { delay(30_000); abortJoin(ctx, lease.id) }
+ return lease.id
+ }
+ fun abortJoin(ctx: Context, id: String) {
+ val lease = joinLease?.takeIf { it.id == id } ?: return
+ joinLease = null; leaseTimeout?.cancel(); leaseTimeout = null
+ if (!accepted && offer?.callId == lease.callId) end(ctx, lease.callId)
+ }
+ fun abortPendingJoin(ctx: Context) { joinLease?.let { abortJoin(ctx, it.id) } }
+ fun resetRecipient(ctx: Context, previous: String?) {
+ if (previous == null) return
+ joinLease?.takeIf { it.recipient == previous }?.let { abortJoin(ctx, it.id) }
+ if (recipient == previous) end(ctx)
+ }
+ // Pause local expiry only; remote ring status still resolves cancelled calls.
+ private fun ringTime(): Long {
+ val pending = microphonePermissionStartedAt?.let { SystemClock.elapsedRealtime() - it } ?: 0L
+ return System.currentTimeMillis() - microphonePermissionPausedMs - pending
+ }
+ fun beginMicrophonePermission(id: String): Boolean {
+ val next = offer ?: return false
+ if (next.callId != id || accepted || !CallOffer.fresh(next.sentTime, ringTime())) return false
+ if (microphonePermissionStartedAt == null) microphonePermissionStartedAt = SystemClock.elapsedRealtime()
+ return true
+ }
+ fun finishMicrophonePermission(id: String) {
+ if (offer?.callId != id) return
+ microphonePermissionStartedAt?.let { microphonePermissionPausedMs += SystemClock.elapsedRealtime() - it }
+ microphonePermissionStartedAt = null
+ }
+ fun receive(ctx: Context, data: Map<String, String>, sentTime: Long) {
+ if (android.os.Build.VERSION.SDK_INT < 26) return
+ if (data["recipientId"] != ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)) return
+ val next = runCatching { CallOffer.parse(data["payload"] ?: return, sentTime) }.getOrNull() ?: return
+ if (!CallOffer.fresh(sentTime, System.currentTimeMillis())) return
+ if (ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE).getLong(next.callId, 0) > System.currentTimeMillis() - 120_000) return
+ if (offer != null) return
+ recipient = ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)
+ title = next.title
+ offer = next; state = "ringing"; accepted = false
+ try {
+ val handle = account(ctx)
+ ctx.getSystemService(TelecomManager::class.java).addNewIncomingCall(handle, Bundle().apply { putString("callId", next.callId) })
+ if (joinLease?.channelId == next.channelId) {
+ joinLease?.callId = next.callId
+ return
+ }
+ poller = scope.launch {
+ while (offer === next && room == null) {
+ if (!CallOffer.fresh(next.sentTime, ringTime())) { end(ctx, next.callId); break }
+ val status = ringStatus(next)
+ if (offer !== next || joinLease?.channelId == next.channelId) break
+ if (RingPolicy.decide(next.sentTime, ringTime(), status) == RingPolicy.Decision.RESOLVE) { end(ctx, next.callId); break }
+ delay(1000)
+ }
+ }
+ } catch (_: Exception) { end(ctx, next.callId) }
+ }
+ private suspend fun ringStatus(next: CallOffer): String? = withContext(Dispatchers.IO) {
+ runCatching {
+ val http = URL(next.ringUrl ?: return@withContext null).openConnection() as HttpURLConnection
+ try {
+ http.instanceFollowRedirects = false
+ http.connectTimeout = 5000; http.readTimeout = 5000
+ http.setRequestProperty("Authorization", "Bearer ${next.token}")
+ when (http.responseCode) {
+ 200 -> JSONObject(http.inputStream.bufferedReader().use { it.readText() }).getString("status")
+ 401, 403, 404 -> "invalid"
+ else -> null
+ }
+ } finally { http.disconnect() }
+ }.getOrNull()
+ }
+ fun outgoing(ctx: Context, next: CallOffer, leaseId: String? = null) {
+ if (leaseId != null) check(joinLease?.let { it.id == leaseId && it.channelId == next.channelId } == true) { "Call join was cancelled" }
+ val current = offer
+ if (current?.callId == next.callId) {
+ if (accepted) { joinLease = null; leaseTimeout?.cancel(); leaseTimeout = null }
+ if (!accepted) {
+ poller?.cancel(); poller = null
+ offer = next; title = next.title; accepted = true; state = "connecting"
+ joinLease = null; leaseTimeout?.cancel(); leaseTimeout = null
+ publish(); connect(ctx)
+ }
+ return
+ }
+ check(current == null) { "Another call is active" }
+ recipient = ctx.getSharedPreferences("macro_push", Context.MODE_PRIVATE).getString("recipient", null)
+ title = next.title
+ joinLease = null; leaseTimeout?.cancel(); leaseTimeout = null
+ offer = next; state = "connecting"; accepted = true; publish()
+ try {
+ val handle = account(ctx)
+ ctx.getSystemService(TelecomManager::class.java).placeCall(Uri.parse("macro-call:${next.callId}"), Bundle().apply {
+ putParcelable(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, handle)
+ putBundle(TelecomManager.EXTRA_OUTGOING_CALL_EXTRAS, Bundle().apply { putString("callId", next.callId) })
+ })
+ } catch (error: Exception) { end(ctx, next.callId); throw error }
+ }
+ fun showIncoming(ctx: Context) {
+ try { CallService.start(ctx); publish() }
+ catch (_: Exception) { end(ctx) }
+ }
+ fun answer(ctx: Context, id: String, verify: suspend (CallOffer) -> String? = ::ringStatus) {
+ val next = offer ?: return
+ if (next.callId != id || room != null || answering) return
+ answering = true
+ scope.launch {
+ // Recheck immediately before answer to close the answered-elsewhere race.
+ val status = verify(next)
+ if (offer !== next) return@launch
+ answering = false
+ if (joinLease?.channelId == next.channelId) return@launch
+ if (room != null || accepted) return@launch
+ when (RingPolicy.decide(next.sentTime, ringTime(), status)) {
+ RingPolicy.Decision.RESOLVE -> { end(ctx, id); return@launch }
+ RingPolicy.Decision.RETRY -> { error = "Could not verify this call. Check your connection and try again."; publish(); return@launch }
+ RingPolicy.Decision.RING -> error = null
+ }
+ if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
+ if (!beginMicrophonePermission(id)) return@launch
+ runCatching {
+ ctx.startActivity(Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).putExtra("answer", id))
+ }.onFailure { finishMicrophonePermission(id) }
+ return@launch
+ }
+ poller?.cancel(); poller = null
+ accepted = true; state = "connecting"
+ pendingAnswered = next.channelId
+ connect(ctx)
+ emit("answered", JSObject().apply { put("channelId", next.channelId); put("nativeMedia", true) })
+ }
+ }
+ fun connect(ctx: Context) {
+ val next = offer ?: return
+ if (room != null) return
+ if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { end(ctx, next.callId); return }
+ val media = LiveKit.create(ctx.applicationContext)
+ room = media
+ media.audioSwitchHandler?.loggingEnabled = false
+ media.audioSwitchHandler?.registerAudioDeviceChangeListener { devices, selected ->
+ scope.launch {
+ if (room !== media) return@launch
+ audioRoute = selected?.javaClass?.simpleName
+ publish()
+ if (selected?.javaClass?.simpleName != desiredAudioType) {
+ devices.firstOrNull { it.javaClass.simpleName == desiredAudioType }?.let { media.audioSwitchHandler?.selectDevice(it) }
+ }
+ }
+ }
+ media.audioSwitchHandler?.registerOnAudioFocusChangeListener(AudioManager.OnAudioFocusChangeListener { focus ->
+ scope.launch {
+ if (room !== media) return@launch
+ focusLost = focus != AudioManager.AUDIOFOCUS_GAIN
+ if (state == "connected" || state == "reconnecting") runCatching { applyMicrophone() }
+ publish()
+ }
+ })
+ session = scope.launch {
+ try {
+ CallService.start(ctx, media = true)
+ launch {
+ media.events.collect { event ->
+ if (room !== media) return@collect
+ when (event) {
+ is RoomEvent.Reconnecting -> state = "reconnecting"
+ is RoomEvent.Reconnected -> state = "connected"
+ is RoomEvent.Disconnected -> { end(ctx, next.callId); return@collect }
+ else -> {}
+ }
+ publish()
+ }
+ }
+ media.connect(next.serverUrl, next.token)
+ if (room !== media) return@launch
+ media.localParticipant.setMicrophoneEnabled(!muted && !interrupted())
+ state = "connected"; connection?.setActive(); publish()
+ ctx.startActivity(Intent(ctx, CallActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
+ } catch (_: CancellationException) {
+ // end() already owns teardown.
+ } catch (error: Exception) {
+ // Exception messages can contain the signaling URL/token; log types only.
+ android.util.Log.w("MacroCall", "Native media failed: ${error.javaClass.simpleName}; cause=${error.cause?.javaClass?.simpleName}")
+ if (offer === next) {
+ android.widget.Toast.makeText(ctx, "Could not connect the call. Please try again.", android.widget.Toast.LENGTH_LONG).show()
+ end(ctx, next.callId)
+ }
+ }
+ }
+ }
+ suspend fun microphone(enabled: Boolean) = audioMutex.withLock {
+ val media = room ?: return@withLock
+ media.localParticipant.setMicrophoneEnabled(enabled && !interrupted())
+ if (room === media) { muted = !enabled; publish() }
+ }
+ private suspend fun applyMicrophone() = audioMutex.withLock {
+ val media = room ?: return@withLock
+ media.localParticipant.setMicrophoneEnabled(!muted && !interrupted())
+ if (room === media) publish()
+ }
+ fun hold(value: Boolean) {
+ held = value
+ scope.launch { runCatching { applyMicrophone() } }
+ }
+ suspend fun camera(ctx: Context, enabled: Boolean, expectedRoom: Room? = null) = videoMutex.withLock {
+ val media = room ?: return@withLock
+ if (expectedRoom != null && media !== expectedRoom) return@withLock
+ if (enabled) {
+ check(ContextCompat.checkSelfPermission(ctx, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { "Camera permission required" }
+ CallService.start(ctx, media = true, camera = true)
+ }
+ media.localParticipant.setCameraEnabled(enabled)
+ if (room === media) { video = enabled; CallService.start(ctx, media = true, camera = enabled); publish() }
+ }
+ fun switchCamera() { (room?.localParticipant?.getTrackPublication(Track.Source.CAMERA)?.track as? LocalVideoTrack)?.switchCamera() }
+ private fun selectAudio(type: String) {
+ desiredAudioType = type
+ val handler = room?.audioSwitchHandler ?: return
+ handler.availableAudioDevices.firstOrNull { it.javaClass.simpleName == type }?.let { handler.selectDevice(it) }
+ }
+ fun telecomAudio(audio: CallAudioState) {
+ scope.launch {
+ if (telecomMuted != audio.isMuted) {
+ telecomMuted = audio.isMuted
+ runCatching { microphone(!audio.isMuted) }
+ }
+ selectAudio(when (audio.route) {
+ CallAudioState.ROUTE_BLUETOOTH -> "BluetoothHeadset"
+ CallAudioState.ROUTE_WIRED_HEADSET -> "WiredHeadset"
+ CallAudioState.ROUTE_SPEAKER -> "Speakerphone"
+ else -> "Earpiece"
+ })
+ }
+ }
+ fun telecomFocus(gained: Boolean) {
+ telecomFocusLost = !gained
+ scope.launch { runCatching { applyMicrophone() }; publish() }
+ }
+ fun systemMute(value: Boolean) {
+ telecomMuted = value
+ scope.launch { runCatching { microphone(!value) } }
+ }
+ fun endpointAudio(type: Int) {
+ selectAudio(when (type) {
+ CallEndpoint.TYPE_BLUETOOTH -> "BluetoothHeadset"
+ CallEndpoint.TYPE_WIRED_HEADSET -> "WiredHeadset"
+ CallEndpoint.TYPE_SPEAKER -> "Speakerphone"
+ else -> "Earpiece"
+ })
+ }
+ fun route(route: Int) { (connection as? TelecomService.MacroConnection)?.route(route) }
+ fun end(ctx: Context, id: String? = offer?.callId,
+ disconnectConnection: (Connection) -> Unit = { it.setDisconnected(DisconnectCause(DisconnectCause.LOCAL)) }) {
+ val next = offer ?: return
+ if (next.callId != id) return
+ val preferences = ctx.getSharedPreferences("macro_calls", Context.MODE_PRIVATE)
+ val now = System.currentTimeMillis()
+ runCatching {
+ preferences.edit().apply {
+ preferences.all.forEach { (key, timestamp) -> if ((timestamp as? Long ?: 0) < now - 120_000) remove(key) }
+ putLong(next.callId, now)
+ }.apply()
+ }
+ if (joinLease?.callId == next.callId) {
+ joinLease = null; leaseTimeout?.cancel(); leaseTimeout = null
+ }
+ microphonePermissionStartedAt = null; microphonePermissionPausedMs = 0L
+ poller?.cancel(); poller = null
+ session?.cancel(); session = null
+ val media = room; room = null
+ val telecomConnection = connection; connection = null
+ offer = null; pendingAnswered = null; state = "disconnected"; title = null; recipient = null; displayNames.clear(); error = null; muted = false; video = false; held = false; answering = false; accepted = false; focusLost = false; telecomMuted = false; telecomFocusLost = false; desiredAudioType = null; audioRoute = null; overlay = "hidden"
+ // Native/SDK callbacks may fail or reenter; no resource owns the cleared session.
+ // Release each resource independently so one failure cannot leave a phantom call.
+ runCatching { media?.disconnect() }
+ runCatching { media?.release() }
+ runCatching { telecomConnection?.let(disconnectConnection) }
+ runCatching { telecomConnection?.destroy() }
+ runCatching { CallService.stop() }
+ runCatching { ctx.getSystemService(android.app.NotificationManager::class.java).cancel(CallService.NOTIFICATION_ID) }
+ runCatching { publish() }
+ runCatching { emit("ended", JSObject().apply { put("callId", next.callId) }) }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/RingPolicy.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/RingPolicy.kt
new file mode 100644
index 0000000000..3d4eaf83c0
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/RingPolicy.kt
@@ -0,0 +1,14 @@
+package com.macro.call
+
+/** Decisions shared by push receipt, polling and answer revalidation. */
+internal object RingPolicy {
+ enum class Decision { RING, RESOLVE, RETRY }
+ // FCM uses the server clock; a small skew must not discard immediate delivery.
+ fun fresh(sentTime: Long, now: Long): Boolean = sentTime > 0 && now - sentTime in -5_000..60_000
+ fun decide(sentTime: Long, now: Long, status: String?): Decision = when {
+ !fresh(sentTime, now) -> Decision.RESOLVE
+ status in listOf("answered", "ended", "invalid") -> Decision.RESOLVE
+ status == "ringing" -> Decision.RING
+ else -> Decision.RETRY
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/TelecomService.kt b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/TelecomService.kt
new file mode 100644
index 0000000000..c015563ab5
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/java/com/macro/call/TelecomService.kt
@@ -0,0 +1,67 @@
+package com.macro.call
+
+import android.net.Uri
+import android.telecom.*
+import android.os.Build
+import android.os.OutcomeReceiver
+
+class TelecomService : ConnectionService() {
+ override fun onConnectionServiceFocusLost() {
+ Calls.telecomFocus(false)
+ connectionServiceFocusReleased()
+ }
+ override fun onConnectionServiceFocusGained() { Calls.telecomFocus(true) }
+ override fun onCreateIncomingConnection(handle: PhoneAccountHandle, request: ConnectionRequest): Connection = create(request, true)
+ override fun onCreateOutgoingConnection(handle: PhoneAccountHandle, request: ConnectionRequest): Connection = create(request, false)
+ private fun create(request: ConnectionRequest, incoming: Boolean): Connection {
+ val id = request.extras?.getString("callId")
+ val offer = Calls.offer
+ if (offer == null || offer.callId != id) return Connection.createFailedConnection(DisconnectCause(DisconnectCause.CANCELED))
+ return MacroConnection(id).apply {
+ connectionProperties = Connection.PROPERTY_SELF_MANAGED
+ connectionCapabilities = Connection.CAPABILITY_SUPPORT_HOLD or Connection.CAPABILITY_HOLD or Connection.CAPABILITY_MUTE
+ setAddress(Uri.parse("macro-call:$id"), TelecomManager.PRESENTATION_ALLOWED)
+ setCallerDisplayName(offer.title, TelecomManager.PRESENTATION_ALLOWED)
+ setAudioModeIsVoip(true)
+ Calls.connection = this
+ // App Join can adopt an incoming offer before Telecom creates it.
+ if (incoming && Calls.snapshot() == null) setRinging()
+ else {
+ if (Calls.state == "connected") setActive() else setDialing()
+ if (!incoming) Calls.connect(applicationContext)
+ }
+ }
+ }
+ override fun onCreateIncomingConnectionFailed(handle: PhoneAccountHandle, request: ConnectionRequest) { Calls.end(applicationContext, request.extras?.getString("callId")) }
+ override fun onCreateOutgoingConnectionFailed(handle: PhoneAccountHandle, request: ConnectionRequest) { Calls.end(applicationContext, request.extras?.getString("callId")) }
+
+ inner class MacroConnection(private val id: String) : Connection() {
+ private var endpoints: List<CallEndpoint> = emptyList()
+ override fun onShowIncomingCallUi() { if (Calls.offer?.callId == id) Calls.showIncoming(applicationContext) }
+ override fun onAnswer() { Calls.answer(applicationContext, id) }
+ override fun onAnswer(videoState: Int) { onAnswer() }
+ override fun onReject() { Calls.end(applicationContext, id) }
+ override fun onDisconnect() { Calls.end(applicationContext, id) }
+ override fun onHold() { if (Calls.offer?.callId == id) { Calls.hold(true); setOnHold() } }
+ override fun onUnhold() { if (Calls.offer?.callId == id) { Calls.hold(false); setActive() } }
+ override fun onCallAudioStateChanged(state: CallAudioState) { if (Calls.offer?.callId == id) Calls.telecomAudio(state) }
+ override fun onAvailableCallEndpointsChanged(available: MutableList<CallEndpoint>) { endpoints = available.toList() }
+ override fun onCallEndpointChanged(endpoint: CallEndpoint) { if (Calls.offer?.callId == id) Calls.endpointAudio(endpoint.endpointType) }
+ override fun onMuteStateChanged(isMuted: Boolean) { if (Calls.offer?.callId == id) Calls.systemMute(isMuted) }
+ fun route(route: Int) {
+ if (Build.VERSION.SDK_INT >= 34) {
+ val type = when (route) {
+ CallAudioState.ROUTE_BLUETOOTH -> CallEndpoint.TYPE_BLUETOOTH
+ CallAudioState.ROUTE_WIRED_HEADSET -> CallEndpoint.TYPE_WIRED_HEADSET
+ CallAudioState.ROUTE_SPEAKER -> CallEndpoint.TYPE_SPEAKER
+ else -> CallEndpoint.TYPE_EARPIECE
+ }
+ val endpoint = endpoints.firstOrNull { it.endpointType == type } ?: return
+ requestCallEndpointChange(endpoint, mainExecutor, object : OutcomeReceiver<Void, CallEndpointException> {
+ override fun onResult(result: Void?) { Calls.endpointAudio(type) }
+ override fun onError(error: CallEndpointException) { Calls.publish() }
+ })
+ } else setAudioRoute(route)
+ }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/main/res/values/styles.xml b/apps/web/tauri/callkit_plugin/android/src/main/res/values/styles.xml
new file mode 100644
index 0000000000..ece697da85
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/main/res/values/styles.xml
@@ -0,0 +1,9 @@
+<resources>
+ <style name="MacroCallOverlay" parent="android:style/Theme.Material.Light.NoActionBar">
+ <item name="android:windowIsTranslucent">true</item>
+ <item name="android:windowBackground">@android:color/transparent</item>
+ <item name="android:windowNoTitle">true</item>
+ <item name="android:windowDisablePreview">true</item>
+ <item name="android:windowActionModeOverlay">true</item>
+ </style>
+</resources>
diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt
new file mode 100644
index 0000000000..acc2590810
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/CallOfferTest.kt
@@ -0,0 +1,34 @@
+package com.macro.call
+
+import org.json.JSONObject
+import org.junit.Assert.*
+import org.junit.Test
+
+class CallOfferTest {
+ private fun offer(): JSONObject = JSONObject().apply {
+ put("callId", "11111111-1111-1111-1111-111111111111")
+ put("channelId", "channel-1")
+ put("channelName", "General")
+ put("callerName", "Alice")
+ put("livekitServerUrl", "wss://livekit.example.com")
+ put("livekitToken", "recipient-scoped-token")
+ put("ringStatusUrl", "https://dev.macro.com/call/ring-status/call-1")
+ }
+ @Test fun acceptsTheBackendCallEnvelope() {
+ val parsed = CallOffer.parse(offer().toString(), 1000)
+ assertEquals("channel-1", parsed.channelId)
+ assertEquals("recipient-scoped-token", parsed.token)
+ assertEquals(1000L, parsed.sentTime)
+ }
+ @Test fun refusesToSendBearerTokensToUntrustedOrInsecureRingEndpoints() {
+ for (url in listOf("http://dev.macro.com/ring", "https://macro.com.evil.example/ring", "https://evil.example/ring", "https://[email protected]/ring")) {
+ assertThrows(IllegalArgumentException::class.java) { CallOffer.parse(offer().put("ringStatusUrl", url).toString(), 1000) }
+ }
+ }
+ @Test fun requiresSecureMediaAndValidIdentity() {
+ assertThrows(IllegalArgumentException::class.java) { CallOffer.parse(offer().put("livekitServerUrl", "ws://livekit.example.com").toString(), 1000) }
+ assertThrows(IllegalArgumentException::class.java) { CallOffer.parse(offer().put("callId", "invalid").toString(), 1000) }
+ assertThrows(IllegalArgumentException::class.java) { CallOffer.parse(offer().put("channelId", " ").toString(), 1000) }
+ assertThrows(IllegalArgumentException::class.java) { CallOffer.parse(offer().put("livekitToken", " ").toString(), 1000) }
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/NameArgsTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/NameArgsTest.kt
new file mode 100644
index 0000000000..1881081f93
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/NameArgsTest.kt
@@ -0,0 +1,16 @@
+package com.macro.call
+
+import app.tauri.plugin.Invoke
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.junit.Assert.*
+import org.junit.Test
+
+class NameArgsTest {
+ @Test fun sharedNullDisplayNamePayloadDeserializes() {
+ val invoke = Invoke(0, "setParticipantDisplayName", 0, 0, { _, _ -> },
+ "{\"identity\":\"participant\",\"displayName\":null}", ObjectMapper())
+ val args = invoke.parseArgs(NameArgs::class.java)
+ assertEquals("participant", args.identity)
+ assertNull(args.displayName)
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/RingPolicyTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/RingPolicyTest.kt
new file mode 100644
index 0000000000..ceeb5da9ee
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/RingPolicyTest.kt
@@ -0,0 +1,29 @@
+package com.macro.call
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class RingPolicyTest {
+ @Test fun expiresDelayedPushesAndRejectsExcessiveClockSkew() {
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(1_000, 61_001, "ringing"))
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(6_001, 1_000, "ringing"))
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(0, 1_000, "ringing"))
+ }
+ @Test fun toleratesSmallFcmServerClockSkew() {
+ assertEquals(RingPolicy.Decision.RING, RingPolicy.decide(1_300, 1_000, "ringing"))
+ assertEquals(RingPolicy.Decision.RING, RingPolicy.decide(6_000, 1_000, "ringing"))
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(1_000, 61_001, "ringing"))
+ }
+ @Test fun resolvesRemoteCancellationAndAnswersElsewhere() {
+ for (status in listOf("ended", "answered", "invalid")) {
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(1_000, 2_000, status))
+ }
+ }
+ @Test fun transientFailuresCanRetryButCannotAuthorizeAnAnswer() {
+ for (status in listOf(null, "unknown")) {
+ assertEquals(RingPolicy.Decision.RETRY, RingPolicy.decide(1_000, 2_000, status))
+ }
+ assertEquals(RingPolicy.Decision.RING, RingPolicy.decide(1_000, 2_000, "ringing"))
+ assertEquals(RingPolicy.Decision.RESOLVE, RingPolicy.decide(1_000, 61_001, null))
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/ThemeArgsTest.kt b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/ThemeArgsTest.kt
new file mode 100644
index 0000000000..3400387f6b
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/android/src/test/java/com/macro/call/ThemeArgsTest.kt
@@ -0,0 +1,16 @@
+package com.macro.call
+
+import app.tauri.plugin.Invoke
+import com.fasterxml.jackson.databind.ObjectMapper
+import org.junit.Assert.*
+import org.junit.Test
+
+class ThemeArgsTest {
+ @Test fun sharedThemeEnvelopeDeserializesThroughTheTauriBridge() {
+ val invoke = Invoke(0, "setCallDrawerTheme", 0, 0, { _, _ -> },
+ """{"theme":{"drawerBackground":{"red":0.2,"green":0.3,"blue":0.4,"alpha":1}}}""", ObjectMapper())
+ val args = invoke.parseArgs(ThemeArgs::class.java)
+ assertEquals(0.2, args.theme["drawerBackground"]!!["red"]!!, 0.0001)
+ assertEquals(1.0, args.theme["drawerBackground"]!!["alpha"]!!, 0.0001)
+ }
+}
diff --git a/apps/web/tauri/callkit_plugin/build.rs b/apps/web/tauri/callkit_plugin/build.rs
index f832e6c25c..a093e11ff0 100644
--- a/apps/web/tauri/callkit_plugin/build.rs
+++ b/apps/web/tauri/callkit_plugin/build.rs
@@ -16,6 +16,8 @@ const COMMANDS: &[&str] = &[
"watch_participant_identities",
"get_active_call_state",
"start_outgoing_call",
+ "prepare_join",
+ "abort_join",
"set_video_enabled",
"set_video_overlay_mode",
"set_call_drawer_channel_title",
@@ -55,7 +57,10 @@ impl BuildEnv {
}
fn main() {
- tauri_plugin::Builder::new(COMMANDS).try_build().unwrap();
+ tauri_plugin::Builder::new(COMMANDS)
+ .android_path("android")
+ .try_build()
+ .unwrap();
let build_env = BuildEnv::from_env();
if build_env.is_ios_target() {
diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/abort_join.toml b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/abort_join.toml
new file mode 100644
index 0000000000..bf23b91e37
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/abort_join.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-abort-join"
+description = "Enables the abort_join command without any pre-configured scope."
+commands.allow = ["abort_join"]
+
+[[permission]]
+identifier = "deny-abort-join"
+description = "Denies the abort_join command without any pre-configured scope."
+commands.deny = ["abort_join"]
diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/prepare_join.toml b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/prepare_join.toml
new file mode 100644
index 0000000000..45bce9208f
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/commands/prepare_join.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-prepare-join"
+description = "Enables the prepare_join command without any pre-configured scope."
+commands.allow = ["prepare_join"]
+
+[[permission]]
+identifier = "deny-prepare-join"
+description = "Denies the prepare_join command without any pre-configured scope."
+commands.deny = ["prepare_join"]
diff --git a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md
index a2e765471c..67194124bc 100644
--- a/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md
+++ b/apps/web/tauri/callkit_plugin/permissions/autogenerated/reference.md
@@ -7,6 +7,32 @@
</tr>
+<tr>
+<td>
+
+`call-kit:allow-abort-join`
+
+</td>
+<td>
+
+Enables the abort_join command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`call-kit:deny-abort-join`
+
+</td>
+<td>
+
+Denies the abort_join command without any pre-configured scope.
+
+</td>
+</tr>
+
<tr>
<td>
@@ -114,6 +140,32 @@ Denies the get_voip_token command without any pre-configured scope.
<tr>
<td>
+`call-kit:allow-prepare-join`
+
+</td>
+<td>
+
+Enables the prepare_join command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`call-kit:deny-prepare-join`
+
+</td>
+<td>
+
+Denies the prepare_join command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
`call-kit:allow-register-listener`
</td>
diff --git a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json
index 9ece65d847..5a6d055330 100644
--- a/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json
+++ b/apps/web/tauri/callkit_plugin/permissions/schemas/schema.json
@@ -294,6 +294,18 @@
"PermissionKind": {
"type": "string",
"oneOf": [
+ {
+ "description": "Enables the abort_join command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-abort-join",
+ "markdownDescription": "Enables the abort_join command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the abort_join command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-abort-join",
+ "markdownDescription": "Denies the abort_join command without any pre-configured scope."
+ },
{
"description": "Enables the end_active_call command without any pre-configured scope.",
"type": "string",
@@ -342,6 +354,18 @@
"const": "deny-get-voip-token",
"markdownDescription": "Denies the get_voip_token command without any pre-configured scope."
},
+ {
+ "description": "Enables the prepare_join command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-prepare-join",
+ "markdownDescription": "Enables the prepare_join command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the prepare_join command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-prepare-join",
+ "markdownDescription": "Denies the prepare_join command without any pre-configured scope."
+ },
{
"description": "Enables the register_listener command without any pre-configured scope.",
"type": "string",
diff --git a/apps/web/tauri/callkit_plugin/src/android-init.js b/apps/web/tauri/callkit_plugin/src/android-init.js
new file mode 100644
index 0000000000..3be204444c
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/src/android-init.js
@@ -0,0 +1 @@
+Object.defineProperty(window, '__MACRO_ANDROID_CALL_KIT__', { value: true });
diff --git a/apps/web/tauri/callkit_plugin/src/android.rs b/apps/web/tauri/callkit_plugin/src/android.rs
new file mode 100644
index 0000000000..e9aad7bc09
--- /dev/null
+++ b/apps/web/tauri/callkit_plugin/src/android.rs
@@ -0,0 +1,219 @@
+use serde::Serialize;
+use serde_json::Value;
+use tauri::{AppHandle, Manager, Runtime, ipc::Channel, plugin::PluginHandle};
+
+pub(crate) struct Calls<R: Runtime>(pub PluginHandle<R>);
+
+macro_rules! command {
+ ($name:ident, $native:literal) => {
+ #[tauri::command]
+ pub(crate) async fn $name<R: Runtime>(app: AppHandle<R>) -> Result<Value, String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async($native, ())
+ .await
+ .map_err(|e| e.to_string())
+ }
+ };
+}
+command!(get_voip_token, "getVoipToken");
+command!(end_active_call, "endActiveCall");
+command!(get_pending_answered_call, "getPendingAnsweredCall");
+command!(get_active_call_state, "getActiveCallState");
+command!(switch_camera, "switchCamera");
+
+#[derive(Serialize)]
+struct WatchArgs {
+ channel: Channel<Value>,
+}
+macro_rules! watch {
+ ($name:ident, $native:literal) => {
+ #[tauri::command]
+ pub(crate) async fn $name<R: Runtime>(
+ app: AppHandle<R>,
+ channel: Channel<Value>,
+ ) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async($native, WatchArgs { channel })
+ .await
+ .map_err(|e| e.to_string())
+ }
+ };
+}
+watch!(watch_call_answered, "watchCallAnswered");
+watch!(watch_call_ended, "watchCallEnded");
+watch!(watch_connection_state, "watchConnectionState");
+watch!(watch_drawer_opened, "watchDrawerOpened");
+watch!(watch_participant_identities, "watchParticipantIdentities");
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct StartOutgoingCallArgs {
+ channel_id: String,
+ call_id: String,
+ channel_title: Option<String>,
+ caller_name: Option<String>,
+ server_url: String,
+ token: String,
+ join_lease: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) async fn start_outgoing_call<R: Runtime>(
+ app: AppHandle<R>,
+ channel_id: String,
+ call_id: String,
+ channel_title: Option<String>,
+ caller_name: Option<String>,
+ server_url: String,
+ token: String,
+ join_lease: Option<String>,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async(
+ "startOutgoingCall",
+ StartOutgoingCallArgs {
+ channel_id,
+ call_id,
+ channel_title,
+ caller_name,
+ server_url,
+ token,
+ join_lease,
+ },
+ )
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetVideoEnabledArgs {
+ enabled: bool,
+}
+
+#[tauri::command]
+pub(crate) async fn set_video_enabled<R: Runtime>(
+ app: AppHandle<R>,
+ enabled: bool,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async("setVideoEnabled", SetVideoEnabledArgs { enabled })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetVideoOverlayModeArgs {
+ mode: String,
+}
+
+#[tauri::command]
+pub(crate) async fn set_video_overlay_mode<R: Runtime>(
+ app: AppHandle<R>,
+ mode: String,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async("setVideoOverlayMode", SetVideoOverlayModeArgs { mode })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetCallDrawerChannelTitleArgs {
+ channel_title: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) async fn set_call_drawer_channel_title<R: Runtime>(
+ app: AppHandle<R>,
+ channel_title: Option<String>,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async(
+ "setCallDrawerChannelTitle",
+ SetCallDrawerChannelTitleArgs { channel_title },
+ )
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetCallDrawerThemeArgs {
+ theme: Value,
+}
+
+#[tauri::command]
+pub(crate) async fn set_call_drawer_theme<R: Runtime>(
+ app: AppHandle<R>,
+ theme: Value,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async("setCallDrawerTheme", SetCallDrawerThemeArgs { theme })
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct SetParticipantDisplayNameArgs {
+ identity: String,
+ display_name: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) async fn set_participant_display_name<R: Runtime>(
+ app: AppHandle<R>,
+ identity: String,
+ display_name: Option<String>,
+) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async(
+ "setParticipantDisplayName",
+ SetParticipantDisplayNameArgs {
+ identity,
+ display_name,
+ },
+ )
+ .await
+ .map_err(|e| e.to_string())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct PrepareJoinArgs {
+ channel_id: String,
+}
+#[tauri::command]
+pub(crate) async fn prepare_join<R: Runtime>(
+ app: AppHandle<R>,
+ channel_id: String,
+) -> Result<Value, String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async("prepareJoin", PrepareJoinArgs { channel_id })
+ .await
+ .map_err(|e| e.to_string())
+}
+#[derive(Serialize)]
+struct AbortJoinArgs {
+ lease: String,
+}
+#[tauri::command]
+pub(crate) async fn abort_join<R: Runtime>(app: AppHandle<R>, lease: String) -> Result<(), String> {
+ app.state::<Calls<R>>()
+ .0
+ .run_mobile_plugin_async("abortJoin", AbortJoinArgs { lease })
+ .await
+ .map_err(|e| e.to_string())
+}
diff --git a/apps/web/tauri/callkit_plugin/src/lib.rs b/apps/web/tauri/callkit_plugin/src/lib.rs
index 5031d5603a..88fa29f1d2 100644
--- a/apps/web/tauri/callkit_plugin/src/lib.rs
+++ b/apps/web/tauri/callkit_plugin/src/lib.rs
@@ -4,24 +4,58 @@
//! 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.
+//! tokens to the JS layer. Android uses self-managed Telecom and native LiveKit.
+//! Desktop platforms have no native call integration.
#![deny(missing_docs)]
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_call_kit);
+#[cfg(target_os = "android")]
+mod android;
+
/// 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.
+/// On Android, registers the Kotlin Telecom and LiveKit bridge.
///
/// Pass the result directly to [`tauri::Builder::plugin`].
pub fn init<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
- tauri::plugin::Builder::new("call-kit")
+ let builder = tauri::plugin::Builder::new("call-kit");
+ #[cfg(target_os = "android")]
+ let builder = builder
+ .invoke_handler(tauri::generate_handler![
+ android::get_voip_token,
+ android::end_active_call,
+ android::get_pending_answered_call,
+ android::watch_call_answered,
+ android::watch_call_ended,
+ android::watch_connection_state,
+ android::watch_drawer_opened,
+ android::watch_participant_identities,
+ android::get_active_call_state,
+ android::start_outgoing_call,
+ android::prepare_join,
+ android::abort_join,
+ android::set_video_enabled,
+ android::set_video_overlay_mode,
+ android::set_call_drawer_channel_title,
+ android::set_call_drawer_theme,
+ android::set_participant_display_name,
+ android::switch_camera
+ ])
+ .js_init_script(include_str!("android-init.js"));
+ builder
.setup(|_app, _api| {
#[cfg(target_os = "ios")]
_api.register_ios_plugin(init_plugin_call_kit)?;
+ #[cfg(target_os = "android")]
+ {
+ use tauri::Manager;
+ let handle = _api.register_android_plugin("com.macro.call", "CallPlugin")?;
+ _app.manage(android::Calls(handle));
+ }
Ok(())
})
.build()
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index fc4805f4db..94a360c09f 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -111,6 +111,7 @@ rustls-platform-verifier = "0.6"
tauri-plugin-android-auth = { path = "../android_auth_plugin" }
tauri-plugin-android-mobile = { path = "../android_mobile_plugin" }
tauri-plugin-android-push = { path = "../android_push_plugin" }
+tauri-plugin-call-kit = { path = "../callkit_plugin" }
tauri-plugin-network-status = { path = "../network_status_plugin" }
[target.'cfg(target_os = "ios")'.dependencies]
diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.json
index 01b3c9a3db..66ba40024a 100644
--- a/apps/web/tauri/src-tauri/capabilities/android.json
+++ b/apps/web/tauri/src-tauri/capabilities/android.json
@@ -10,6 +10,23 @@
"android-auth:allow-authenticate",
"android-mobile:default",
"android-push:default",
+ "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-prepare-join",
+ "call-kit:allow-abort-join",
+ "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",
"network-status:allow-watch-status"
]
}
diff --git a/apps/web/tauri/src-tauri/gen/android/build.gradle.kts b/apps/web/tauri/src-tauri/gen/android/build.gradle.kts
index 78859e9e78..e2aa03f2d3 100644
--- a/apps/web/tauri/src-tauri/gen/android/build.gradle.kts
+++ b/apps/web/tauri/src-tauri/gen/android/build.gradle.kts
@@ -14,6 +14,7 @@ allprojects {
repositories {
google()
mavenCentral()
+ maven { url = uri("https://jitpack.io") }
}
}
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 914da5f8ec..d4fd1cef9d 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -220,6 +220,7 @@ pub fn run() {
.plugin(tauri_plugin_android_auth::init())
.plugin(tauri_plugin_android_mobile::init())
.plugin(tauri_plugin_android_push::init())
+ .plugin(tauri_plugin_call_kit::init())
.plugin(tauri_plugin_network_status::init());
}
diff --git a/apps/web/tauri/src-tauri/tauri.android.conf.json b/apps/web/tauri/src-tauri/tauri.android.conf.json
index 905c8831e2..a474155b6f 100644
--- a/apps/web/tauri/src-tauri/tauri.android.conf.json
+++ b/apps/web/tauri/src-tauri/tauri.android.conf.json
@@ -5,7 +5,7 @@
"version": "2.5.0",
"bundle": {
"android": {
- "versionCode": 3
+ "versionCode": 4
}
},
"plugins": {
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index 2527d2cd16..ef3e563cae 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -971,9 +971,8 @@ impl<
.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.
+ // Try native call pushes first; ordinary alerts remain fallbacks
+ // independently for iOS and Android.
// Resolve VoIP endpoints before minting tokens:
// users without PushKit endpoints should not get
@@ -1045,15 +1044,16 @@ impl<
})
.collect();
- let voip_recipient_ids =
+ let native_delivery =
self.voip_push_sender.send_voip_pushes(pushes).await;
- let apns_recipient_ids =
- exclude_voip_recipients(recipient_ids, &voip_recipient_ids);
+ let apns_recipient_ids = exclude_voip_recipients(
+ recipient_ids,
+ &native_delivery.fully_delivered,
+ );
- // APNS is the fallback/default path. Recipients
- // with a successful VoIP delivery skip the regular
- // alert to avoid duplicate incoming-call UI. One
+ // Persist and alert only recipients with an unhandled platform.
+ // Suppress ordinary alerts on platforms reached natively. One
// request per distinct channel name, so the alert
// title and stored metadata match what each
// recipient calls the channel.
@@ -1075,7 +1075,8 @@ impl<
recipient_ids: apns_group_recipients,
}
.into_request()
- .with_apns();
+ .with_apns()
+ .with_mobile_push_exclusions(native_delivery.delivered.clone());
self.notification_ingress
.send_notification(req)
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index f679c841a2..3e97e18f8b 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -4401,3 +4401,27 @@ async fn call_record_reader_reports_a_deleted_record_as_not_found() {
Err(CallError::NotFound(_))
));
}
+
+#[test]
+fn native_call_fallback_persists_only_users_with_unhandled_platforms() {
+ use notification::domain::models::{MobilePushRecipients, NativeCallPushResult};
+ let fully_handled = user("[email protected]");
+ let ios_fallback = user("[email protected]");
+ let android_fallback = user("[email protected]");
+ let result = NativeCallPushResult {
+ delivered: MobilePushRecipients {
+ ios: HashSet::from([fully_handled.clone(), android_fallback.clone()]),
+ android: HashSet::from([fully_handled.clone(), ios_fallback.clone()]),
+ },
+ fully_delivered: HashSet::from([fully_handled.clone()]),
+ };
+ let fallback = exclude_voip_recipients(
+ HashSet::from([
+ fully_handled,
+ ios_fallback.clone(),
+ android_fallback.clone(),
+ ]),
+ &result.fully_delivered,
+ );
+ assert_eq!(fallback, HashSet::from([ios_fallback, android_fallback]));
+}
diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.md
index 9fb3ee2a93..77bd346b5b 100644
--- a/crates/macro_db_client/AGENTS.md
+++ b/crates/macro_db_client/AGENTS.md
@@ -10,7 +10,7 @@ queries used across Rust services.
- `src/lib.rs`: the module list — one module per table/feature area
(`user.rs`, `document.rs`, `organization.rs`, `team/`, `item_access/`, ...).
-- `migrations/`: MacroDB's SQLx migrations, paired `.up.sql`/`.down.sql`, 500+
+- `migrations/`: MacroDB's SQLx-generated migrations, 500+
files; the only place MacroDB schema changes are made.
- `tests/`: cross-table integration tests (e.g. `add_forms.rs`).
@@ -32,7 +32,7 @@ queries used across Rust services.
## Recipes
- Add a column or table: `sqlx migrate add --source crates/macro_db_client/migrations <name>`
- → edit the generated `.up.sql`/`.down.sql` → the module in `src/<area>.rs`
+ → edit the generated SQL file(s) → the module in `src/<area>.rs`
(or `src/<area>/`) → `nix develop --command just prepare_db`.
- Add a query to an existing table: the module in `src/<area>.rs` → its tests
→ `nix develop --command just prepare_db` if cache metadata is missing.
diff --git a/crates/macro_db_client/migrations/20261015214828_notification_device_native_call_capability.sql b/crates/macro_db_client/migrations/20261015214828_notification_device_native_call_capability.sql
new file mode 100644
index 0000000000..7be7f97960
--- /dev/null
+++ b/crates/macro_db_client/migrations/20261015214828_notification_device_native_call_capability.sql
@@ -0,0 +1,4 @@
+-- Existing binaries omit this capability and must retain ordinary Android alerts.
+SET LOCAL lock_timeout = '5s';
+ALTER TABLE notification_user_device_registration
+ ADD COLUMN native_call_capable BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/crates/notification/src/domain/models.rs b/crates/notification/src/domain/models.rs
index 2bfb97b9f8..9734c7377e 100644
--- a/crates/notification/src/domain/models.rs
+++ b/crates/notification/src/domain/models.rs
@@ -27,7 +27,7 @@ pub use rate_limit::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimit
pub use recipient::{ExclusionReason, FilteredRecipient, RecipientExclusion};
pub use request::{NotificationResult, SendNotificationRequest, SendNotificationRequestBuilder};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
-use std::{borrow::Cow, sync::Arc};
+use std::{borrow::Cow, collections::HashSet, sync::Arc};
use uuid::Uuid;
/// Notification ID paired with its APNS collapse key, for push clearing.
@@ -44,8 +44,26 @@ pub struct NotificationIdAndCollapseKey {
pub struct VoipPushTarget {
/// Recipient whose VoIP-capable endpoints were resolved.
pub recipient_id: MacroUserIdStr<'static>,
- /// SNS endpoints registered for APNS_VOIP delivery.
- pub endpoint_arns: Vec<String>,
+ /// Registered mobile endpoints, retaining ordinary devices for fallback decisions.
+ pub endpoints: Vec<DeviceEndpoint>,
+}
+
+/// Recipients grouped by mobile platform for delivery or exclusion.
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MobilePushRecipients {
+ /// Users whose iOS devices are included.
+ pub ios: HashSet<MacroUserIdStr<'static>>,
+ /// Users whose Android devices are included.
+ pub android: HashSet<MacroUserIdStr<'static>>,
+}
+
+/// Native call delivery results used to select ordinary mobile fallbacks.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub struct NativeCallPushResult {
+ /// Users with a successful native delivery on each platform.
+ pub delivered: MobilePushRecipients,
+ /// Users whose registered mobile platforms were all handled natively.
+ pub fully_delivered: HashSet<MacroUserIdStr<'static>>,
}
/// A compact patch describing user notification status fields that changed.
diff --git a/crates/notification/src/domain/models/device.rs b/crates/notification/src/domain/models/device.rs
index 6a358a94b8..144b7862c6 100644
--- a/crates/notification/src/domain/models/device.rs
+++ b/crates/notification/src/domain/models/device.rs
@@ -28,4 +28,7 @@ pub struct DeviceRequest {
pub device_type: DeviceType,
/// The device push notification token.
pub token: String,
+ /// Whether this Android binary supports native Telecom incoming calls.
+ #[serde(default)]
+ pub native_call_capable: bool,
}
diff --git a/crates/notification/src/domain/models/mobile.rs b/crates/notification/src/domain/models/mobile.rs
index aaca23a900..ba54f64722 100644
--- a/crates/notification/src/domain/models/mobile.rs
+++ b/crates/notification/src/domain/models/mobile.rs
@@ -71,10 +71,12 @@ pub enum PushType {
}
/// A device endpoint for push notifications.
-#[derive(Debug, Clone)]
+#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeviceEndpoint {
- /// Android device endpoint (FCM).
+ /// Android FCM endpoint without native call support (including older APKs).
Android(String),
+ /// Android endpoint registered by a binary with native Telecom call support.
+ AndroidNativeCall(String),
/// iOS device endpoint (APNS).
Ios(String),
/// iOS VoIP device endpoint (APNS_VOIP / PushKit).
diff --git a/crates/notification/src/domain/models/request.rs b/crates/notification/src/domain/models/request.rs
index 77cff9de7f..beab3b3f54 100644
--- a/crates/notification/src/domain/models/request.rs
+++ b/crates/notification/src/domain/models/request.rs
@@ -1,8 +1,8 @@
//! Request and response models for the notification service.
use crate::domain::models::{
- ExclusionReason, FilteredRecipient, Notification, NotificationExtEmail, NotificationExtIos,
- RecipientExclusion, TaggedContent,
+ ExclusionReason, FilteredRecipient, MobilePushRecipients, Notification, NotificationExtEmail,
+ NotificationExtIos, RecipientExclusion, TaggedContent,
apple::APNSPushNotification,
mobile::{self, MessageAttributes},
queue_message::EmailCreateBundle,
@@ -86,6 +86,7 @@ where
build_apns: None,
build_email: None,
send_conn_gateway: false,
+ mobile_push_exclusions: MobilePushRecipients::default(),
}
}
}
@@ -111,6 +112,9 @@ pub struct SendNotificationRequest<'a, T, U> {
pub(crate) build_email: Option<EmailCreateBundle>,
/// connection gateway accepts arbitrary json so we just ask if its enabled or not
pub(crate) send_conn_gateway: bool,
+ /// Platforms already handled by another delivery path for these recipients.
+ #[serde(default)]
+ pub(crate) mobile_push_exclusions: MobilePushRecipients,
}
impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
@@ -122,6 +126,7 @@ impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
build_email,
uuid_to_write,
send_conn_gateway,
+ mobile_push_exclusions,
} = self;
let sender = req.sender_id.clone().map(CowLike::into_owned);
@@ -152,6 +157,7 @@ impl<'a, T: NotificationExtIos, U> SendNotificationRequest<'a, T, U> {
build_apns,
build_email,
send_conn_gateway,
+ mobile_push_exclusions,
}
}
}
@@ -173,6 +179,14 @@ impl<'a, T: Notification, U> SendNotificationRequest<'a, T, U> {
}
impl<'a, T, U> SendNotificationRequest<'a, T, U> {
+ /// Skip ordinary mobile alerts for recipients already handled on that platform.
+ /// Android exclusions apply only to devices registered with native call support;
+ /// older APKs always retain ordinary alerts. Other channels and persistence are unchanged.
+ pub fn with_mobile_push_exclusions(mut self, recipients: MobilePushRecipients) -> Self {
+ self.mobile_push_exclusions = recipients;
+ self
+ }
+
pub(crate) fn update_recipients(
mut self,
muted_users: HashSet<MacroUserIdStr<'a>>,
diff --git a/crates/notification/src/domain/ports.rs b/crates/notification/src/domain/ports.rs
index 538966f1bd..94779f8fcc 100644
--- a/crates/notification/src/domain/ports.rs
+++ b/crates/notification/src/domain/ports.rs
@@ -22,8 +22,9 @@ use crate::domain::models::{NotificationStatusPayload, TaggedContent};
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
use crate::domain::models::request::{NotificationListFilters, NotificationStatus};
use crate::domain::models::{
- DeviceEndpoint, DisabledNotificationType, NotificationExtEmail, NotificationIdAndCollapseKey,
- SendNotificationRequestBuilder, UserNotificationRow, VoipPushTarget,
+ DeviceEndpoint, DisabledNotificationType, NativeCallPushResult, NotificationExtEmail,
+ NotificationIdAndCollapseKey, SendNotificationRequestBuilder, UserNotificationRow,
+ VoipPushTarget,
android::FCMMessage,
apple::{APNSPushNotification, VoipPushPayload},
mobile::MessageAttributes,
@@ -231,6 +232,7 @@ pub trait NotificationRepository: Send + Sync + 'static {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> impl Future<Output = Result<(), Report>> + Send;
/// Delete all of the user's device registrations matching the given token
@@ -555,11 +557,12 @@ pub trait VoipPushDelivery: Send + Sync + 'static {
fn send_voip_push(
&self,
endpoint_arn: &str,
+ recipient_id: &MacroUserIdStr<'_>,
payload: &VoipPushPayload,
) -> impl Future<Output = Result<String, Report>> + Send;
}
-/// Port for sending VoIP push notifications (PushKit / CallKit) to iOS devices.
+/// Port for sending native call pushes to iOS PushKit and Android FCM devices.
///
/// VoIP pushes bypass the regular notification pipeline — they are delivered
/// immediately without DB persistence and wake the app via PushKit so that
@@ -573,12 +576,13 @@ pub trait VoipPushSender: Send + Sync + 'static {
/// Send recipient-specific payloads to already-resolved VoIP endpoints.
///
- /// Errors are logged but do not propagate. The returned set contains users
- /// that received at least one successful VoIP push delivery.
+ /// Errors are logged but do not propagate. Successful deliveries suppress
+ /// ordinary alerts only on the corresponding platform. Users whose mobile
+ /// platforms are all handled natively need no fallback notification row.
fn send_voip_pushes(
&self,
pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
- ) -> impl std::future::Future<Output = HashSet<MacroUserIdStr<'static>>> + Send;
+ ) -> impl std::future::Future<Output = NativeCallPushResult> + Send;
}
impl VoipPushSender for () {
@@ -592,8 +596,8 @@ impl VoipPushSender for () {
async fn send_voip_pushes(
&self,
_: Vec<(VoipPushTarget, VoipPushPayload)>,
- ) -> HashSet<MacroUserIdStr<'static>> {
- HashSet::new()
+ ) -> NativeCallPushResult {
+ NativeCallPushResult::default()
}
}
@@ -612,11 +616,11 @@ impl<V: VoipPushSender> VoipPushSender for Option<V> {
async fn send_voip_pushes(
&self,
pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
- ) -> HashSet<MacroUserIdStr<'static>> {
+ ) -> NativeCallPushResult {
if let Some(inner) = self {
inner.send_voip_pushes(pushes).await
} else {
- HashSet::new()
+ NativeCallPushResult::default()
}
}
}
diff --git a/crates/notification/src/domain/service/device/test.rs b/crates/notification/src/domain/service/device/test.rs
index 6c220100d1..64a20252aa 100644
--- a/crates/notification/src/domain/service/device/test.rs
+++ b/crates/notification/src/domain/service/device/test.rs
@@ -18,7 +18,7 @@ fn test_user_id() -> MacroUserIdStr<'static> {
/// Mock NotificationRepository that only implements device-related methods.
struct MockNotifRepo {
existing_endpoint: Mutex<Option<String>>,
- upserted: Mutex<Vec<(String, String, String, String)>>,
+ upserted: Mutex<Vec<(String, String, String, String, bool)>>,
deleted_token_result: Mutex<Result<Vec<String>, &'static str>>,
deleted_token_calls: Mutex<Vec<(String, String)>>,
stale_endpoints: Mutex<Vec<String>>,
@@ -88,12 +88,14 @@ impl NotificationRepository for MockNotifRepo {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
self.upserted.lock().unwrap().push((
user_id.to_string(),
device_token.to_string(),
device_endpoint.to_string(),
format!("{device_type:?}"),
+ native_call_capable,
));
Ok(())
}
@@ -436,6 +438,7 @@ async fn register_existing_token_valid_endpoint() {
MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),
"device-token",
&DeviceType::Ios,
+ false,
)
.await
.unwrap();
@@ -452,7 +455,7 @@ async fn register_missing_token_creates_endpoint() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "device-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "device-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -468,7 +471,7 @@ async fn register_get_attributes_fails_creates_new_endpoint() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "device-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "device-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -486,7 +489,7 @@ async fn register_disabled_endpoint_re_enables() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "device-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "device-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -506,7 +509,7 @@ async fn register_token_mismatch_updates() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "new-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "new-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -522,7 +525,7 @@ async fn register_ios_uses_apns_arn() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "token", &DeviceType::Ios)
+ .register_device(test_user_id(), "token", &DeviceType::Ios, false)
.await
.unwrap();
}
@@ -534,7 +537,7 @@ async fn register_android_uses_fcm_arn() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "token", &DeviceType::Android)
+ .register_device(test_user_id(), "token", &DeviceType::Android, false)
.await
.unwrap();
}
@@ -547,7 +550,7 @@ async fn register_prunes_stale_registrations_for_token() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "device-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "device-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -569,7 +572,7 @@ async fn register_succeeds_when_stale_sns_delete_fails() {
let service = make_service(db, sns);
service
- .register_device(test_user_id(), "device-token", &DeviceType::Ios)
+ .register_device(test_user_id(), "device-token", &DeviceType::Ios, false)
.await
.unwrap();
@@ -660,3 +663,31 @@ async fn unregister_db_error_propagates() {
let deleted = service.sns_endpoint.deleted.lock().unwrap();
assert!(deleted.is_empty());
}
+
+#[tokio::test]
+async fn native_call_capability_is_honored_only_for_android_and_can_be_revoked() {
+ for device_type in [DeviceType::Android, DeviceType::Ios, DeviceType::IosVoip] {
+ let service = make_service(MockNotifRepo::empty(), MockSnsManager::new());
+ service
+ .register_device(test_user_id(), "device-token", &device_type, true)
+ .await
+ .unwrap();
+ service
+ .register_device(test_user_id(), "device-token", &device_type, false)
+ .await
+ .unwrap();
+ let upserted = service.repository.upserted.lock().unwrap();
+ assert_eq!(upserted[0].4, matches!(device_type, DeviceType::Android));
+ assert!(!upserted[1].4);
+ }
+}
+
+#[test]
+fn existing_device_registration_payloads_default_to_no_native_call_capability() {
+ let request: crate::domain::models::device::DeviceRequest =
+ serde_json::from_value(serde_json::json!({
+ "deviceType": "android", "token": "device-token"
+ }))
+ .unwrap();
+ assert!(!request.native_call_capable);
+}
diff --git a/crates/notification/src/domain/service/ingress.rs b/crates/notification/src/domain/service/ingress.rs
index 2a6caf745c..befc24bdee 100644
--- a/crates/notification/src/domain/service/ingress.rs
+++ b/crates/notification/src/domain/service/ingress.rs
@@ -18,8 +18,9 @@ use crate::domain::models::request::{
UpdateNotificationsRequest,
};
use crate::domain::models::{
- DeviceEndpoint, DisabledNotificationType, Notification, NotificationResult,
- NotificationStatusPayload, NotificationTypeName, PatchDelete, UserNotificationRow,
+ DeviceEndpoint, DisabledNotificationType, MobilePushRecipients, Notification,
+ NotificationResult, NotificationStatusPayload, NotificationTypeName, PatchDelete,
+ UserNotificationRow,
};
use crate::domain::ports::{
NoopNotificationRealtimePublisher, NotificationIngressQueue, NotificationQueue,
@@ -133,6 +134,7 @@ pub trait NotificationReader: Send + Sync + 'static {
user_id: MacroUserIdStr<'_>,
device_token: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
/// Unregister the user's device from push notifications.
@@ -384,7 +386,8 @@ where
.await
.context(SendNotificationError::Other)?;
- let mobile_endpoints = group_mobile_endpoints(device_endpoints);
+ let mobile_endpoints =
+ group_mobile_endpoints(device_endpoints, &notification.mobile_push_exclusions);
if !mobile_endpoints.is_empty() {
let BuildApnsOutput { notif, attr } = build_apns;
@@ -560,7 +563,8 @@ where
.get_device_endpoints(&[req.user_id.copied()])
.await?;
- let mobile_endpoints = group_mobile_endpoints(device_endpoints);
+ let mobile_endpoints =
+ group_mobile_endpoints(device_endpoints, &MobilePushRecipients::default());
if mobile_endpoints.is_empty() {
return deserialize_updated_notifications(changed);
@@ -613,6 +617,7 @@ where
/// no push-capable device. VoIP endpoints are delivered separately.
fn group_mobile_endpoints(
device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,
+ exclusions: &MobilePushRecipients,
) -> HashMap<MacroUserIdStr<'static>, UserApnsEndpoints> {
device_endpoints
.into_iter()
@@ -623,9 +628,18 @@ fn group_mobile_endpoints(
match endpoint {
DeviceEndpoint::Ios(arn) => ios.push(arn),
DeviceEndpoint::Android(arn) => android.push(arn),
+ DeviceEndpoint::AndroidNativeCall(arn)
+ if !exclusions.android.contains(&user_id) =>
+ {
+ android.push(arn)
+ }
+ DeviceEndpoint::AndroidNativeCall(_) => {}
DeviceEndpoint::IosVoip(_) => {}
}
}
+ if exclusions.ios.contains(&user_id) {
+ ios.clear();
+ }
if ios.is_empty() && android.is_empty() {
return None;
}
@@ -843,6 +857,7 @@ where
user_id: MacroUserIdStr<'_>,
device_token: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
let platform_arn: &str = match device_type {
DeviceType::Ios => self.platform_config.apns_platform_arn.as_str(),
@@ -892,7 +907,13 @@ where
};
self.repository
- .upsert_device(user_id, device_token, &endpoint, device_type)
+ .upsert_device(
+ user_id,
+ device_token,
+ &endpoint,
+ device_type,
+ native_call_capable && matches!(device_type, DeviceType::Android),
+ )
.await?;
// A device token must map to a single registration. When SNS minted a
diff --git a/crates/notification/src/domain/service/push_notification_event/test.rs b/crates/notification/src/domain/service/push_notification_event/test.rs
index d09ff81bc7..17a90d2a10 100644
--- a/crates/notification/src/domain/service/push_notification_event/test.rs
+++ b/crates/notification/src/domain/service/push_notification_event/test.rs
@@ -221,6 +221,7 @@ impl NotificationRepository for MockNotifRepo {
_: &str,
_: &str,
_: &crate::domain::models::device::DeviceType,
+ _native_call_capable: bool,
) -> Result<(), Report> {
unimplemented!()
}
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index b6007a3a8e..c1f034b558 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -518,6 +518,7 @@ impl NotificationRepository for MockRepository {
_device_token: &str,
_device_endpoint: &str,
_device_type: &DeviceType,
+ _native_call_capable: bool,
) -> Result<(), Report> {
Ok(())
}
@@ -777,9 +778,16 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
(**self)
- .upsert_device(user_id, device_token, device_endpoint, device_type)
+ .upsert_device(
+ user_id,
+ device_token,
+ device_endpoint,
+ device_type,
+ native_call_capable,
+ )
.await
}
diff --git a/crates/notification/src/domain/service/test/android.rs b/crates/notification/src/domain/service/test/android.rs
index 944b6431b6..edf1a954ec 100644
--- a/crates/notification/src/domain/service/test/android.rs
+++ b/crates/notification/src/domain/service/test/android.rs
@@ -5,7 +5,7 @@ use crate::domain::models::email_notification_digest::{
BatchSend, BulkDigestEgressStateMachine, DontSend, ResumeMachineBRequest,
};
use crate::domain::models::mobile::MessageAttributes;
-use crate::domain::models::queue_message::DeliverySuccess;
+use crate::domain::models::queue_message::{DeliverySuccess, UserApnsEndpoints};
#[tokio::test]
async fn queues_android_and_ios_together_after_recipient_filtering() {
@@ -240,3 +240,159 @@ async fn seen_and_done_deliver_silent_clear_to_android_only_users() {
assert!(android[0].1["body"].is_null());
}
}
+
+#[tokio::test]
+async fn native_call_exclusions_keep_only_unhandled_mobile_platforms() {
+ use crate::domain::models::MobilePushRecipients;
+ use crate::domain::models::queue_message::IngressQueueMessage;
+
+ for (ios, android) in [(false, false), (true, false), (false, true), (true, true)] {
+ let user = test_user_id("[email protected]");
+ let exclusions = MobilePushRecipients {
+ ios: if ios {
+ HashSet::from([user.clone()])
+ } else {
+ HashSet::new()
+ },
+ android: if android {
+ HashSet::from([user.clone()])
+ } else {
+ HashSet::new()
+ },
+ };
+ let repo = Arc::new(
+ MockRepository::new()
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Ios("ios".into()))
+ .with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::AndroidNativeCall("android".into()),
+ ),
+ );
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationIngressService::new(repo, queue.clone(), MockStateMachine);
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("doc"),
+ secondary_notification_entity: None,
+ notification: TestNotification {
+ message: "Hello".into(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([user.clone()]),
+ }
+ .into_request()
+ .with_mobile_push_exclusions(exclusions.clone())
+ .with_apns()
+ .with_conn_gateway();
+ // Production crosses the ingress queue as a type-erased serialized request.
+ let queued = IngressQueueMessage::from_request(&request).unwrap();
+ assert_eq!(queued.request.mobile_push_exclusions, exclusions);
+ service.process_from_queue(queued.request).await.unwrap();
+ let published = queue.get_published();
+ assert!(
+ published
+ .iter()
+ .any(|message| message["content"]["ConnGateway"].is_object())
+ );
+ let mobile = published
+ .iter()
+ .find(|message| message["content"]["Ios"].is_object());
+ if ios && android {
+ assert!(mobile.is_none());
+ } else {
+ let endpoints: UserApnsEndpoints = serde_json::from_value(
+ mobile.unwrap()["content"]["Ios"]["ios_device_endpoints"][user.as_ref()].clone(),
+ )
+ .unwrap();
+ assert_eq!(
+ endpoints.endpoints,
+ if ios {
+ Vec::<String>::new()
+ } else {
+ vec!["ios".into()]
+ }
+ );
+ assert_eq!(
+ endpoints.android_endpoints,
+ if android {
+ Vec::<String>::new()
+ } else {
+ vec!["android".into()]
+ }
+ );
+ }
+ }
+}
+
+#[test]
+fn queued_requests_without_mobile_exclusions_keep_existing_delivery() {
+ use crate::domain::models::MobilePushRecipients;
+ use crate::domain::models::queue_message::IngressQueueMessage;
+ let request = SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("doc"),
+ secondary_notification_entity: None,
+ notification: TestNotification {
+ message: "Hello".into(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([test_user_id("[email protected]")]),
+ }
+ .into_request()
+ .with_apns();
+ let mut serialized =
+ serde_json::to_value(IngressQueueMessage::from_request(&request).unwrap()).unwrap();
+ serialized["request"]
+ .as_object_mut()
+ .unwrap()
+ .remove("mobile_push_exclusions");
+ let decoded: IngressQueueMessage = serde_json::from_value(serialized).unwrap();
+ assert_eq!(
+ decoded.request.mobile_push_exclusions,
+ MobilePushRecipients::default()
+ );
+}
+
+#[tokio::test]
+async fn native_android_exclusion_preserves_ordinary_alerts_for_legacy_devices() {
+ use crate::domain::models::MobilePushRecipients;
+ let user = test_user_id("[email protected]");
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationIngressService::new(
+ MockRepository::new()
+ .with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::Android("legacy-android".into()),
+ )
+ .with_device_endpoint(
+ user.clone(),
+ DeviceEndpoint::AndroidNativeCall("native-android".into()),
+ ),
+ queue.clone(),
+ MockStateMachine,
+ );
+ service
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: EntityType::Document.with_entity_str("doc"),
+ secondary_notification_entity: None,
+ notification: TestNotification {
+ message: "Hello".into(),
+ },
+ sender_id: None,
+ recipient_ids: HashSet::from([user.clone()]),
+ }
+ .into_request()
+ .with_apns()
+ .with_mobile_push_exclusions(MobilePushRecipients {
+ ios: HashSet::new(),
+ android: HashSet::from([user.clone()]),
+ }),
+ )
+ .await
+ .unwrap();
+ let published = queue.get_published();
+ assert_eq!(published.len(), 1);
+ assert_eq!(
+ published[0]["content"]["Ios"]["ios_device_endpoints"][user.as_ref()]["android_endpoints"],
+ json!(["legacy-android"])
+ );
+}
diff --git a/crates/notification/src/domain/service/voip.rs b/crates/notification/src/domain/service/voip.rs
index eb1b162b80..b9bfeaae49 100644
--- a/crates/notification/src/domain/service/voip.rs
+++ b/crates/notification/src/domain/service/voip.rs
@@ -1,7 +1,7 @@
-//! VoIP push notification service.
+//! Native call 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.
+//! Delivers iOS PushKit and Android FCM call pushes directly, without queueing
+//! or DB persistence. Native clients own incoming-call presentation.
#[cfg(test)]
mod test;
@@ -9,16 +9,15 @@ mod test;
use futures::future;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
-use std::collections::HashSet;
-use crate::domain::models::VoipPushTarget;
use crate::domain::models::apple::VoipPushPayload;
use crate::domain::models::mobile::DeviceEndpoint;
+use crate::domain::models::{NativeCallPushResult, VoipPushTarget};
use crate::domain::ports::{NotificationRepository, VoipPushDelivery, VoipPushSender};
const VOIP_PUSH_DELIVERY_CONCURRENCY: usize = 32;
-/// Direct APNS_VOIP sender for CallKit pushes.
+/// Direct sender for iOS and Android native call pushes.
pub struct VoipPushServiceImpl<R, M> {
repository: R,
mobile: M,
@@ -45,18 +44,18 @@ where
Ok(device_map
.into_iter()
.filter_map(|(recipient_id, endpoints)| {
- let endpoint_arns: Vec<String> = endpoints
- .into_iter()
- .filter_map(|endpoint| match endpoint {
- DeviceEndpoint::IosVoip(arn) => Some(arn),
- _ => None,
+ endpoints
+ .iter()
+ .any(|endpoint| {
+ matches!(
+ endpoint,
+ DeviceEndpoint::IosVoip(_) | DeviceEndpoint::AndroidNativeCall(_)
+ )
+ })
+ .then_some(VoipPushTarget {
+ recipient_id,
+ endpoints,
})
- .collect();
-
- (!endpoint_arns.is_empty()).then_some(VoipPushTarget {
- recipient_id,
- endpoint_arns,
- })
})
.collect())
}
@@ -64,26 +63,55 @@ where
async fn send_voip_pushes(
&self,
pushes: Vec<(VoipPushTarget, VoipPushPayload)>,
- ) -> HashSet<MacroUserIdStr<'static>> {
- let jobs: Vec<(MacroUserIdStr<'static>, String, VoipPushPayload)> = pushes
+ ) -> NativeCallPushResult {
+ let platforms: Vec<_> = pushes
+ .iter()
+ .map(|(target, _)| {
+ (
+ target.recipient_id.clone(),
+ target.endpoints.iter().any(|endpoint| {
+ matches!(
+ endpoint,
+ DeviceEndpoint::Ios(_) | DeviceEndpoint::IosVoip(_)
+ )
+ }),
+ target.endpoints.iter().any(|endpoint| {
+ matches!(
+ endpoint,
+ DeviceEndpoint::Android(_) | DeviceEndpoint::AndroidNativeCall(_)
+ )
+ }),
+ target
+ .endpoints
+ .iter()
+ .any(|endpoint| matches!(endpoint, DeviceEndpoint::Android(_))),
+ )
+ })
+ .collect();
+ let jobs: Vec<(MacroUserIdStr<'static>, DeviceEndpoint, VoipPushPayload)> = pushes
.into_iter()
.flat_map(|(target, payload)| {
let recipient_id = target.recipient_id;
target
- .endpoint_arns
+ .endpoints
.into_iter()
- .map(move |arn| (recipient_id.clone(), arn, payload.clone()))
+ .map(move |endpoint| (recipient_id.clone(), endpoint, payload.clone()))
})
.collect();
- let mut delivered = HashSet::new();
+ let mut result = NativeCallPushResult::default();
for batch in jobs.chunks(VOIP_PUSH_DELIVERY_CONCURRENCY) {
- let results = future::join_all(batch.iter().map(|(user_id, arn, payload)| {
+ let results = future::join_all(batch.iter().map(|(user_id, endpoint, payload)| {
let user_id = user_id.clone();
async move {
let mobile = &self.mobile;
- match mobile.send_voip_push(arn, payload).await {
- Ok(_) => Some(user_id),
+ let (arn, ios) = match endpoint {
+ DeviceEndpoint::IosVoip(arn) => (arn, true),
+ DeviceEndpoint::AndroidNativeCall(arn) => (arn, false),
+ DeviceEndpoint::Ios(_) | DeviceEndpoint::Android(_) => return None,
+ };
+ match mobile.send_voip_push(arn, &user_id, payload).await {
+ Ok(_) => Some((user_id, ios)),
Err(e) => {
tracing::error!(
error=?e,
@@ -95,9 +123,24 @@ where
}
}))
.await;
- delivered.extend(results.into_iter().flatten());
+ for (user_id, ios) in results.into_iter().flatten() {
+ if ios {
+ result.delivered.ios.insert(user_id);
+ } else {
+ result.delivered.android.insert(user_id);
+ }
+ }
}
- delivered
+ result.fully_delivered = platforms
+ .into_iter()
+ .filter_map(|(user_id, ios, android, legacy_android)| {
+ (!legacy_android
+ && (!ios || result.delivered.ios.contains(&user_id))
+ && (!android || result.delivered.android.contains(&user_id)))
+ .then_some(user_id)
+ })
+ .collect();
+ result
}
}
diff --git a/crates/notification/src/domain/service/voip/test.rs b/crates/notification/src/domain/service/voip/test.rs
index 7c80b1c633..467f06495e 100644
--- a/crates/notification/src/domain/service/voip/test.rs
+++ b/crates/notification/src/domain/service/voip/test.rs
@@ -89,6 +89,7 @@ impl NotificationRepository for MockRepo {
_: &str,
_: &str,
_: &crate::domain::models::device::DeviceType,
+ _native_call_capable: bool,
) -> Result<(), Report> {
unimplemented!()
}
@@ -270,6 +271,7 @@ impl NotificationRepository for MockRepo {
struct MockPush {
calls: Arc<Mutex<Vec<String>>>,
should_fail: bool,
+ failing_endpoints: HashSet<String>,
}
impl MockPush {
@@ -277,6 +279,7 @@ impl MockPush {
Self {
calls,
should_fail: false,
+ failing_endpoints: HashSet::new(),
}
}
@@ -284,6 +287,7 @@ impl MockPush {
Self {
calls: Arc::new(Mutex::new(Vec::new())),
should_fail: true,
+ failing_endpoints: HashSet::new(),
}
}
}
@@ -295,7 +299,7 @@ impl MobilePushOps for MockPush {
_: &SnsTarget<'_, T>,
_: HashMap<String, MessageAttributeValue>,
) -> Result<String, Report> {
- if self.should_fail {
+ if self.should_fail || self.failing_endpoints.contains(endpoint_arn) {
return Err(rootcause::report!("SNS error"));
}
self.calls.lock().unwrap().push(endpoint_arn.to_string());
@@ -345,20 +349,22 @@ async fn dispatches_to_ios_voip_endpoint() {
assert_eq!(*calls.lock().unwrap(), vec!["arn:voip-alice"]);
assert_eq!(
- result,
+ result.fully_delivered,
std::collections::HashSet::from([user("[email protected]")])
);
}
#[tokio::test]
-async fn skips_non_voip_endpoints() {
+async fn targets_android_calls_but_skips_regular_ios_endpoints() {
let (push, calls) = tracked_push();
let svc = make_service(
MockRepo::with_endpoints(HashMap::from([(
vec![
DeviceEndpoint::Ios("arn:apns-bob".to_string()),
- DeviceEndpoint::Android("arn:fcm-bob".to_string()),
+ DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".to_string(),
+ ),
],
)])),
push,
@@ -369,8 +375,22 @@ async fn skips_non_voip_endpoints() {
.await
.unwrap();
- assert!(targets.is_empty());
- assert!(calls.lock().unwrap().is_empty());
+ assert_eq!(targets.len(), 1);
+ assert!(matches!(
+ targets[0].endpoints.as_slice(),
+ [DeviceEndpoint::Ios(_), DeviceEndpoint::AndroidNativeCall(arn)] if arn == "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob"
+ ));
+ let delivered = svc
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
+ .await;
+ // Android delivery cannot replace the ordinary iOS alert on another device.
+ assert!(delivered.fully_delivered.is_empty());
+ assert!(delivered.delivered.ios.is_empty());
+ assert_eq!(
+ delivered.delivered.android,
+ HashSet::from([user("[email protected]")])
+ );
+ assert_eq!(calls.lock().unwrap().len(), 1);
}
#[tokio::test]
@@ -404,5 +424,192 @@ async fn sns_failure_does_not_panic() {
.send_voip_pushes(vec![(targets[0].clone(), payload())])
.await;
- assert!(result.is_empty());
+ assert_eq!(
+ result,
+ crate::domain::models::NativeCallPushResult::default()
+ );
+}
+
+#[tokio::test]
+async fn android_delivery_does_not_suppress_apns_when_ios_voip_fails() {
+ let (mut push, calls) = tracked_push();
+ push.failing_endpoints.insert("arn:voip-bob".to_string());
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(
+ vec![
+ DeviceEndpoint::Ios("arn:apns-bob".to_string()),
+ DeviceEndpoint::IosVoip("arn:voip-bob".to_string()),
+ DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".to_string(),
+ ),
+ ],
+ )])),
+ push,
+ );
+
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ let suppress_apns = svc
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
+ .await;
+
+ assert!(suppress_apns.fully_delivered.is_empty());
+ assert!(suppress_apns.delivered.ios.is_empty());
+ assert_eq!(
+ suppress_apns.delivered.android,
+ HashSet::from([user("[email protected]")])
+ );
+ assert_eq!(
+ *calls.lock().unwrap(),
+ vec!["arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob"]
+ );
+}
+
+#[tokio::test]
+async fn successful_ios_voip_delivery_suppresses_apns_when_android_fails() {
+ let (mut push, calls) = tracked_push();
+ push.failing_endpoints
+ .insert("arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".to_string());
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(
+ vec![
+ DeviceEndpoint::IosVoip("arn:voip-bob".to_string()),
+ DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".to_string(),
+ ),
+ ],
+ )])),
+ push,
+ );
+
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ let suppress_apns = svc
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
+ .await;
+
+ assert!(suppress_apns.fully_delivered.is_empty());
+ assert!(suppress_apns.delivered.android.is_empty());
+ assert_eq!(
+ suppress_apns.delivered.ios,
+ HashSet::from([user("[email protected]")])
+ );
+ assert_eq!(*calls.lock().unwrap(), vec!["arn:voip-bob"]);
+}
+
+#[tokio::test]
+async fn successful_native_delivery_on_all_registered_platforms_needs_no_fallback_row() {
+ for endpoints in [
+ vec![DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".into(),
+ )],
+ vec![
+ DeviceEndpoint::Ios("arn:apns-bob".into()),
+ DeviceEndpoint::IosVoip("arn:voip-bob".into()),
+ ],
+ vec![
+ DeviceEndpoint::Ios("arn:apns-bob".into()),
+ DeviceEndpoint::IosVoip("arn:voip-bob".into()),
+ DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".into(),
+ ),
+ ],
+ ] {
+ let (push, _) = tracked_push();
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(user("[email protected]"), endpoints)])),
+ push,
+ );
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ let result = svc
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
+ .await;
+ assert_eq!(
+ result.fully_delivered,
+ HashSet::from([user("[email protected]")])
+ );
+ }
+}
+
+#[tokio::test]
+async fn ordinary_ios_only_users_do_not_need_native_call_tokens() {
+ let (push, calls) = tracked_push();
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(
+ vec![DeviceEndpoint::Ios("arn:apns-bob".into())],
+ )])),
+ push,
+ );
+ assert!(
+ svc.get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn legacy_android_devices_are_not_native_call_targets() {
+ let (push, calls) = tracked_push();
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(
+ vec![DeviceEndpoint::Android("legacy-android".into())],
+ )])),
+ push,
+ );
+ assert!(
+ svc.get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert!(calls.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn native_android_success_keeps_legacy_android_fallback_on_the_same_account() {
+ let (push, calls) = tracked_push();
+ let svc = make_service(
+ MockRepo::with_endpoints(HashMap::from([(
+ vec![
+ DeviceEndpoint::Android("legacy-android".into()),
+ DeviceEndpoint::AndroidNativeCall(
+ "arn:aws:sns:us-east-1:123:endpoint/GCM/macro/bob".into(),
+ ),
+ DeviceEndpoint::IosVoip("arn:voip-bob".into()),
+ ],
+ )])),
+ push,
+ );
+ let targets = svc
+ .get_voip_push_targets(&[user("[email protected]")])
+ .await
+ .unwrap();
+ let result = svc
+ .send_voip_pushes(vec![(targets[0].clone(), payload())])
+ .await;
+ assert!(result.fully_delivered.is_empty());
+ assert!(result.delivered.android.contains(&user("[email protected]")));
+ assert!(result.delivered.ios.contains(&user("[email protected]")));
+ assert_eq!(calls.lock().unwrap().len(), 2);
+ assert!(
+ !calls
+ .lock()
+ .unwrap()
+ .iter()
+ .any(|arn| arn == "legacy-android")
+ );
}
diff --git a/crates/notification/src/inbound/http/device.rs b/crates/notification/src/inbound/http/device.rs
index bb853f7099..ce7520c6f5 100644
--- a/crates/notification/src/inbound/http/device.rs
+++ b/crates/notification/src/inbound/http/device.rs
@@ -37,6 +37,7 @@ async fn register_device<S: NotificationReader, Auth: MacroAuthorizationService>
user.authorization.user.macro_user_id,
&req.token,
&req.device_type,
+ req.native_call_capable,
)
.await
.map_err(|e| {
diff --git a/crates/notification/src/inbound/http/test.rs b/crates/notification/src/inbound/http/test.rs
index 5bae4231bd..90c56dd24f 100644
--- a/crates/notification/src/inbound/http/test.rs
+++ b/crates/notification/src/inbound/http/test.rs
@@ -182,6 +182,7 @@ impl NotificationReader for AuthenticationTestService {
_user_id: MacroUserIdStr<'_>,
_device_token: &str,
_device_type: &DeviceType,
+ _native_call_capable: bool,
) -> impl Future<Output = Result<(), Report>> + Send {
async { unreachable!("should not be called") }
}
@@ -667,6 +668,7 @@ impl NotificationReader for PresignedTestService {
_user_id: MacroUserIdStr<'_>,
_device_token: &str,
_device_type: &DeviceType,
+ _native_call_capable: bool,
) -> impl Future<Output = Result<(), Report>> + Send {
async { unreachable!() }
}
diff --git a/crates/notification/src/outbound/device_registration.rs b/crates/notification/src/outbound/device_registration.rs
index a981ae4768..becb79910c 100644
--- a/crates/notification/src/outbound/device_registration.rs
+++ b/crates/notification/src/outbound/device_registration.rs
@@ -30,6 +30,7 @@ pub trait DeviceRegistrationDbOps: Send + Sync + 'static {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> impl std::future::Future<Output = Result<(), Report>> + Send;
/// Delete all of the user's registrations matching the token and type,
@@ -94,20 +95,22 @@ impl DeviceRegistrationDbOps for PgPool {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
let id = macro_uuid::generate_uuid_v7();
let user_id_str = user_id.as_ref();
sqlx::query!(
r#"
- INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type)
- VALUES ($1, $2, $3, $4, $5)
- ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, updated_at = NOW()
+ INSERT INTO notification_user_device_registration (id, user_id, device_token, device_endpoint, device_type, native_call_capable)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (device_endpoint) DO UPDATE SET user_id = $2, device_token = $3, device_type = $5, native_call_capable = $6, updated_at = NOW()
"#,
id,
user_id_str,
device_token,
device_endpoint,
DbDeviceType::from(device_type) as _,
+ native_call_capable,
)
.execute(self)
.await?;
diff --git a/crates/notification/src/outbound/mobile.rs b/crates/notification/src/outbound/mobile.rs
index 98818bf3ba..3ede4cacf9 100644
--- a/crates/notification/src/outbound/mobile.rs
+++ b/crates/notification/src/outbound/mobile.rs
@@ -122,12 +122,21 @@ impl<P: MobilePushOps + Send + Sync + 'static> MobilePushAdapter<P> {
/// 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))]
+ #[tracing::instrument(err, skip(self, recipient_id, payload))]
pub async fn send_voip_push(
&self,
endpoint_arn: &str,
+ recipient_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
payload: &VoipPushPayload,
) -> Result<String, Report> {
+ if endpoint_arn.contains(":endpoint/GCM/") {
+ let recipient = recipient_id.to_string();
+ let target: SnsTarget<'_, ()> = SnsTarget::AndroidCall(payload, &recipient);
+ return self
+ .push_service
+ .push_notification(endpoint_arn, &target, HashMap::new())
+ .await;
+ }
let voip_bundle_id = self.voip_bundle_id.as_deref().ok_or_else(|| {
rootcause::report!("voip_bundle_id not configured on MobilePushAdapter")
})?;
@@ -244,8 +253,9 @@ impl<P: MobilePushOps + Send + Sync + 'static> crate::domain::ports::VoipPushDel
async fn send_voip_push(
&self,
endpoint_arn: &str,
+ recipient_id: &macro_user_id::user_id::MacroUserIdStr<'_>,
payload: &VoipPushPayload,
) -> Result<String, Report> {
- MobilePushAdapter::send_voip_push(self, endpoint_arn, payload).await
+ MobilePushAdapter::send_voip_push(self, endpoint_arn, recipient_id, payload).await
}
}
diff --git a/crates/notification/src/outbound/mobile/payload.rs b/crates/notification/src/outbound/mobile/payload.rs
index fe696eb175..c97e3e9164 100644
--- a/crates/notification/src/outbound/mobile/payload.rs
+++ b/crates/notification/src/outbound/mobile/payload.rs
@@ -16,6 +16,8 @@ pub enum SnsTarget<'a, T> {
Ios(&'a APNSPushNotification<T>),
/// iOS VoIP target via APNS_VOIP.
Voip(&'a VoipPushPayload),
+ /// Data-only, short-lived Android incoming-call push and its recipient.
+ AndroidCall(&'a VoipPushPayload, &'a str),
/// Android target via FCM.
Android(&'a FCMMessage<T>),
}
@@ -46,6 +48,14 @@ pub(crate) enum SnsPayload<'a, T> {
#[serde(rename = "APNS_VOIP_SANDBOX", serialize_with = "stringified_json")]
apns_voip_sandbox: &'a VoipPushPayload,
},
+ /// Android incoming-call payload.
+ AndroidCall {
+ /// Default message text.
+ default: String,
+ /// FCM v1 envelope, serialized as an SNS platform string.
+ #[serde(rename = "GCM", serialize_with = "stringified_json")]
+ gcm: serde_json::Value,
+ },
/// Android payload with GCM key.
Android {
/// Default message text.
@@ -123,7 +133,9 @@ 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::Voip(payload) | SnsTarget::AndroidCall(payload, _) => {
+ format!("Incoming call in {}", payload.channel_name)
+ }
SnsTarget::Android(fcmmessage) => fcmmessage.title.clone().unwrap_or_default(),
}
}
@@ -140,6 +152,14 @@ impl<T> SnsTarget<'_, T> {
apns_voip: payload,
apns_voip_sandbox: payload,
},
+ SnsTarget::AndroidCall(payload, recipient) => SnsPayload::AndroidCall {
+ default: self.default_string(),
+ gcm: serde_json::json!({"fcmV1Message": {"message": {
+ "android": {"priority": "high", "ttl": "60s"},
+ "data": {"type": "call", "recipientId": recipient,
+ "payload": serde_json::to_string(payload).expect("call payload serializes")}
+ }}}),
+ },
SnsTarget::Android(fcmmessage) => SnsPayload::Android {
default: self.default_string(),
gcm: fcmmessage,
diff --git a/crates/notification/src/outbound/mobile/payload/test.rs b/crates/notification/src/outbound/mobile/payload/test.rs
index e8ce3a6a9e..a73f9d5fa7 100644
--- a/crates/notification/src/outbound/mobile/payload/test.rs
+++ b/crates/notification/src/outbound/mobile/payload/test.rs
@@ -91,3 +91,37 @@ fn payload_serialization_errors_are_returned_without_panicking() {
);
assert!(SnsTarget::Android(&notification).as_json().is_err());
}
+
+#[test]
+fn android_call_push_is_short_lived_data_only_and_recipient_scoped() {
+ let payload = VoipPushPayload {
+ aps: Default::default(),
+ call_id: Uuid::new_v4().to_string(),
+ channel_id: "channel-1".into(),
+ channel_name: "General".into(),
+ caller_name: "Alice".into(),
+ livekit_server_url: Some("wss://livekit.example".into()),
+ livekit_token: Some("recipient-token".into()),
+ ring_status_url: Some("https://dev.macro.com/call/ring-status/call-1".into()),
+ };
+ let target: SnsTarget<'_, ()> = SnsTarget::AndroidCall(&payload, "macro|[email protected]");
+ let sns: Value = serde_json::from_str(&target.as_json().unwrap()).unwrap();
+ assert!(sns.get("APNS_VOIP").is_none());
+ let fcm: Value = serde_json::from_str(sns["GCM"].as_str().unwrap()).unwrap();
+ let message = &fcm["fcmV1Message"]["message"];
+ assert_eq!(message["android"]["priority"], "high");
+ assert_eq!(message["android"]["ttl"], "60s");
+ assert!(message.get("notification").is_none());
+ assert_eq!(message["data"]["type"], "call");
+ assert_eq!(message["data"]["recipientId"], "macro|[email protected]");
+ assert!(
+ message["data"]
+ .as_object()
+ .unwrap()
+ .values()
+ .all(Value::is_string)
+ );
+ let offer: Value = serde_json::from_str(message["data"]["payload"].as_str().unwrap()).unwrap();
+ assert_eq!(offer["livekitToken"], "recipient-token");
+ assert_eq!(offer["callId"], payload.call_id);
+}
diff --git a/crates/notification/src/outbound/repository.rs b/crates/notification/src/outbound/repository.rs
index 470915304f..f500448af4 100644
--- a/crates/notification/src/outbound/repository.rs
+++ b/crates/notification/src/outbound/repository.rs
@@ -644,7 +644,7 @@ impl NotificationDbOps for PgPool {
let rows = sqlx::query!(
r#"
- SELECT user_id, device_endpoint, device_type as "device_type: DbDeviceType"
+ SELECT user_id, device_endpoint, device_type as "device_type: DbDeviceType", native_call_capable
FROM notification_user_device_registration
WHERE user_id = ANY($1)
"#,
@@ -662,6 +662,9 @@ impl NotificationDbOps for PgPool {
let device = match row.device_type {
DbDeviceType::Ios => DeviceEndpoint::Ios(row.device_endpoint),
+ DbDeviceType::Android if row.native_call_capable => {
+ DeviceEndpoint::AndroidNativeCall(row.device_endpoint)
+ }
DbDeviceType::Android => DeviceEndpoint::Android(row.device_endpoint),
DbDeviceType::IosVoip => DeviceEndpoint::IosVoip(row.device_endpoint),
};
@@ -1847,9 +1850,16 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
self.db
- .upsert_device(user_id, device_token, device_endpoint, device_type)
+ .upsert_device(
+ user_id,
+ device_token,
+ device_endpoint,
+ device_type,
+ native_call_capable,
+ )
.await
}
diff --git a/crates/notification/src/outbound/repository/test.rs b/crates/notification/src/outbound/repository/test.rs
index 3edae28ca9..c2bde35078 100644
--- a/crates/notification/src/outbound/repository/test.rs
+++ b/crates/notification/src/outbound/repository/test.rs
@@ -1513,3 +1513,34 @@ async fn test_delete_all_user_notifications_does_not_affect_other_users(pool: Po
.unwrap();
assert_eq!(other_count, 1);
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("user_devices"))
+)]
+async fn android_native_call_capability_round_trips_and_can_be_cleared(pool: Pool<Postgres>) {
+ use crate::domain::models::device::DeviceType;
+ use crate::outbound::device_registration::DeviceRegistrationDbOps;
+ let user = test_user("[email protected]");
+ for capable in [true, false] {
+ pool.upsert_device(
+ user.clone(),
+ "native-token",
+ "native-endpoint",
+ &DeviceType::Android,
+ capable,
+ )
+ .await
+ .unwrap();
+ let devices = pool
+ .get_device_endpoints(std::slice::from_ref(&user))
+ .await
+ .unwrap();
+ let endpoints = &devices[&user];
+ assert!(endpoints.iter().any(|endpoint| match endpoint {
+ DeviceEndpoint::AndroidNativeCall(arn) => capable && arn == "native-endpoint",
+ DeviceEndpoint::Android(arn) => !capable && arn == "native-endpoint",
+ _ => false,
+ }));
+ }
+}
diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.md
index d68fd2dd4d..8eff5ce81f 100644
--- a/docs/agent-guide/calls.md
+++ b/docs/agent-guide/calls.md
@@ -176,3 +176,17 @@ Standalone instant and scheduled calls are excluded from team memory. They have
`Share with team` or `Team access` controls during the call or on the saved recording.
Signed-in participants keep direct access to their recordings, transcripts, and summaries;
joining a standalone call never makes its content available to the wider team.
+
+### Android native channel calls
+
+Android channel calls use a native call activity rather than browser media.
+After joining, the themed drawer shows a large participant tile and a horizontally
+scrolling participant strip; tap a strip tile to make it primary. Speaker toggles
+speaker mode (hold it for headset/Bluetooth routing), Mute and Video control capture, and **Leave** ends the call.
+The local primary video tile exposes Switch camera. Swipe the drawer handle down,
+tap outside the drawer, or use Back to enter PiP on supported devices; **Open call
+controls** in the web call controls restores the native surface. Leaving the channel does
+not end the call. Incoming calls expose Answer/Decline in the **Calls** notification
+channel, including while locked/backgrounded. PiP is a native, device-dependent
+flow. Browser-only tests cannot validate Telecom, FCM wakeup or background media;
+follow the hardware matrix in [Android development](../development/android.md#native-calling).
diff --git a/docs/development/android.md b/docs/development/android.md
index 6e175ec8df..fabb9d46ff 100644
--- a/docs/development/android.md
+++ b/docs/development/android.md
@@ -896,3 +896,87 @@ unit tests. Expired-session refresh, all pending-upload and queued-write logout
paths, actual large-document rendering/hydration, and physical memory-pressure,
battery, and cellular testing remain necessary for full Task 05 acceptance.
Play verification remains Task 07.
+
+## Native calling
+
+Channel calls use the Android `call-kit` plugin with a self-managed Telecom
+`ConnectionService` and a native LiveKit room. The WebView observes that room;
+reloading or navigating the web UI does not create another media session.
+Native calls require Android 8/API 26 or newer and an installed binary that
+advertises the call-kit plugin. Android 7 and older installed binaries keep the
+browser call controls, including when they receive a newer frontend OTA bundle.
+
+The existing Android push registration supplies the FCM endpoint and advertises
+`nativeCallCapable` only when the installed binary and OS support native calls.
+Existing registrations default to false and keep ordinary call alerts until a
+capable app re-registers. Deploy the device-capability migration before services;
+deploy the notification ingress and call-producing services before enabling the
+new client registration. Native delivery suppresses ordinary alerts only for the
+platform and capable Android endpoints it handles, so another device can still
+receive its fallback alert.
+
+Call pushes are data-only, high priority, have a 60-second TTL, and include a recipient-specific
+LiveKit token and HTTPS ring-status URL. The receiver checks the registered
+account and message age. Tokens are kept in memory and never logged or persisted.
+While ringing, the native coordinator polls the existing ring-status endpoint;
+answering rechecks it before connecting. Answered-elsewhere, cancelled, expired,
+and invalid-token rings are dismissed. Transient verification failures allow a
+retry but cannot authorize an answer. Logout/account switching ends native calls.
+
+The **Calls** notification channel presents Answer/Decline and an ongoing End
+call action. Telecom handles headset/system actions and coordinates interruptions.
+Android's full-screen-intent setting controls whether a locked phone opens the
+call activity automatically; when unavailable, the call notification remains the
+entry point. Test both permission states. Microphone access is required to join;
+camera access is requested when enabling video, and Bluetooth access when selecting
+that route on Android 12 or newer. A denied permission does not silently enable
+capture.
+
+The native call activity presents a themed drawer at approximately 92% of the
+safe screen height, above navigation bars/cutouts. A large participant tile sits
+above a horizontally scrolling participant strip; tapping a strip tile selects
+it as primary. Speaker, Mute and Video form a compact control row, with Leave
+in the header and camera switching on the primary local video tile. Hold Speaker
+to select headset/Bluetooth routing. Back,
+tapping the scrim, or swiping the handle down enters PiP on supported devices.
+Without PiP support, dismissal returns to Macro while retaining audio. Audio continues in the
+foreground service while backgrounded. Camera capture stops when the call activity
+is backgrounded outside PiP. PiP uses native renderers and requires device support.
+The web call controls can reopen the native activity after returning to Macro.
+
+After a debug build generates Tauri's Gradle includes, run the plugin unit tests
+from `tauri/src-tauri/gen/android` with
+`./gradlew :tauri-plugin-call-kit:testDebugUnitTest`. Run
+`./gradlew :tauri-plugin-call-kit:connectedDebugAndroidTest` for native
+Telecom/foreground-notification instrumentation on an emulator or device.
+These tests use synthetic offers to check screen-on/off incoming presentation,
+decline/redelivery and stale/account filtering without connecting media. Shared tests run
+with `bun run test src/features/channel/Call/tests` from `apps/web`. Backend
+notification tests require the local SQLx test database described in
+[database.md](database.md), with `SQLX_OFFLINE` unset.
+
+For isolated native media testing, run a local LiveKit server in `--dev` mode
+bound to `0.0.0.0`, then add
+`-Pandroid.testInstrumentationRunnerArguments.livekitUrl=ws://10.0.2.2:7880`
+to the connected-test command on the standard Android emulator. The optional
+media test uses LiveKit's development credentials, a second native participant,
+and emulator microphone/camera permissions to verify video subscription, mute,
+camera start/stop, duplicate start, network interruption/reconnect, navigation/PiP
+and resource cleanup. Cleartext
+access is enabled only in the instrumentation APK. This test does not validate
+production FCM delivery or hardware audio quality.
+
+Hardware qualification is still required on Pixel and Samsung. For each device,
+record Android version, APK revision, permissions, route/accessory and results:
+
+| Flow | Required checks |
+| --- | --- |
+| Incoming | Foreground, background, locked, ordinary process death; answer, decline, timeout; full-screen permission allowed/denied |
+| Outgoing | Foreground start, lock/background after connecting, end from app/notification/headset |
+| Ring coordination | Caller cancels, answer on another device, duplicate/delayed push, logout/account switch while ringing |
+| Audio | Microphone denied/revoked, earpiece/speaker, wired headset, Bluetooth connect/disconnect, cellular-call interruption |
+| Lifecycle | Wi-Fi/cellular transitions, temporary offline/reconnect, navigation, WebView reload, foreground resume, no duplicate participant |
+| Video | Camera denial, front/back switch, remote video, supported PiP, PiP dismissal, background without PiP, end and reopen; granting camera permission for an ended call must not enable video on a replacement call |
+
+A local build or JVM/shared-state test does not prove this hardware matrix. Play
+installation/distribution regression belongs to release workstream 07.
diff --git a/packages/sdk/generated/notification/types.gen.ts b/packages/sdk/generated/notification/types.gen.ts
index c93c7d42e4..7fe90632b0 100644
--- a/packages/sdk/generated/notification/types.gen.ts
+++ b/packages/sdk/generated/notification/types.gen.ts
@@ -485,6 +485,10 @@ export type DeviceRequest = {
* The device platform type (iOS or Android).
*/
deviceType: DeviceType;
+ /**
+ * Whether this Android binary supports native Telecom incoming calls.
+ */
+ nativeCallCapable?: boolean;
/**
* The device push notification token.
*/
diff --git a/packages/sdk/specs/notification.json b/packages/sdk/specs/notification.json
index 22abce106a..8d2113ab05 100644
--- a/packages/sdk/specs/notification.json
+++ b/packages/sdk/specs/notification.json
@@ -1678,6 +1678,10 @@
"$ref": "#/components/schemas/DeviceType",
"description": "The device platform type (iOS or Android)."
},
+ "nativeCallCapable": {
+ "type": "boolean",
+ "description": "Whether this Android binary supports native Telecom incoming calls."
+ },
"token": {
"type": "string",
"description": "The device push notification token."
diff --git a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
index baf84636af..fb0716df81 100644
--- a/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/tooling/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -240,9 +240,16 @@ impl NotificationRepository for SandboxNotificationRepository {
device_token: &str,
device_endpoint: &str,
device_type: &DeviceType,
+ native_call_capable: bool,
) -> Result<(), Report> {
self.inner
- .upsert_device(user_id, device_token, device_endpoint, device_type)
+ .upsert_device(
+ user_id,
+ device_token,
+ device_endpoint,
+ device_type,
+ native_call_capable,
+ )
.await
}