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): android push notifications (#7227)

Peter Chinman8d18e6d38fb5
diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
index 2c490c1801..7a35e84982 100644
--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.test.tsx
@@ -30,6 +30,9 @@ vi.mock('@core/auth/native-auth', () => ({
vi.mock('@queries/auth', () => ({
invalidateGithubLinkStatus: mocks.invalidateGithubLinkStatus,
+ useReauthenticateGithubMutation: () => ({
+ mutateAsync: mocks.reauthenticateGithub,
+ }),
}));
vi.mock('@core/component/Toast/Toast', () => ({
@@ -43,7 +46,6 @@ vi.mock('@core/component/Toast/Toast', () => ({
vi.mock('@service-auth/client', () => ({
authServiceClient: {
checkGithubLinkStatus: mocks.checkGithubLinkStatus,
- reauthenticateGithub: mocks.reauthenticateGithub,
},
}));
@@ -83,7 +85,7 @@ async function flushPromises(): Promise<void> {
}
function getReconnectAction(): ToastAction {
- const config = mocks.toastCustom.mock.calls[0]?.[0] as
+ const config = mocks.toastCustom.mock.calls.at(-1)?.[0] as
| ToastConfig
| undefined;
if (!config) throw new Error('Expected GitHub reauthentication toast');
@@ -138,7 +140,7 @@ describe('GithubReauthenticationPrompt', () => {
);
const originalUrl = window.location.href;
const authorizationUrl = 'https://github.com/login/oauth/authorize';
- mocks.reauthenticateGithub.mockResolvedValue(resultOk(authorizationUrl));
+ mocks.reauthenticateGithub.mockResolvedValue(authorizationUrl);
mocks.authenticate.mockResolvedValue(result);
const cleanup = renderPrompt();
@@ -155,10 +157,73 @@ describe('GithubReauthenticationPrompt', () => {
invalidates ? 1 : 0
);
expect(mocks.toastFailure).toHaveBeenCalledTimes(failure ? 1 : 0);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(result.success ? 1 : 2);
+ if (!result.success) {
+ mocks.authenticate.mockResolvedValue({ success: true });
+ await getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.authenticate).toHaveBeenCalledTimes(2);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);
+ }
+ cleanup();
+ }
+ );
+
+ it.each([true, false])(
+ 'restores the prompt after OAuth startup fails (native: %s)',
+ async (native) => {
+ mocks.nativeMobile = native;
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultErr([{ code: 'REAUTHENTICATION_REQUIRED', message: 'Reconnect' }])
+ );
+ mocks.reauthenticateGithub.mockRejectedValue(new Error('Unavailable'));
+ const cleanup = renderPrompt();
+ await flushPromises();
+ await getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.toastFailure).toHaveBeenCalledOnce();
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);
+ expect(mocks.authenticate).not.toHaveBeenCalled();
cleanup();
}
);
+ it('keeps the prompt hidden and prevents duplicate reconnects while native OAuth is pending', async () => {
+ mocks.nativeMobile = true;
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultErr([{ code: 'REAUTHENTICATION_REQUIRED', message: 'Reconnect' }])
+ );
+ mocks.reauthenticateGithub.mockResolvedValue(
+ 'https://github.com/login/oauth/authorize'
+ );
+ let complete!: (result: { success: boolean; error: string }) => void;
+ mocks.authenticate.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ })
+ );
+ const cleanup = renderPrompt();
+ await flushPromises();
+ const action = getReconnectAction();
+ action.onClick();
+ action.onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ action.onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledOnce();
+ expect(mocks.authenticate).toHaveBeenCalledOnce();
+ expect(mocks.toastDismiss).toHaveBeenCalledWith(101);
+ expect(mocks.toastCustom).toHaveBeenCalledOnce();
+ complete({ success: false, error: 'User canceled login' });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);
+ cleanup();
+ });
+
it('shows a reconnect toast globally when GitHub reauthentication is required', async () => {
mocks.checkGithubLinkStatus.mockResolvedValue(
resultErr([
@@ -170,7 +235,7 @@ describe('GithubReauthenticationPrompt', () => {
);
const originalUrl = window.location.href;
const authorizationUrl = `${originalUrl}#github-reauth`;
- mocks.reauthenticateGithub.mockResolvedValue(resultOk(authorizationUrl));
+ mocks.reauthenticateGithub.mockResolvedValue(authorizationUrl);
const cleanup = renderPrompt();
await flushPromises();
@@ -193,6 +258,79 @@ describe('GithubReauthenticationPrompt', () => {
cleanup();
});
+ it.each([true, false])(
+ 'refreshes a restored browser page before allowing retry (needs reauth: %s)',
+ async (needsReauth) => {
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultOk({ reauthentication_required: true })
+ );
+ mocks.reauthenticateGithub.mockResolvedValue(
+ `${window.location.href}#github-reauth`
+ );
+ const cleanup = renderPrompt();
+ await flushPromises();
+ getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.toastCustom).toHaveBeenCalledOnce();
+ expect(mocks.toastDismiss).toHaveBeenCalledWith(101);
+
+ window.dispatchEvent(new PageTransitionEvent('pageshow'));
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledOnce();
+
+ const refreshedStatus = resultOk({
+ reauthentication_required: needsReauth,
+ });
+ let complete!: (value: typeof refreshedStatus) => void;
+ mocks.checkGithubLinkStatus.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ })
+ );
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledTimes(2);
+ expect(mocks.toastCustom).toHaveBeenCalledOnce();
+ complete(refreshedStatus);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(needsReauth ? 2 : 1);
+ if (needsReauth) {
+ getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.reauthenticateGithub).toHaveBeenCalledTimes(2);
+ }
+
+ cleanup();
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ expect(mocks.checkGithubLinkStatus).toHaveBeenCalledTimes(2);
+ }
+ );
+
+ it('allows retry if the restored browser page cannot refresh link status', async () => {
+ mocks.checkGithubLinkStatus.mockResolvedValue(
+ resultOk({ reauthentication_required: true })
+ );
+ mocks.reauthenticateGithub.mockResolvedValue(
+ `${window.location.href}#github-reauth`
+ );
+ const cleanup = renderPrompt();
+ await flushPromises();
+ getReconnectAction().onClick();
+ await vi.advanceTimersByTimeAsync(0);
+ mocks.checkGithubLinkStatus.mockRejectedValueOnce(
+ new Error('Network unavailable')
+ );
+ window.dispatchEvent(
+ new PageTransitionEvent('pageshow', { persisted: true })
+ );
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mocks.toastCustom).toHaveBeenCalledTimes(2);
+ cleanup();
+ });
+
it('does not show a reconnect toast for valid GitHub links', async () => {
mocks.checkGithubLinkStatus.mockResolvedValue(
resultOk({ reauthentication_required: false })
diff --git a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
index a11b3d4225..82baa6019c 100644
--- a/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
+++ b/apps/web/src/features/auth/GithubReauthenticationPrompt.tsx
@@ -1,9 +1,10 @@
import { authorizeGithub } from '@core/auth/authorize-github';
import { toast } from '@core/component/Toast/Toast';
import { useKeyedPersistentToasts } from '@core/component/Toast/useKeyedPersistentToasts';
-import { throwOnErr } from '@core/util/result';
+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
+import { useReauthenticateGithubMutation } from '@queries/auth';
import { authServiceClient } from '@service-auth/client';
-import { createSignal, onMount } from 'solid-js';
+import { createSignal, onCleanup, onMount } from 'solid-js';
async function checkGithubReauthenticationStatus(): Promise<boolean> {
const response = await authServiceClient.checkGithubLinkStatus();
@@ -14,36 +15,57 @@ async function checkGithubReauthenticationStatus(): Promise<boolean> {
);
}
-/** Kick off the OAuth flow; the web navigates away, native completes in-app. */
-async function startGithubReauthentication(): Promise<void> {
- try {
- await authorizeGithub(
- (callbackUrl) =>
- throwOnErr(() => authServiceClient.reauthenticateGithub(callbackUrl)),
- 'Failed to reconnect GitHub'
- );
- } catch {
- toast.failure('Failed to start GitHub reconnect flow');
- }
-}
-
/**
* Surfaces a "Reconnect GitHub" prompt when the GitHub grant has expired,
- * probed once on mount. Shares the capped prompt region with the other auth
- * prompts, so it takes its turn instead of stacking on them.
+ * probed on mount and browser history restoration. Shares the capped prompt
+ * region with the other auth prompts, so it takes its turn instead of stacking.
*/
export function GithubReauthenticationPrompt() {
const [needsReauth, setNeedsReauth] = createSignal(false);
+ const [reconnecting, setReconnecting] = createSignal(false);
+ const reauthenticateGithub = useReauthenticateGithubMutation();
+
+ async function reconnect() {
+ if (reconnecting()) return;
+ setReconnecting(true);
+ try {
+ const connected = await authorizeGithub(
+ (callbackUrl) => reauthenticateGithub.mutateAsync(callbackUrl),
+ 'Failed to reconnect GitHub'
+ );
+ if (connected) setNeedsReauth(false);
+ // Browser OAuth is navigating away. Native OAuth settles in this view.
+ if (!isNativeMobilePlatform()) return;
+ } catch {
+ toast.failure('Failed to start GitHub reconnect flow');
+ }
+ setReconnecting(false);
+ }
onMount(() => {
void checkGithubReauthenticationStatus().then(setNeedsReauth);
+ if (isNativeMobilePlatform()) return;
+
+ async function onPageShow(event: PageTransitionEvent) {
+ if (!event.persisted) return;
+ try {
+ setNeedsReauth(await checkGithubReauthenticationStatus());
+ } catch {
+ // Preserve the previous status if the restored page cannot reach auth.
+ } finally {
+ setReconnecting(false);
+ }
+ }
+
+ window.addEventListener('pageshow', onPageShow);
+ onCleanup(() => window.removeEventListener('pageshow', onPageShow));
});
useKeyedPersistentToasts({
// One GitHub grant per user, so the set is empty or this one fixed key.
- items: () => (needsReauth() ? ['github'] : []),
+ items: () => (needsReauth() && !reconnecting() ? ['github'] : []),
key: (item) => item,
- toast: (_item, dismiss) => ({
+ toast: () => ({
title: 'Reconnect GitHub',
content(): string {
return 'Your GitHub authorization has expired. Reconnect GitHub to restore pull request details.';
@@ -52,10 +74,7 @@ export function GithubReauthenticationPrompt() {
{
label: 'Reconnect',
onClick: () => {
- // Suppress re-prompting while the OAuth flow runs. On the web
- // success navigates away; on native the link status is refetched.
- dismiss();
- void startGithubReauthentication();
+ void reconnect();
},
},
],
diff --git a/apps/web/src/lib/core/auth/push-registration-lifecycle.test.ts b/apps/web/src/lib/core/auth/push-registration-lifecycle.test.ts
new file mode 100644
index 0000000000..2be93a873c
--- /dev/null
+++ b/apps/web/src/lib/core/auth/push-registration-lifecycle.test.ts
@@ -0,0 +1,51 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+beforeEach(() => vi.resetModules());
+
+describe('push registration session boundary', () => {
+ it('ignores resume events during logout until a new session is established', async () => {
+ const lifecycle = await import('./push-registration-lifecycle');
+ let finishLogout!: () => void;
+ const syncRegistration = vi.fn(async () => {});
+ lifecycle.registerPushRegistrationLifecycle({
+ syncRegistration,
+ unregisterForLogout: () =>
+ new Promise<void>((resolve) => {
+ finishLogout = resolve;
+ }),
+ });
+ const logout = lifecycle.unregisterPushRegistrationsForLogout();
+ await lifecycle.syncPushRegistrations('resume');
+ expect(syncRegistration).not.toHaveBeenCalled();
+ finishLogout();
+ await logout;
+ await lifecycle.syncPushRegistrations('resume');
+ expect(syncRegistration).not.toHaveBeenCalled();
+ await lifecycle.syncPushRegistrations();
+ expect(syncRegistration).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not retry a failed registration from the previous session', async () => {
+ vi.useFakeTimers();
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const lifecycle = await import('./push-registration-lifecycle');
+ const syncRegistration = vi.fn(async () => {
+ throw new Error('offline');
+ });
+ lifecycle.registerPushRegistrationLifecycle({
+ syncRegistration,
+ unregisterForLogout: async () => {},
+ });
+ const syncing = lifecycle.syncPushRegistrations();
+ await Promise.resolve();
+ await lifecycle.unregisterPushRegistrationsForLogout();
+ await vi.runAllTimersAsync();
+ await syncing;
+ expect(syncRegistration).toHaveBeenCalledTimes(1);
+ } finally {
+ error.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/web/src/lib/core/auth/push-registration-lifecycle.ts b/apps/web/src/lib/core/auth/push-registration-lifecycle.ts
index ff1d2424ec..80195cc6d8 100644
--- a/apps/web/src/lib/core/auth/push-registration-lifecycle.ts
+++ b/apps/web/src/lib/core/auth/push-registration-lifecycle.ts
@@ -17,6 +17,10 @@ export type PushRegistrationLifecycle = {
};
const lifecycles = new Set<PushRegistrationLifecycle>();
+// Incremented at logout to invalidate delayed retries from that session.
+let sessionGeneration = 0;
+// A registration pause set by logout, not an authoritative auth-state check.
+let loggedOut = false;
/** Register a platform push lifecycle. Returns a function that removes it. */
export function registerPushRegistrationLifecycle(
@@ -30,14 +34,29 @@ const SYNC_RETRY_DELAY_MS = 5_000;
/**
* (Re-)register this device's push tokens under the current session's user.
- * Call whenever a session is established — on login or at app launch with an
- * existing session.
+ *
+ * `source` identifies the caller's reason for syncing:
+ * - `session` (the default): the caller has established an authenticated
+ * session. This lifts the registration pause set by logout; this function
+ * does not verify authentication itself.
+ * - `resume`: app startup/resume or token refresh should reconcile the current
+ * registration, but must not lift a pause set by logout.
+ *
+ * Logout unregisters devices before clearing authentication because the
+ * unregister request needs valid credentials. A native resume/token event in
+ * that window must not register the account again just because its cookie
+ * still exists. Only a subsequent `session` call may resume registration.
*
* A failed sync leaves the previous account's registration in place on the
* backend, so each lifecycle gets one short delayed retry against transient
* failures (network blip, backend error).
*/
-export async function syncPushRegistrations(): Promise<void> {
+export async function syncPushRegistrations(
+ source: 'session' | 'resume' = 'session'
+): Promise<void> {
+ if (source === 'resume' && loggedOut) return;
+ if (source === 'session') loggedOut = false;
+ const generation = sessionGeneration;
await Promise.all(
[...lifecycles].map(async (lifecycle) => {
try {
@@ -47,6 +66,9 @@ export async function syncPushRegistrations(): Promise<void> {
await new Promise((resolve) =>
setTimeout(resolve, SYNC_RETRY_DELAY_MS)
);
+ // A logout invalidates this retry even if another login has already
+ // reset loggedOut to false. The boolean alone cannot detect that.
+ if (generation !== sessionGeneration) return;
try {
await lifecycle.syncRegistration();
} catch (retryErr) {
@@ -62,6 +84,8 @@ export async function syncPushRegistrations(): Promise<void> {
* the session is still valid — the unregister call is authenticated.
*/
export async function unregisterPushRegistrationsForLogout(): Promise<void> {
+ loggedOut = true;
+ ++sessionGeneration;
await Promise.all(
[...lifecycles].map((lifecycle) =>
lifecycle.unregisterForLogout().catch((err) => {
diff --git a/apps/web/src/lib/queries/auth/user-info.ts b/apps/web/src/lib/queries/auth/user-info.ts
index 63ad0ad772..bdd1380fda 100644
--- a/apps/web/src/lib/queries/auth/user-info.ts
+++ b/apps/web/src/lib/queries/auth/user-info.ts
@@ -96,7 +96,7 @@ export async function prefetchUserInfo() {
}
/** Fetch user info and return the data. Use when you need the result. */
-async function _fetchUserInfo() {
+export async function fetchUserInfo() {
return queryClient.fetchQuery({
queryKey: authKeys.userInfo.queryKey,
queryFn: async () =>
diff --git a/apps/web/src/lib/queries/notification/device-registration.ts b/apps/web/src/lib/queries/notification/device-registration.ts
new file mode 100644
index 0000000000..5876922f6f
--- /dev/null
+++ b/apps/web/src/lib/queries/notification/device-registration.ts
@@ -0,0 +1,16 @@
+import { notificationServiceClient } from '@service-notification/client';
+import { fetchUserInfo } from '../auth/user-info';
+
+type Device = { deviceType: 'android' | 'ios'; token: string };
+
+export function registerPushDevice(device: Device) {
+ return notificationServiceClient.registerDevice(device);
+}
+
+export function unregisterPushDevice(device: Device) {
+ return notificationServiceClient.unregisterDevice(device);
+}
+
+export async function fetchPushRecipient() {
+ return (await fetchUserInfo()).userId;
+}
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..5dbc1a7ab2
--- /dev/null
+++ b/apps/web/src/lib/tauri/PushNotification.test.tsx
@@ -0,0 +1,352 @@
+import type { PushRegistrationLifecycle } from '@core/auth/push-registration-lifecycle';
+import type { PlatformNotificationInterface } from '@notifications';
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { PushEvent } from './push-api';
+
+const mock = vi.hoisted(() => ({
+ loggedIn: true,
+ lifecycle: undefined as PushRegistrationLifecycle | undefined,
+ watcher: undefined as ((event: PushEvent) => void) | undefined,
+ check: vi.fn(),
+ request: vi.fn(),
+ register: vi.fn(),
+ configure: vi.fn(),
+ unwatch: vi.fn(),
+ watch: vi.fn(),
+ registerDevice: vi.fn(),
+ unregisterDevice: vi.fn(),
+ recipient: vi.fn(),
+ navigate: vi.fn(),
+ acknowledge: vi.fn(),
+ localShow: vi.fn(),
+ notifications: undefined as PlatformNotificationInterface | undefined,
+}));
+
+vi.mock('@core/util/cookies', () => ({ hasLoginCookie: () => mock.loggedIn }));
+vi.mock('@core/auth/push-registration-lifecycle', () => ({
+ registerPushRegistrationLifecycle: (lifecycle: PushRegistrationLifecycle) => {
+ mock.lifecycle = lifecycle;
+ return () => {};
+ },
+ syncPushRegistrations: async () => {
+ await mock.lifecycle?.syncRegistration();
+ },
+}));
+vi.mock('@queries/notification/device-registration', () => ({
+ fetchPushRecipient: mock.recipient,
+ registerPushDevice: mock.registerDevice,
+ unregisterPushDevice: mock.unregisterDevice,
+}));
+vi.mock('@notifications', () => ({
+ PlatformNotificationProvider: (props: {
+ children: unknown;
+ overrideDefault: (
+ disabled: () => Promise<void>
+ ) => PlatformNotificationInterface;
+ }) => {
+ mock.notifications = props.overrideDefault(async () => {});
+ return props.children;
+ },
+ triggerNotificationNavigation: mock.navigate,
+}));
+vi.mock('@tauri-apps/plugin-notification', () => ({
+ removeAllActive: vi.fn(async () => {}),
+}));
+vi.mock('./notification', () => ({
+ createTauriNotificationInterface: () => ({
+ showNotification: mock.localShow,
+ requestPermission: async () => 'granted',
+ getCurrentPermission: async () => 'granted',
+ unregisterNotifications: async () => {},
+ }),
+}));
+vi.mock('./TauriProvider', () => ({
+ useExpectTauri: () => ({ os: 'android' }),
+}));
+vi.mock('./push-api', () => ({
+ createPushApi: () => ({
+ checkPermissions: mock.check,
+ requestPermissions: mock.request,
+ register: mock.register,
+ configureRecipient: mock.configure,
+ unwatch: mock.unwatch,
+ acknowledge: mock.acknowledge,
+ watch: async (callback: (event: PushEvent) => void) => {
+ await mock.watch(callback);
+ },
+ }),
+}));
+
+import { MaybePushNotificationRegistration } from './PushNotification';
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ localStorage.clear();
+ mock.loggedIn = true;
+ mock.watcher = undefined;
+ mock.watch.mockImplementation(
+ async (callback: (event: PushEvent) => void) => {
+ mock.watcher = callback;
+ }
+ );
+ mock.notifications = undefined;
+ mock.check.mockResolvedValue({ status: 'denied' });
+ mock.register.mockResolvedValue({ success: true, token: 'test-token' });
+ mock.configure.mockResolvedValue(undefined);
+ mock.unwatch.mockResolvedValue(undefined);
+ mock.recipient.mockResolvedValue('macro|[email protected]');
+ mock.registerDevice.mockResolvedValue({ isErr: () => false });
+ mock.unregisterDevice.mockResolvedValue({ isErr: () => false });
+});
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
+
+async function mount() {
+ render(() => (
+ <MaybePushNotificationRegistration>
+ <div />
+ </MaybePushNotificationRegistration>
+ ));
+ await vi.waitFor(() => expect(mock.watcher).toBeDefined());
+ // Let the launch sync (permission denied -> receiver disarmed) finish
+ // before starting a new action.
+ await vi.waitFor(() => expect(mock.configure).toHaveBeenCalledWith(null));
+ expect(mock.check).toHaveBeenCalledTimes(1);
+ expect(mock.configure).toHaveBeenCalledTimes(1);
+ mock.configure.mockClear();
+}
+
+describe('Android push lifecycle', () => {
+ it('listens before registration and navigates only on taps', async () => {
+ await mount();
+ expect(mock.registerDevice).not.toHaveBeenCalled();
+ mock.watcher?.({
+ type: 'BACKGROUND_DELIVERY',
+ payload: { notificationId: 'id' },
+ });
+ expect(mock.navigate).not.toHaveBeenCalled();
+ mock.watcher?.({
+ type: 'BACKGROUND_TAP',
+ payload: { notificationId: 'id' },
+ deliveryId: 'delivery-id',
+ });
+ expect(mock.navigate).toHaveBeenCalledWith('id');
+ expect(mock.acknowledge).toHaveBeenCalledWith('delivery-id');
+ });
+
+ it('shares an in-flight watcher and retries failure so taps still navigate', async () => {
+ vi.useFakeTimers();
+ let fail!: (error: Error) => void;
+ mock.watch.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ fail = reject;
+ })
+ );
+ render(() => (
+ <MaybePushNotificationRegistration>
+ <div />
+ </MaybePushNotificationRegistration>
+ ));
+ await vi.advanceTimersByTimeAsync(0);
+ mock.check.mockResolvedValue({ status: 'granted' });
+ let finished = false;
+ async function syncRegistration() {
+ await mock.lifecycle!.syncRegistration();
+ finished = true;
+ }
+ const registration = syncRegistration();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mock.watch).toHaveBeenCalledOnce();
+ expect(finished).toBe(false);
+ fail(new Error('Transient bridge failure'));
+ await registration;
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(mock.watch).toHaveBeenCalledTimes(2);
+ mock.watcher?.({
+ type: 'BACKGROUND_TAP',
+ payload: { notificationId: 'id' },
+ deliveryId: 'tap',
+ });
+ expect(mock.navigate).toHaveBeenCalledWith('id');
+ expect(mock.acknowledge).toHaveBeenCalledWith('tap');
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(mock.watch).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([false, true])(
+ 'does not retry a failed watcher after disposal (failure pending: %s)',
+ async (pending) => {
+ vi.useFakeTimers();
+ let fail!: (error: Error) => void;
+ mock.watch.mockImplementationOnce(
+ () =>
+ new Promise((_, reject) => {
+ fail = reject;
+ })
+ );
+ const { unmount } = render(() => (
+ <MaybePushNotificationRegistration>
+ <div />
+ </MaybePushNotificationRegistration>
+ ));
+ await vi.advanceTimersByTimeAsync(0);
+ if (pending) unmount();
+ fail(new Error('Transient bridge failure'));
+ await vi.advanceTimersByTimeAsync(0);
+ if (!pending) unmount();
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(mock.watch).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('binds the native receiver only after backend registration succeeds', async () => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ await mock.lifecycle?.syncRegistration();
+ expect(mock.registerDevice).toHaveBeenCalledWith({
+ deviceType: 'android',
+ token: 'test-token',
+ });
+ expect(mock.configure).toHaveBeenCalledWith('macro|[email protected]');
+ });
+
+ it('cannot re-enable the old recipient when registration finishes after logout', async () => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ let complete!: (value: { isErr: () => boolean }) => void;
+ mock.registerDevice.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ })
+ );
+ const syncing = expect(mock.lifecycle!.syncRegistration()).rejects.toThrow(
+ 'push device registration did not complete'
+ );
+ await vi.waitFor(() => expect(mock.registerDevice).toHaveBeenCalled());
+ const logout = mock.lifecycle!.unregisterForLogout();
+ await vi.waitFor(() => expect(mock.configure).toHaveBeenCalledWith(null));
+ mock.loggedIn = false;
+ complete({ isErr: () => false });
+ await Promise.all([syncing, logout]);
+ expect(mock.configure.mock.calls).toEqual([[null]]);
+ expect(mock.unregisterDevice).toHaveBeenCalledWith({
+ deviceType: 'android',
+ token: 'test-token',
+ });
+ expect(mock.unregisterDevice.mock.invocationCallOrder[0]).toBeGreaterThan(
+ mock.registerDevice.mock.invocationCallOrder[0]
+ );
+ });
+
+ it.each(['logout', 'opt-out'])(
+ 'disarms a native configure that completes during %s',
+ async (action) => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ let complete!: () => void;
+ let nativeRecipient: string | null = null;
+ mock.configure.mockImplementation(async (recipient: string | null) => {
+ if (recipient !== null) {
+ await new Promise<void>((resolve) => {
+ complete = resolve;
+ });
+ }
+ nativeRecipient = recipient;
+ });
+ const syncing = expect(
+ mock.lifecycle!.syncRegistration()
+ ).rejects.toThrow('push device registration did not complete');
+ await vi.waitFor(() => expect(complete).toBeDefined());
+ const disabling =
+ action === 'logout'
+ ? mock.lifecycle!.unregisterForLogout()
+ : mock.notifications!.unregisterNotifications();
+ if (action === 'logout') mock.loggedIn = false;
+ complete();
+ await Promise.all([syncing, disabling]);
+ expect(nativeRecipient).toBeNull();
+ expect(mock.configure).toHaveBeenLastCalledWith(null);
+ expect(mock.unregisterDevice).toHaveBeenCalledWith({
+ deviceType: 'android',
+ token: 'test-token',
+ });
+ }
+ );
+
+ it.each(['backend', 'native'])(
+ 'keeps the new account registered after stale %s completion',
+ async (pendingStep) => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ let complete!: () => void;
+ let nativeRecipient: string | null = null;
+ let backendRegistered = false;
+ const delayed = async () => {
+ await new Promise<void>((resolve) => {
+ complete = resolve;
+ });
+ };
+ mock.registerDevice.mockImplementation(async () => {
+ if (
+ pendingStep === 'backend' &&
+ mock.registerDevice.mock.calls.length === 1
+ )
+ await delayed();
+ backendRegistered = true;
+ return { isErr: () => false };
+ });
+ mock.unregisterDevice.mockImplementation(async () => {
+ backendRegistered = false;
+ return { isErr: () => false };
+ });
+ mock.configure.mockImplementation(async (recipient: string | null) => {
+ if (pendingStep === 'native' && recipient === 'macro|[email protected]')
+ await delayed();
+ nativeRecipient = recipient;
+ });
+ const oldSync = expect(
+ mock.lifecycle!.syncRegistration()
+ ).rejects.toThrow('push device registration did not complete');
+ await vi.waitFor(() => expect(complete).toBeDefined());
+ const logout = mock.lifecycle!.unregisterForLogout();
+ // Model a new login after logout's network timeout. The token is shared.
+ mock.recipient.mockResolvedValue('macro|[email protected]');
+ const newSync = mock.lifecycle!.syncRegistration();
+ complete();
+ await Promise.all([oldSync, logout, newSync]);
+ expect(backendRegistered).toBe(true);
+ expect(nativeRecipient).toBe('macro|[email protected]');
+ expect(mock.configure).toHaveBeenLastCalledWith('macro|[email protected]');
+ expect(mock.registerDevice).toHaveBeenCalledTimes(2);
+ expect(mock.registerDevice.mock.invocationCallOrder[1]).toBeGreaterThan(
+ Math.max(...mock.unregisterDevice.mock.invocationCallOrder)
+ );
+ }
+ );
+
+ it('disables native display when permission is revoked', async () => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ await mock.lifecycle?.syncRegistration();
+ mock.configure.mockClear();
+ mock.check.mockResolvedValue({ status: 'denied' });
+ await mock.lifecycle?.syncRegistration();
+ expect(mock.configure).toHaveBeenCalledWith(null);
+ });
+
+ it('suppresses websocket local notifications after remote push registration', async () => {
+ await mount();
+ mock.check.mockResolvedValue({ status: 'granted' });
+ await mock.lifecycle?.syncRegistration();
+ await mock.notifications!.showNotification({
+ title: 'Duplicate message',
+ options: { body: 'Body' },
+ });
+ expect(mock.localShow).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/tauri/PushNotification.tsx b/apps/web/src/lib/tauri/PushNotification.tsx
index 9fa297b1db..4ef4d6fc65 100644
--- a/apps/web/src/lib/tauri/PushNotification.tsx
+++ b/apps/web/src/lib/tauri/PushNotification.tsx
@@ -3,32 +3,32 @@ import {
syncPushRegistrations,
} from '@core/auth/push-registration-lifecycle';
import { hasLoginCookie } from '@core/util/cookies';
-import { whenSettled } from '@core/util/whenSettled';
-import {
- checkPermissions,
- type NotificationEvent,
- type NotificationRegistrationResult,
- registerForRemoteNotifications,
- requestPermissions,
- watchNotifications,
+import type {
+ NotificationEvent,
+ NotificationRegistrationResult,
} from '@inkibra/tauri-plugins/packages/tauri-plugin-notifications';
import {
type PlatformNotificationInterface,
PlatformNotificationProvider,
triggerNotificationNavigation,
} from '@notifications';
-import { notificationServiceClient } from '@service-notification/client';
+import {
+ fetchPushRecipient,
+ registerPushDevice,
+ unregisterPushDevice,
+} from '@queries/notification/device-registration';
import { makePersisted } from '@solid-primitives/storage';
import { removeAllActive } from '@tauri-apps/plugin-notification';
+import { Mutex } from 'async-mutex';
import {
createContext,
createEffect,
- createResource,
createSignal,
type JSX,
onCleanup,
} from 'solid-js';
import { createTauriNotificationInterface } from './notification';
+import { createPushApi, type PushEvent } from './push-api';
import { useExpectTauri } from './TauriProvider';
function getNotificationId(payload: Record<string, unknown>) {
@@ -40,7 +40,18 @@ function usePushNotifications(
deviceType: 'android' | 'ios',
onPushNotification?: (event: NotificationEvent) => void
) {
- const [systemPermission] = createResource(checkPermissions);
+ const api = createPushApi(deviceType);
+ // Bumped by every registration-changing action so an in-flight one can
+ // detect it was superseded (logout, opt-out, a newer sync) and stop.
+ let registrationEpoch = 0;
+ // Keep token writes ordered across logout/account switching. Native writes
+ // have their own queue so logout can disarm without waiting for the network.
+ const registrationMutex = new Mutex();
+ const recipientMutex = new Mutex();
+ let disposed = false;
+ let requestingPermission = false;
+ let notificationWatch: Promise<void> | undefined;
+ let watchRetryTimeout: ReturnType<typeof setTimeout> | undefined;
const [registrationResult, setRegistrationResult] = makePersisted(
createSignal<NotificationRegistrationResult | undefined>(undefined)
@@ -58,61 +69,132 @@ function usePushNotifications(
createSignal(false)
);
+ function isStale(epoch: number) {
+ return epoch !== registrationEpoch;
+ }
+
+ // A registration step must stop once a newer sync started or the session
+ // ended, otherwise late async completion could bind the wrong account.
+ function aborted(epoch: number) {
+ return isStale(epoch) || !hasLoginCookie();
+ }
+
async function registerDeviceWithNotificationService(
- token: string
+ token: string,
+ epoch: number
): Promise<'granted' | 'denied'> {
- const res = await notificationServiceClient.registerDevice({
- deviceType,
- token,
+ return registrationMutex.runExclusive(async () => {
+ if (aborted(epoch)) return 'denied';
+ const recipient = await fetchRecipient();
+ if (recipient === undefined) return 'denied';
+ if (aborted(epoch)) return 'denied';
+ const res = await registerPushDevice({ deviceType, token });
+ if (res.isErr()) {
+ // Transient failures must not erase a previously granted permission.
+ console.error('failed to register device for push', res.error);
+ return 'denied';
+ }
+ try {
+ if (aborted(epoch)) return 'denied';
+ await configureRecipient(recipient, epoch);
+ if (aborted(epoch)) return 'denied';
+ setPermission('granted');
+ setPushDisabledByUser(false);
+ await startWatch();
+ if (aborted(epoch)) return 'denied';
+ return 'granted';
+ } finally {
+ // A successful backend write may finish after logout/opt-out. Roll it
+ // back before a newer registration can acquire the lock and bind it.
+ if (aborted(epoch)) await unregisterDevice(token);
+ }
});
- if (res.isErr()) {
- // A failed registration is always a transient condition (network blip,
- // auth still settling, backend error) — the endpoint has no "rejected"
- // semantics. Only success may write the persisted state: flipping it to
- // 'denied' here would disable remote-push dedupe and report push as off
- // in Settings until the next successful sync.
- console.error('failed to register device for push', res.error);
- return 'denied';
+ }
+
+ async function configureRecipient(recipient: string | null, epoch: number) {
+ await recipientMutex.runExclusive(async () => {
+ if (isStale(epoch)) return;
+ try {
+ await api.configureRecipient(recipient);
+ } finally {
+ // The bridge may finish an old configure after logout has started.
+ // Disarm before releasing the lock to any newer account's configure.
+ if (recipient !== null && aborted(epoch)) {
+ await api.configureRecipient(null);
+ }
+ }
+ });
+ }
+
+ async function unregisterDevice(token: string) {
+ const res = await unregisterPushDevice({ deviceType, token });
+ if (res.isErr()) throw new Error('failed to unregister device for push');
+ }
+
+ // The native receiver only displays pushes addressed to this account, so
+ // Android needs the user id before it can be armed. iOS has no such gate.
+ async function fetchRecipient(): Promise<string | null | undefined> {
+ if (deviceType !== 'android') return null;
+ try {
+ return await fetchPushRecipient();
+ } catch (error) {
+ // Transient like a failed registration: leave persisted state alone so
+ // the lifecycle retry gets another go.
+ console.error('failed to resolve push recipient', error);
+ return undefined;
}
- setPermission('granted');
- setPushDisabledByUser(false);
- return 'granted';
}
async function requestNotificationRegistration() {
- const perm = await requestPermissions();
+ requestingPermission = true;
+ try {
+ return await requestAndRegister();
+ } finally {
+ requestingPermission = false;
+ }
+ }
+
+ async function requestAndRegister() {
+ const epoch = ++registrationEpoch;
+ const perm = await api.requestPermissions();
+ if (isStale(epoch)) return 'denied';
if (perm.status !== 'granted') {
setPermission(undefined);
setRegistrationResult(undefined);
+ await configureRecipient(null, epoch);
return 'denied';
}
- const reg = await registerForRemoteNotifications();
+ const reg = await api.register();
+ if (isStale(epoch)) return 'denied';
if (!reg.token) {
+ console.error('push registration returned no token', reg.error);
setPermission(undefined);
setRegistrationResult(undefined);
return 'denied';
}
setRegistrationResult(reg);
- return await registerDeviceWithNotificationService(reg.token);
+ return await registerDeviceWithNotificationService(reg.token, epoch);
}
- async function unregisterPushNotifications() {
+ async function unregisterPushNotifications(disabledByUser = true) {
+ const epoch = ++registrationEpoch;
const token = registrationResult()?.token;
-
- if (token) {
- const res = await notificationServiceClient.unregisterDevice({
- deviceType,
- token,
- });
- if (res.isErr()) {
- console.error('failed to unregister device for push', res.error);
- }
- } else {
- console.warn('Cannot unregister device with no token set');
- }
- setRegistrationResult(undefined);
setPermission(undefined);
- setPushDisabledByUser(true);
+ setPushDisabledByUser(disabledByUser);
+ setRegistrationResult(undefined);
+ // Queue removal immediately, before another login can enqueue a token
+ // registration. Disarming the receiver is independent of backend latency.
+ await Promise.all([
+ configureRecipient(null, epoch),
+ registrationMutex.runExclusive(async () => {
+ if (!token) return;
+ try {
+ await unregisterDevice(token);
+ } catch (error) {
+ console.error('failed to unregister device for push', error);
+ }
+ }),
+ ]);
}
// (Re-)register this device under whoever is currently logged in. The
@@ -120,21 +202,49 @@ function usePushNotifications(
// not just when the APNs token rotates — or the previous account keeps
// receiving this device's pushes.
async function syncDeviceRegistration() {
- if (pushDisabledByUser()) return;
- const sysPerm = await checkPermissions();
- if (sysPerm.status !== 'granted') return;
- const freshResult = await registerForRemoteNotifications();
- if (!freshResult.token) return;
+ if (
+ disposed ||
+ requestingPermission ||
+ pushDisabledByUser() ||
+ !hasLoginCookie()
+ )
+ return;
+ const epoch = ++registrationEpoch;
+ const sysPerm = await api.checkPermissions();
+ if (isStale(epoch)) return;
+ if (sysPerm.status !== 'granted') {
+ setPermission(undefined);
+ await configureRecipient(null, epoch);
+ const token = registrationResult()?.token;
+ if (deviceType === 'android' && token) {
+ await registrationMutex.runExclusive(async () => {
+ if (!isStale(epoch)) await unregisterDevice(token);
+ });
+ }
+ return;
+ }
+ const freshResult = await api.register();
+ if (isStale(epoch)) return;
+ if (!freshResult.token) {
+ console.error('push registration returned no token', freshResult.error);
+ return;
+ }
const storedToken = registrationResult()?.token;
if (storedToken && storedToken !== freshResult.token) {
// Best-effort: unregister the old token
- notificationServiceClient
- .unregisterDevice({ deviceType, token: storedToken })
- .catch(console.error);
+ try {
+ await registrationMutex.runExclusive(async () => {
+ if (!isStale(epoch)) await unregisterDevice(storedToken);
+ });
+ } catch (error) {
+ console.error('failed to unregister rotated push token', error);
+ }
}
+ if (isStale(epoch)) return;
setRegistrationResult(freshResult);
const result = await registerDeviceWithNotificationService(
- freshResult.token
+ freshResult.token,
+ epoch
);
if (result !== 'granted') {
// Surface the failure so the lifecycle's retry (and its logging) see it.
@@ -146,12 +256,17 @@ function usePushNotifications(
// The logged-out account's already-delivered notifications must not
// linger in the system notification center for the next account to see.
await Promise.all([
- removeAllActive().catch(console.error),
- unregisterPushNotifications(),
+ clearDisplayedNotifications(),
+ unregisterPushNotifications(false),
]);
- // unregisterPushNotifications() sets pushDisabledByUser, but that's an
- // opt-out for this account, not the next one that logs in on this device.
- setPushDisabledByUser(false);
+ }
+
+ async function clearDisplayedNotifications() {
+ try {
+ await removeAllActive();
+ } catch (error) {
+ console.error(error);
+ }
}
const removeLifecycle = registerPushRegistrationLifecycle({
@@ -159,49 +274,93 @@ function usePushNotifications(
unregisterForLogout,
});
onCleanup(removeLifecycle);
+ onCleanup(() => {
+ disposed = true;
+ ++registrationEpoch;
+ clearTimeout(watchRetryTimeout);
+ void stopWatch();
+ });
+
+ async function stopWatch() {
+ try {
+ await api.unwatch();
+ } catch (error) {
+ console.error(error);
+ }
+ }
- // On launch, once permission state resolves, ensure persisted state is
- // synced correctly and — when a session exists — re-register the device so
- // the backend registration tracks the current user (covering both an APNs
- // token rotation and an account switch since the last launch).
- whenSettled(
- systemPermission,
- (perm) => {
- // OS permission was revoked externally (iOS Settings) — clear the
- // persisted registration state so it never claims 'granted' when
- // notifications can't display.
- if (perm.status !== 'granted') {
+ // On launch, re-register the device so the backend registration tracks the
+ // current user (covering both a token rotation and an account switch since
+ // the last launch). The lifecycle sync also clears state when the OS
+ // permission was revoked; only the cases it skips are handled here.
+ void reconcileOnLaunch();
+
+ async function reconcileOnLaunch() {
+ const epoch = registrationEpoch;
+ try {
+ if (!hasLoginCookie() || pushDisabledByUser()) {
setPermission(undefined);
+ await configureRecipient(null, epoch);
return;
}
- if (!hasLoginCookie()) {
- // Logged out: nothing to register against; login will sync.
- return;
- }
- // Sync via the lifecycle registry so the launch path gets the same
- // one-retry behavior as login (registrations are idempotent).
- syncPushRegistrations().catch(console.error);
- },
- console.error
- );
+ await syncPushRegistrations('resume');
+ } catch (error) {
+ console.error('push launch sync failed', error);
+ }
+ }
- const [notificationWatchStarted, setNotificationWatchStarted] =
- createSignal(false);
createEffect(() => {
- if (!registrationResult()?.success || !onPushNotification) return;
- if (notificationWatchStarted()) return;
-
- setNotificationWatchStarted(true);
- void watchNotifications(onPushNotification).catch(() => {
- setNotificationWatchStarted(false);
- });
+ if (!onPushNotification) return;
+ if (deviceType === 'ios' && !registrationResult()?.success) return;
+ void startWatch();
});
+ function startWatch() {
+ if (disposed || !onPushNotification) return;
+ if (notificationWatch) return notificationWatch;
+ clearTimeout(watchRetryTimeout);
+ notificationWatch = watchNotifications();
+ return notificationWatch;
+ }
+
+ async function watchNotifications() {
+ const epoch = registrationEpoch;
+ try {
+ if (deviceType === 'android' && !hasLoginCookie())
+ await configureRecipient(null, epoch);
+ await api.watch((event) => {
+ void handlePushEvent(event);
+ });
+ if (disposed) await api.unwatch();
+ } catch (error) {
+ notificationWatch = undefined;
+ console.error('failed to watch push notifications', error);
+ if (!disposed) {
+ watchRetryTimeout = setTimeout(() => void startWatch(), 1000);
+ }
+ }
+ }
+
+ async function handlePushEvent(event: PushEvent) {
+ if (disposed || !hasLoginCookie()) return;
+ try {
+ if (event.type === 'TOKEN_REFRESH' || event.type === 'RESUME') {
+ await syncPushRegistrations('resume');
+ return;
+ }
+ onPushNotification?.(event);
+ if (event.deliveryId) await api.acknowledge(event.deliveryId);
+ } catch (error) {
+ console.error('push event handling failed', error);
+ }
+ }
+
return {
permission,
requestNotificationRegistration,
registrationResult,
unregisterPushNotifications,
+ checkPermissions: api.checkPermissions,
};
}
@@ -217,11 +376,7 @@ export function MaybePushNotificationRegistration(props: {
}) {
const { os } = useExpectTauri();
- // Android remote push requires the token/permission/watcher implementation
- // tracked by Android task 02. Its current scaffold throws without Firebase
- // configuration and does not implement watchNotifications. Keep local
- // notifications usable while the Android app shell is brought up.
- if (os !== 'ios') {
+ if (os !== 'ios' && os !== 'android') {
return (
<PushNotificationContext.Provider value={'not-supported'}>
<PlatformNotificationProvider
@@ -268,7 +423,7 @@ export function MaybePushNotificationRegistration(props: {
return baseShowNotification(data);
},
getCurrentPermission: async () => {
- const sysPerm = await checkPermissions();
+ const sysPerm = await push.checkPermissions();
if (sysPerm.status === 'prompt') {
return 'default';
}
diff --git a/apps/web/src/lib/tauri/push-api.ts b/apps/web/src/lib/tauri/push-api.ts
new file mode 100644
index 0000000000..7767ca1aa3
--- /dev/null
+++ b/apps/web/src/lib/tauri/push-api.ts
@@ -0,0 +1,63 @@
+import * as ios from '@inkibra/tauri-plugins/packages/tauri-plugin-notifications';
+import { Channel, invoke } from '@tauri-apps/api/core';
+
+type LifecycleEvent<Type extends 'TOKEN_REFRESH' | 'RESUME'> = {
+ type: Type;
+ payload: Record<string, string>;
+};
+
+// One member per lifecycle type so a handler that returns early on them
+// narrows the rest to NotificationEvent.
+export type PushEvent =
+ | (ios.NotificationEvent & { deliveryId?: string })
+ | LifecycleEvent<'TOKEN_REFRESH'>
+ | LifecycleEvent<'RESUME'>;
+
+/** Keep the Android bridge separate from the existing iOS plugin contract. */
+export function createPushApi(platform: 'android' | 'ios') {
+ const android = platform === 'android';
+ return {
+ checkPermissions: () =>
+ android
+ ? invoke<ios.NotificationPermissionStatus>(
+ 'plugin:android-push|check_permissions'
+ )
+ : ios.checkPermissions(),
+ requestPermissions: () =>
+ android
+ ? invoke<ios.NotificationPermissionStatus>(
+ 'plugin:android-push|request_permissions'
+ )
+ : ios.requestPermissions(),
+ register: () =>
+ android
+ ? invoke<ios.NotificationRegistrationResult>(
+ 'plugin:android-push|register'
+ )
+ : ios.registerForRemoteNotifications(),
+ configureRecipient: async (recipientId: string | null) => {
+ if (android)
+ await invoke('plugin:android-push|configure', {
+ payload: { recipientId },
+ });
+ },
+ watch: async (callback: (event: PushEvent) => void) => {
+ if (!android) {
+ await ios.watchNotifications(callback);
+ return;
+ }
+ const channel = new Channel<PushEvent>();
+ channel.onmessage = callback;
+ await invoke('plugin:android-push|watch', { channel });
+ },
+ unwatch: async () => {
+ if (android) await invoke('plugin:android-push|unwatch');
+ },
+ acknowledge: async (deliveryId: string) => {
+ if (android)
+ await invoke('plugin:android-push|acknowledge', {
+ payload: { deliveryId },
+ });
+ },
+ };
+}
diff --git a/apps/web/tauri/Cargo.lock b/apps/web/tauri/Cargo.lock
index 6296902db8..edacd6f3b9 100644
--- a/apps/web/tauri/Cargo.lock
+++ b/apps/web/tauri/Cargo.lock
@@ -215,6 +215,7 @@ dependencies = [
"tauri",
"tauri-build",
"tauri-plugin-android-auth",
+ "tauri-plugin-android-push",
"tauri-plugin-auth",
"tauri-plugin-call-kit",
"tauri-plugin-deep-link",
@@ -6574,6 +6575,16 @@ dependencies = [
"tauri-plugin",
]
+[[package]]
+name = "tauri-plugin-android-push"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+]
+
[[package]]
name = "tauri-plugin-auth"
version = "0.1.0"
diff --git a/apps/web/tauri/Cargo.toml b/apps/web/tauri/Cargo.toml
index 8b3712046e..897cfbbcef 100644
--- a/apps/web/tauri/Cargo.toml
+++ b/apps/web/tauri/Cargo.toml
@@ -1,6 +1,7 @@
[workspace]
members = [
"android_auth_plugin",
+ "android_push_plugin",
"callkit_plugin",
"edit_menu_plugin",
"graphql_cache_plugin",
diff --git a/apps/web/tauri/android_push_plugin/.gitignore b/apps/web/tauri/android_push_plugin/.gitignore
new file mode 100644
index 0000000000..0614a2a0e9
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/.gitignore
@@ -0,0 +1,4 @@
+# Tauri-generated Android API sources and local build artifacts.
+.tauri/
+build/
+.gradle/
diff --git a/apps/web/tauri/android_push_plugin/Cargo.toml b/apps/web/tauri/android_push_plugin/Cargo.toml
new file mode 100644
index 0000000000..70aade0d51
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "tauri-plugin-android-push"
+version = "0.1.0"
+edition.workspace = true
+links = "tauri-plugin-android-push"
+
+[build-dependencies]
+tauri-plugin = { version = "2.4", features = ["build"] }
+
+[dependencies]
+serde = { workspace = true, features = ["derive"] }
+serde_json = "1"
+tauri = { workspace = true }
diff --git a/apps/web/tauri/android_push_plugin/android/build.gradle.kts b/apps/web/tauri/android_push_plugin/android/build.gradle.kts
new file mode 100644
index 0000000000..4052cfd351
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/build.gradle.kts
@@ -0,0 +1,23 @@
+plugins {
+ id("com.android.library")
+ id("org.jetbrains.kotlin.android")
+}
+
+android {
+ namespace = "com.macro.push"
+ compileSdk = 36
+ defaultConfig { minSdk = 24 }
+ 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("com.google.firebase:firebase-messaging:24.1.0")
+ testImplementation("junit:junit:4.13.2")
+}
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/AndroidManifest.xml b/apps/web/tauri/android_push_plugin/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..8ef3c7ec19
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/AndroidManifest.xml
@@ -0,0 +1,10 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+ <application>
+ <service android:name="com.macro.push.PushService" android:exported="false">
+ <intent-filter>
+ <action android:name="com.google.firebase.MESSAGING_EVENT" />
+ </intent-filter>
+ </service>
+ </application>
+</manifest>
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushMessage.kt b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushMessage.kt
new file mode 100644
index 0000000000..1d59c186ec
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushMessage.kt
@@ -0,0 +1,24 @@
+package com.macro.push
+
+/** The backend data-only FCM contract. Reject unknown or unowned messages. */
+internal data class PushMessage(
+ val identifier: String,
+ val recipientId: String,
+ val clear: Boolean,
+ val title: String,
+ val body: String,
+ val payload: String,
+) {
+ companion object {
+ fun parse(data: Map<String, String>, activeRecipient: String?): PushMessage? {
+ val recipient = data["recipientId"] ?: return null
+ if (activeRecipient.isNullOrEmpty() || recipient != activeRecipient) return null
+ val identifier = data["identifier"]?.takeIf { it.isNotBlank() } ?: return null
+ val type = data["type"]
+ if (type != "notification" && type != "clear") return null
+ if (type == "notification" && data["title"].isNullOrBlank() && data["body"].isNullOrBlank()) return null
+ return PushMessage(identifier, recipient, type == "clear", data["title"].orEmpty(),
+ data["body"].orEmpty(), data["payload"] ?: "{}")
+ }
+ }
+}
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushPlugin.kt b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushPlugin.kt
new file mode 100644
index 0000000000..2111c882a9
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushPlugin.kt
@@ -0,0 +1,111 @@
+package com.macro.push
+
+import android.Manifest
+import android.app.Activity
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.os.Build
+import android.util.Log
+import android.webkit.WebView
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.content.ContextCompat
+import app.tauri.annotation.Command
+import app.tauri.annotation.InvokeArg
+import app.tauri.annotation.Permission
+import app.tauri.annotation.PermissionCallback
+import app.tauri.annotation.TauriPlugin
+import app.tauri.plugin.Channel
+import app.tauri.plugin.Invoke
+import app.tauri.plugin.JSObject
+import app.tauri.plugin.Plugin
+import com.google.firebase.FirebaseApp
+import com.google.firebase.messaging.FirebaseMessaging
+
+@InvokeArg
+internal class ConfigureArgs { var recipientId: String? = null }
+@InvokeArg
+internal class WatchArgs { lateinit var channel: Channel }
+@InvokeArg
+internal class AcknowledgeArgs { lateinit var deliveryId: String }
+
+@TauriPlugin(permissions = [Permission(strings = [Manifest.permission.POST_NOTIFICATIONS], alias = "notifications")])
+class PushPlugin(private val activity: Activity) : Plugin(activity) {
+ private companion object { const val TAG = "MacroPush" }
+
+ override fun load(webView: WebView) {
+ PushStore.createChannel(activity)
+ PushStore.tap(activity, activity.intent)
+ }
+
+ override fun onNewIntent(intent: Intent) { PushStore.tap(activity, intent) }
+ override fun onResume(activity: AppCompatActivity) {
+ PushStore.foreground = true
+ PushStore.emit("RESUME")
+ }
+ override fun onPause(activity: AppCompatActivity) { PushStore.foreground = false }
+ override fun onDestroy(activity: AppCompatActivity) { PushStore.unwatch() }
+
+ @Command
+ override fun checkPermissions(invoke: Invoke) {
+ PushStore.createChannel(activity)
+ val asked = PushStore.prefs(activity).getBoolean("asked", false)
+ val status = when {
+ PushStore.canDisplay(activity) -> "granted"
+ Build.VERSION.SDK_INT >= 33 && !asked &&
+ ContextCompat.checkSelfPermission(activity, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED -> "prompt"
+ else -> "denied"
+ }
+ invoke.resolve(JSObject().apply { put("status", status) })
+ }
+
+ @Command
+ override fun requestPermissions(invoke: Invoke) {
+ if (Build.VERSION.SDK_INT < 33 || PushStore.canDisplay(activity)) {
+ checkPermissions(invoke)
+ return
+ }
+ PushStore.prefs(activity).edit().putBoolean("asked", true).apply()
+ requestPermissionForAlias("notifications", invoke, "permissionResult")
+ }
+
+ @PermissionCallback
+ fun permissionResult(invoke: Invoke) { checkPermissions(invoke) }
+
+ @Command
+ fun register(invoke: Invoke) {
+ if (FirebaseApp.initializeApp(activity) == null) {
+ invoke.resolve(JSObject().apply { put("success", false); put("error", "Firebase is not configured") })
+ return
+ }
+ FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
+ if (!task.isSuccessful) Log.w(TAG, "FCM token request failed", task.exception)
+ invoke.resolve(JSObject().apply {
+ put("success", task.isSuccessful)
+ if (task.isSuccessful) put("token", task.result)
+ else put("error", task.exception?.message ?: "Could not register for push notifications")
+ })
+ }
+ }
+
+ @Command
+ fun configure(invoke: Invoke) {
+ val args = invoke.parseArgs(ConfigureArgs::class.java)
+ PushStore.configure(activity, args.recipientId?.takeIf { it.isNotBlank() })
+ invoke.resolve()
+ }
+
+ @Command
+ fun watch(invoke: Invoke) {
+ PushStore.watch(activity, invoke.parseArgs(WatchArgs::class.java).channel)
+ invoke.resolve()
+ }
+
+ @Command
+ fun unwatch(invoke: Invoke) { PushStore.unwatch(); invoke.resolve() }
+
+ @Command
+ fun acknowledge(invoke: Invoke) {
+ PushStore.acknowledge(activity, invoke.parseArgs(AcknowledgeArgs::class.java).deliveryId)
+ invoke.resolve()
+ }
+}
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
new file mode 100644
index 0000000000..9402bd174e
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushService.kt
@@ -0,0 +1,16 @@
+package com.macro.push
+
+import com.google.firebase.messaging.FirebaseMessagingService
+import com.google.firebase.messaging.RemoteMessage
+
+class PushService : FirebaseMessagingService() {
+ override fun onMessageReceived(message: RemoteMessage) {
+ PushStore.receive(this, message.data, message.sentTime)
+ }
+
+ override fun onNewToken(token: String) {
+ // Never log tokens. Foreground JS re-registers; cold starts always fetch
+ // the current Firebase token, covering refresh while JS wasn't running.
+ PushStore.emit("TOKEN_REFRESH")
+ }
+}
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
new file mode 100644
index 0000000000..d859f45116
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/java/com/macro/push/PushStore.kt
@@ -0,0 +1,193 @@
+package com.macro.push
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import android.content.SharedPreferences
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import app.tauri.plugin.Channel
+import app.tauri.plugin.JSObject
+import org.json.JSONObject
+import java.util.UUID
+
+/** Persisted display/tap state survives ordinary process death, independently of the WebView. */
+internal object PushStore {
+ const val CHANNEL_ID = "macro_activity"
+ private const val TAP_EXTRA = "com.macro.push.TAP"
+ private const val MAX_RECORDS = 128
+ private var watcher: Channel? = null
+ private var ready = false
+ @Volatile var foreground = false
+ private var generation = 0
+ private val main = Handler(Looper.getMainLooper())
+
+ fun prefs(context: Context): SharedPreferences = context.getSharedPreferences("macro_push", Context.MODE_PRIVATE)
+ private fun records(context: Context): JSONObject =
+ runCatching { JSONObject(prefs(context).getString("records", "{}")!!) }.getOrDefault(JSONObject())
+
+ fun createChannel(context: Context) {
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.getSystemService(NotificationManager::class.java).createNotificationChannel(
+ NotificationChannel(CHANNEL_ID, "Activity", NotificationManager.IMPORTANCE_HIGH).apply {
+ description = "Messages, mentions, email and other Macro activity"
+ }
+ )
+ }
+ }
+
+ fun canDisplay(context: Context): Boolean {
+ if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return false
+ return Build.VERSION.SDK_INT < Build.VERSION_CODES.O ||
+ context.getSystemService(NotificationManager::class.java)
+ .getNotificationChannel(CHANNEL_ID)?.importance != NotificationManager.IMPORTANCE_NONE
+ }
+
+ @Synchronized
+ fun configure(context: Context, recipient: String?) {
+ val preferences = prefs(context)
+ if (recipient != preferences.getString("recipient", null) || recipient == null) {
+ generation++
+ val old = records(context)
+ old.keys().forEach { NotificationManagerCompat.from(context).cancel(it, 0) }
+ preferences.edit().remove("records").putString("recipient", recipient).apply()
+ }
+ ready = recipient != null
+ flush(context)
+ }
+
+ @Synchronized
+ fun watch(context: Context, channel: Channel) {
+ watcher = channel
+ flush(context)
+ }
+
+ @Synchronized
+ fun unwatch() { watcher = null; ready = false }
+
+ @Synchronized
+ fun emit(type: String, payload: JSONObject = JSONObject(), deliveryId: String? = null) {
+ val channel = watcher ?: return
+ val expectedGeneration = generation
+ main.post {
+ synchronized(this) {
+ if (watcher === channel && generation == expectedGeneration) {
+ channel.send(JSObject().apply {
+ put("type", type); put("payload", payload)
+ if (deliveryId != null) put("deliveryId", deliveryId)
+ })
+ }
+ }
+ }
+ }
+
+ @Synchronized
+ fun receive(context: Context, data: Map<String, String>, sentTime: Long) {
+ val message = PushMessage.parse(data, prefs(context).getString("recipient", null)) ?: return
+ val all = records(context)
+ val previous = all.optJSONObject(message.identifier)
+ // FCM may reorder high-priority alerts and normal-priority clears.
+ if (previous != null && sentTime < previous.optLong("sentTime")) return
+ val manager = NotificationManagerCompat.from(context)
+ if (message.clear) {
+ manager.cancel(message.identifier, 0)
+ all.put(message.identifier, JSONObject().put("sentTime", sentTime))
+ save(context, all)
+ return
+ }
+ val payload = runCatching { JSONObject(message.payload) }.getOrNull() ?: return
+ val notificationId = payload.optString("notificationId")
+ if (runCatching { UUID.fromString(notificationId) }.isFailure) return
+ if (previous?.optString("notificationId") == notificationId) return
+ // On an equal sentTime the clear wins: an alert sent in the same
+ // millisecond as its clear must not resurface after the clear landed.
+ if (previous != null && sentTime == previous.optLong("sentTime") && !previous.has("notificationId")) return
+ createChannel(context)
+ if (!canDisplay(context)) return
+ val tapToken = UUID.randomUUID().toString()
+ val launch = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return
+ launch.action = "com.macro.push.OPEN.$tapToken"
+ launch.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
+ launch.putExtra(TAP_EXTRA, tapToken)
+ val pending = PendingIntent.getActivity(context, 0, launch,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
+ val record = JSONObject().put("sentTime", sentTime)
+ .put("notificationId", notificationId).put("token", tapToken)
+ .put("payload", payload).put("pendingTap", false)
+ all.put(message.identifier, record)
+ save(context, all)
+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(R.drawable.ic_macro_notification)
+ .setContentTitle(message.title.ifBlank { "Macro" })
+ .setContentText(message.body)
+ .setStyle(NotificationCompat.BigTextStyle().bigText(message.body))
+ .setContentIntent(pending).setAutoCancel(true).setOnlyAlertOnce(true)
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
+ .setPriority(NotificationCompat.PRIORITY_HIGH).build()
+ try {
+ manager.notify(message.identifier, 0, notification)
+ } catch (_: SecurityException) {
+ // Permission can be revoked between the check and notify().
+ return
+ }
+ emit(if (foreground) "FOREGROUND_DELIVERY" else "BACKGROUND_DELIVERY", payload)
+ }
+
+ @Synchronized
+ fun tap(context: Context, intent: Intent) {
+ val token = intent.getStringExtra(TAP_EXTRA) ?: return
+ intent.removeExtra(TAP_EXTRA)
+ val all = records(context)
+ val id = all.keys().asSequence().firstOrNull { all.optJSONObject(it)?.optString("token") == token } ?: return
+ val record = all.getJSONObject(id)
+ record.put("pendingTap", true)
+ record.put("deliveryId", UUID.randomUUID().toString())
+ record.put("tapType", if (foreground) "FOREGROUND_TAP" else "BACKGROUND_TAP")
+ // A one-use local token prevents exported activity intents from injecting payloads.
+ record.remove("token")
+ save(context, all)
+ NotificationManagerCompat.from(context).cancel(id, 0)
+ flush(context)
+ }
+
+ private fun flush(context: Context) {
+ if (!ready || watcher == null || prefs(context).getString("recipient", null) == null) return
+ val all = records(context)
+ all.keys().forEach { id ->
+ val record = all.getJSONObject(id)
+ if (record.optBoolean("pendingTap")) {
+ emit(record.getString("tapType"), record.getJSONObject("payload"), record.getString("deliveryId"))
+ }
+ }
+ }
+
+ @Synchronized
+ fun acknowledge(context: Context, deliveryId: String) {
+ val all = records(context)
+ all.keys().forEach { id ->
+ val record = all.getJSONObject(id)
+ if (record.optString("deliveryId") == deliveryId) {
+ record.put("pendingTap", false)
+ record.remove("deliveryId")
+ }
+ }
+ save(context, all)
+ }
+
+ private fun save(context: Context, all: JSONObject) {
+ while (all.length() > MAX_RECORDS) {
+ val oldest = all.keys().asSequence().minByOrNull { all.getJSONObject(it).optLong("sentTime") } ?: break
+ all.remove(oldest)
+ NotificationManagerCompat.from(context).cancel(oldest, 0)
+ }
+ // apply() keeps the write off the caller's thread; tap() and configure()
+ // run on the main thread. The framework flushes pending writes before
+ // the process is stopped.
+ prefs(context).edit().putString("records", all.toString()).apply()
+ }
+}
diff --git a/apps/web/tauri/android_push_plugin/android/src/main/res/drawable/ic_macro_notification.xml b/apps/web/tauri/android_push_plugin/android/src/main/res/drawable/ic_macro_notification.xml
new file mode 100644
index 0000000000..fcacb75925
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/main/res/drawable/ic_macro_notification.xml
@@ -0,0 +1,8 @@
+<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:width="24dp" android:height="24dp"
+ android:viewportWidth="24" android:viewportHeight="24">
+ <!-- Monochrome form of src/components/icon/macro-logo.svg. -->
+ <path android:fillColor="#FFFFFFFF" android:pathData="M0,10.014v6.801a0.75,0.75 0,0 0,0.225 0.513l2.742,2.644 2.002,-0.8v-7.099l-2.97,-2.859z" />
+ <path android:fillColor="#FFFFFFFF" android:pathData="M4.078,4.8v5.786l1.36,1.309v1.313L12.481,20l2.002,-0.8 -0.001,-7.1L6.078,4z" />
+ <path android:fillColor="#FFFFFFFF" android:pathData="M13.594,4.8v5.786l1.36,1.311 -0.013,1.3L22,20 24,19.2V12.42a0.75,0.75 0,0 0,-0.225 -0.533L15.595,4z" />
+</vector>
diff --git a/apps/web/tauri/android_push_plugin/android/src/test/java/com/macro/push/PushMessageTest.kt b/apps/web/tauri/android_push_plugin/android/src/test/java/com/macro/push/PushMessageTest.kt
new file mode 100644
index 0000000000..86103bc667
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/android/src/test/java/com/macro/push/PushMessageTest.kt
@@ -0,0 +1,29 @@
+package com.macro.push
+
+import org.junit.Assert.*
+import org.junit.Test
+
+class PushMessageTest {
+ private val recipient = "macro|[email protected]"
+ private val alert = mapOf("type" to "notification", "recipientId" to recipient,
+ "identifier" to "channel-id", "title" to "Alice", "body" to "Hello", "payload" to "{}")
+
+ @Test fun acceptsAlertsOnlyForTheActiveAccount() {
+ assertEquals("Hello", PushMessage.parse(alert, recipient)?.body)
+ assertNull(PushMessage.parse(alert, null))
+ assertNull(PushMessage.parse(alert, "macro|[email protected]"))
+ assertNull(PushMessage.parse(alert - "recipientId", recipient))
+ }
+
+ @Test fun acceptsSilentClearWithoutTitleOrBody() {
+ val message = PushMessage.parse((alert - "title" - "body") + ("type" to "clear"), recipient)
+ assertTrue(message!!.clear)
+ assertEquals("channel-id", message.identifier)
+ }
+
+ @Test fun rejectsUnknownOrIncompleteMessages() {
+ assertNull(PushMessage.parse(alert + ("type" to "unknown"), recipient))
+ assertNull(PushMessage.parse(alert - "identifier", recipient))
+ assertNull(PushMessage.parse(alert - "title" - "body", recipient))
+ }
+}
diff --git a/apps/web/tauri/android_push_plugin/build.rs b/apps/web/tauri/android_push_plugin/build.rs
new file mode 100644
index 0000000000..0298f2852a
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/build.rs
@@ -0,0 +1,13 @@
+fn main() {
+ tauri_plugin::Builder::new(&[
+ "check_permissions",
+ "request_permissions",
+ "register",
+ "configure",
+ "watch",
+ "unwatch",
+ "acknowledge",
+ ])
+ .android_path("android")
+ .build();
+}
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/acknowledge.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/acknowledge.toml
new file mode 100644
index 0000000000..5abc9d2f6a
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/acknowledge.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-acknowledge"
+description = "Enables the acknowledge command without any pre-configured scope."
+commands.allow = ["acknowledge"]
+
+[[permission]]
+identifier = "deny-acknowledge"
+description = "Denies the acknowledge command without any pre-configured scope."
+commands.deny = ["acknowledge"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/check_permissions.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/check_permissions.toml
new file mode 100644
index 0000000000..f5af08b137
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/check_permissions.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-check-permissions"
+description = "Enables the check_permissions command without any pre-configured scope."
+commands.allow = ["check_permissions"]
+
+[[permission]]
+identifier = "deny-check-permissions"
+description = "Denies the check_permissions command without any pre-configured scope."
+commands.deny = ["check_permissions"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/configure.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/configure.toml
new file mode 100644
index 0000000000..223b344e2c
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/configure.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-configure"
+description = "Enables the configure command without any pre-configured scope."
+commands.allow = ["configure"]
+
+[[permission]]
+identifier = "deny-configure"
+description = "Denies the configure command without any pre-configured scope."
+commands.deny = ["configure"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/register.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/register.toml
new file mode 100644
index 0000000000..4eec17dc7d
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/register.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-register"
+description = "Enables the register command without any pre-configured scope."
+commands.allow = ["register"]
+
+[[permission]]
+identifier = "deny-register"
+description = "Denies the register command without any pre-configured scope."
+commands.deny = ["register"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/request_permissions.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/request_permissions.toml
new file mode 100644
index 0000000000..02dcd62718
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/request_permissions.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-request-permissions"
+description = "Enables the request_permissions command without any pre-configured scope."
+commands.allow = ["request_permissions"]
+
+[[permission]]
+identifier = "deny-request-permissions"
+description = "Denies the request_permissions command without any pre-configured scope."
+commands.deny = ["request_permissions"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/unwatch.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/unwatch.toml
new file mode 100644
index 0000000000..3259e9a671
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/unwatch.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-unwatch"
+description = "Enables the unwatch command without any pre-configured scope."
+commands.allow = ["unwatch"]
+
+[[permission]]
+identifier = "deny-unwatch"
+description = "Denies the unwatch command without any pre-configured scope."
+commands.deny = ["unwatch"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/watch.toml b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/watch.toml
new file mode 100644
index 0000000000..8dd1b57724
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/commands/watch.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-watch"
+description = "Enables the watch command without any pre-configured scope."
+commands.allow = ["watch"]
+
+[[permission]]
+identifier = "deny-watch"
+description = "Denies the watch command without any pre-configured scope."
+commands.deny = ["watch"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/autogenerated/reference.md b/apps/web/tauri/android_push_plugin/permissions/autogenerated/reference.md
new file mode 100644
index 0000000000..b9bf47f82c
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/autogenerated/reference.md
@@ -0,0 +1,205 @@
+## Default Permission
+
+Android notification permission, registration and event bridge.
+
+#### This default permission set includes the following:
+
+- `allow-check-permissions`
+- `allow-request-permissions`
+- `allow-register`
+- `allow-configure`
+- `allow-watch`
+- `allow-unwatch`
+- `allow-acknowledge`
+
+## Permission Table
+
+<table>
+<tr>
+<th>Identifier</th>
+<th>Description</th>
+</tr>
+
+
+<tr>
+<td>
+
+`android-push:allow-acknowledge`
+
+</td>
+<td>
+
+Enables the acknowledge command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-acknowledge`
+
+</td>
+<td>
+
+Denies the acknowledge command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-check-permissions`
+
+</td>
+<td>
+
+Enables the check_permissions command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-check-permissions`
+
+</td>
+<td>
+
+Denies the check_permissions command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-configure`
+
+</td>
+<td>
+
+Enables the configure command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-configure`
+
+</td>
+<td>
+
+Denies the configure command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-register`
+
+</td>
+<td>
+
+Enables the register command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-register`
+
+</td>
+<td>
+
+Denies the register command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-request-permissions`
+
+</td>
+<td>
+
+Enables the request_permissions command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-request-permissions`
+
+</td>
+<td>
+
+Denies the request_permissions command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-unwatch`
+
+</td>
+<td>
+
+Enables the unwatch command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-unwatch`
+
+</td>
+<td>
+
+Denies the unwatch command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:allow-watch`
+
+</td>
+<td>
+
+Enables the watch command without any pre-configured scope.
+
+</td>
+</tr>
+
+<tr>
+<td>
+
+`android-push:deny-watch`
+
+</td>
+<td>
+
+Denies the watch command without any pre-configured scope.
+
+</td>
+</tr>
+</table>
diff --git a/apps/web/tauri/android_push_plugin/permissions/default.toml b/apps/web/tauri/android_push_plugin/permissions/default.toml
new file mode 100644
index 0000000000..dd140d01c0
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/default.toml
@@ -0,0 +1,3 @@
+[default]
+description = "Android notification permission, registration and event bridge."
+permissions = ["allow-check-permissions", "allow-request-permissions", "allow-register", "allow-configure", "allow-watch", "allow-unwatch", "allow-acknowledge"]
diff --git a/apps/web/tauri/android_push_plugin/permissions/schemas/schema.json b/apps/web/tauri/android_push_plugin/permissions/schemas/schema.json
new file mode 100644
index 0000000000..8b4b7bfbf7
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/permissions/schemas/schema.json
@@ -0,0 +1,390 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `<h4>` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the acknowledge command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-acknowledge",
+ "markdownDescription": "Enables the acknowledge command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the acknowledge command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-acknowledge",
+ "markdownDescription": "Denies the acknowledge command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the check_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-check-permissions",
+ "markdownDescription": "Enables the check_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the check_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-check-permissions",
+ "markdownDescription": "Denies the check_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the configure command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-configure",
+ "markdownDescription": "Enables the configure command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the configure command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-configure",
+ "markdownDescription": "Denies the configure command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the register command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-register",
+ "markdownDescription": "Enables the register command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the register command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-register",
+ "markdownDescription": "Denies the register command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the request_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-request-permissions",
+ "markdownDescription": "Enables the request_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the request_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-request-permissions",
+ "markdownDescription": "Denies the request_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the unwatch command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-unwatch",
+ "markdownDescription": "Enables the unwatch command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the unwatch command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-unwatch",
+ "markdownDescription": "Denies the unwatch command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the watch command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-watch",
+ "markdownDescription": "Enables the watch command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the watch command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-watch",
+ "markdownDescription": "Denies the watch command without any pre-configured scope."
+ },
+ {
+ "description": "Android notification permission, registration and event bridge.\n#### This default permission set includes:\n\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-register`\n- `allow-configure`\n- `allow-watch`\n- `allow-unwatch`\n- `allow-acknowledge`",
+ "type": "string",
+ "const": "default",
+ "markdownDescription": "Android notification permission, registration and event bridge.\n#### This default permission set includes:\n\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-register`\n- `allow-configure`\n- `allow-watch`\n- `allow-unwatch`\n- `allow-acknowledge`"
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/apps/web/tauri/android_push_plugin/src/android.rs b/apps/web/tauri/android_push_plugin/src/android.rs
new file mode 100644
index 0000000000..734a5b9fad
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/src/android.rs
@@ -0,0 +1,75 @@
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use tauri::{AppHandle, Manager, Runtime, ipc::Channel, plugin::PluginHandle};
+
+pub(crate) struct Push<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::<Push<R>>()
+ .0
+ .run_mobile_plugin_async($native, ())
+ .await
+ .map_err(|error| error.to_string())
+ }
+ };
+}
+command!(check_permissions, "checkPermissions");
+command!(request_permissions, "requestPermissions");
+command!(register, "register");
+command!(unwatch, "unwatch");
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct AcknowledgeArgs {
+ delivery_id: String,
+}
+
+#[tauri::command]
+pub(crate) async fn acknowledge<R: Runtime>(
+ app: AppHandle<R>,
+ payload: AcknowledgeArgs,
+) -> Result<(), String> {
+ app.state::<Push<R>>()
+ .0
+ .run_mobile_plugin_async("acknowledge", payload)
+ .await
+ .map_err(|error| error.to_string())
+}
+
+#[derive(Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct ConfigureArgs {
+ recipient_id: Option<String>,
+}
+
+#[tauri::command]
+pub(crate) async fn configure<R: Runtime>(
+ app: AppHandle<R>,
+ payload: ConfigureArgs,
+) -> Result<(), String> {
+ app.state::<Push<R>>()
+ .0
+ .run_mobile_plugin_async("configure", payload)
+ .await
+ .map_err(|error| error.to_string())
+}
+
+#[derive(Serialize)]
+struct WatchArgs {
+ channel: Channel<Value>,
+}
+
+#[tauri::command]
+pub(crate) async fn watch<R: Runtime>(
+ app: AppHandle<R>,
+ channel: Channel<Value>,
+) -> Result<(), String> {
+ app.state::<Push<R>>()
+ .0
+ .run_mobile_plugin_async("watch", WatchArgs { channel })
+ .await
+ .map_err(|error| error.to_string())
+}
diff --git a/apps/web/tauri/android_push_plugin/src/lib.rs b/apps/web/tauri/android_push_plugin/src/lib.rs
new file mode 100644
index 0000000000..2949fdcb5d
--- /dev/null
+++ b/apps/web/tauri/android_push_plugin/src/lib.rs
@@ -0,0 +1,31 @@
+//! Android remote notifications. iOS retains its existing push plugin.
+#![deny(missing_docs)]
+
+use tauri::Runtime;
+use tauri::plugin::{Builder, TauriPlugin};
+
+#[cfg(target_os = "android")]
+mod android;
+
+/// Register the Android Firebase receiver bridge.
+pub fn init<R: Runtime>() -> TauriPlugin<R> {
+ let builder = Builder::new("android-push");
+ #[cfg(target_os = "android")]
+ let builder = builder
+ .invoke_handler(tauri::generate_handler![
+ android::check_permissions,
+ android::request_permissions,
+ android::register,
+ android::configure,
+ android::watch,
+ android::unwatch,
+ android::acknowledge,
+ ])
+ .setup(|app, api| {
+ use tauri::Manager;
+ let handle = api.register_android_plugin("com.macro.push", "PushPlugin")?;
+ app.manage(android::Push(handle));
+ Ok(())
+ });
+ builder.build()
+}
diff --git a/apps/web/tauri/src-tauri/Cargo.toml b/apps/web/tauri/src-tauri/Cargo.toml
index ca996d169e..660543a9d4 100644
--- a/apps/web/tauri/src-tauri/Cargo.toml
+++ b/apps/web/tauri/src-tauri/Cargo.toml
@@ -78,6 +78,7 @@ tauri-plugin-haptics = "2"
jni = "0.21"
rustls-platform-verifier = "0.6"
tauri-plugin-android-auth = { path = "../android_auth_plugin" }
+tauri-plugin-android-push = { path = "../android_push_plugin" }
[target.'cfg(target_os = "ios")'.dependencies]
tauri-plugin-auth = { git = "https://github.com/macro-inc/tauri-plugins", rev = "6ddd6600e20436388f169e936b610fe93944b7b0" }
diff --git a/apps/web/tauri/src-tauri/capabilities/android.json b/apps/web/tauri/src-tauri/capabilities/android.json
index 58f5490605..f3e1cf1182 100644
--- a/apps/web/tauri/src-tauri/capabilities/android.json
+++ b/apps/web/tauri/src-tauri/capabilities/android.json
@@ -7,6 +7,7 @@
"main"
],
"permissions": [
- "android-auth:allow-authenticate"
+ "android-auth:allow-authenticate",
+ "android-push:default"
]
}
diff --git a/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt b/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
index 254cf10a2f..eae8581aa2 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
+++ b/apps/web/tauri/src-tauri/gen/android/app/src/main/java/com/macro/app/prod/MainActivity.kt
@@ -2,6 +2,7 @@ package com.macro.app.prod
import android.os.Bundle
import android.content.Context
+import android.content.Intent
import androidx.activity.enableEdgeToEdge
class MainActivity : TauriActivity() {
@@ -11,6 +12,13 @@ class MainActivity : TauriActivity() {
private external fun initializeCertificateVerifier(context: Context): Boolean
+ override fun onNewIntent(intent: Intent) {
+ // Android can restore an existing task before Tauri's plugins have loaded.
+ // Keep its latest intent available for the push plugin's load callback.
+ setIntent(intent)
+ super.onNewIntent(intent)
+ }
+
override fun onCreate(savedInstanceState: Bundle?) {
check(initializeCertificateVerifier(applicationContext)) {
"Unable to initialize Android certificate verification"
diff --git a/apps/web/tauri/src-tauri/src/lib.rs b/apps/web/tauri/src-tauri/src/lib.rs
index 57d9e9a6ed..049a30920a 100644
--- a/apps/web/tauri/src-tauri/src/lib.rs
+++ b/apps/web/tauri/src-tauri/src/lib.rs
@@ -161,6 +161,7 @@ pub fn run() {
{
builder = builder
.plugin(tauri_plugin_auth::init())
+ .plugin(tauri_plugin_notifications::init())
.plugin(tauri_plugin_virtual_keyboard::init())
.plugin(tauri_plugin_edit_menu::init())
.plugin(tauri_plugin_input_accessory::init())
@@ -172,7 +173,9 @@ pub fn run() {
#[cfg(target_os = "android")]
{
- builder = builder.plugin(tauri_plugin_android_auth::init());
+ builder = builder
+ .plugin(tauri_plugin_android_auth::init())
+ .plugin(tauri_plugin_android_push::init());
}
// register the rest of the common plugins
@@ -221,8 +224,7 @@ pub fn run() {
// register mobile specific plugins
builder = builder
.plugin(tauri_plugin_haptics::init())
- .plugin(tauri_plugin_safe_area_insets::init())
- .plugin(tauri_plugin_notifications::init());
+ .plugin(tauri_plugin_safe_area_insets::init());
}
// Window origin differs by platform:
diff --git a/crates/notification/src/domain/models/android.rs b/crates/notification/src/domain/models/android.rs
index 8805958467..c0b7b271f8 100644
--- a/crates/notification/src/domain/models/android.rs
+++ b/crates/notification/src/domain/models/android.rs
@@ -1,42 +1,49 @@
-//! Android push notification models (FCM via SNS).
+//! Android push notification content.
+use macro_user_id::user_id::MacroUserIdStr;
use serde::Serialize;
-/// FCM push notification message for Android devices.
+/// Content for an Android push. The outbound adapter encodes the FCM transport.
#[derive(Debug, Serialize)]
pub struct FCMMessage<T> {
- pub(crate) android: AndroidData,
- data: T,
+ /// Intended account, checked by the device before display or navigation.
+ pub recipient_id: MacroUserIdStr<'static>,
+ /// Visible title, absent for a notification-clear command.
+ pub title: Option<String>,
+ /// Visible body, absent for a notification-clear command.
+ pub body: Option<String>,
+ /// Stable identifier used to replace or clear the displayed notification.
+ pub identifier: String,
+ /// Client metadata, including the notification ID used for tap navigation.
+ pub data: T,
}
impl<T> FCMMessage<T> {
- /// temporary method since android is currently out of scope for mobile
- /// this just instantiates a majority blank notif
- pub fn new_temporary_empty(data: T) -> Self {
- FCMMessage {
- android: AndroidData {
- notification: "Temporary placeholder".to_string(),
- priority: AndroidNotifPrio::Normal,
- collapse_key: String::new(),
- },
+ /// Create a visible Android notification.
+ pub fn notification(
+ title: String,
+ body: String,
+ identifier: String,
+ data: T,
+ recipient_id: MacroUserIdStr<'static>,
+ ) -> Self {
+ Self {
+ recipient_id,
+ title: Some(title),
+ body: Some(body),
+ identifier,
data,
}
}
-}
-
-/// Android notification priority level.
-#[derive(Debug, Serialize)]
-pub enum AndroidNotifPrio {
- /// Normal priority.
- Normal,
- /// High priority.
- High,
-}
-/// Android FCM notification data.
-#[derive(Debug, Serialize)]
-pub struct AndroidData {
- pub(crate) notification: String,
- pub(crate) priority: AndroidNotifPrio,
- pub(crate) collapse_key: String,
+ /// Clear a previously displayed notification without displaying an alert.
+ pub fn clear(identifier: String, data: T, recipient_id: MacroUserIdStr<'static>) -> Self {
+ Self {
+ recipient_id,
+ title: None,
+ body: None,
+ identifier,
+ data,
+ }
+ }
}
diff --git a/crates/notification/src/domain/models/mobile.rs b/crates/notification/src/domain/models/mobile.rs
index a0e69de3e4..b4a0b6830b 100644
--- a/crates/notification/src/domain/models/mobile.rs
+++ b/crates/notification/src/domain/models/mobile.rs
@@ -1,122 +1,8 @@
-//! Mobile push notification models for SNS delivery.
+//! Mobile push notification models.
-use serde::{Deserialize, Serialize, Serializer};
+use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
-use crate::domain::models::{
- android::FCMMessage,
- apple::{APNSPushNotification, Alert, VoipPushPayload},
-};
-
-/// SNS target platform for push notifications.
-#[derive(Debug)]
-pub enum SnsTarget<'a, T> {
- /// iOS target via APNS.
- Ios(&'a APNSPushNotification<T>),
- /// iOS VoIP target via APNS_VOIP.
- Voip(&'a VoipPushPayload),
- /// Android target via FCM.
- Android(&'a FCMMessage<T>),
-}
-
-/// SNS payload formatted for platform-specific delivery.
-#[derive(Debug, Serialize)]
-#[serde(bound = "T: Serialize", untagged)]
-pub(crate) enum SnsPayload<'a, T> {
- /// iOS payload with APNS and APNS_SANDBOX keys.
- Ios {
- /// Default message text.
- default: String,
- /// Production APNS payload.
- #[serde(rename = "APNS", serialize_with = "stringified_json")]
- apns: &'a APNSPushNotification<T>,
- /// Sandbox APNS payload.
- #[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]
- apns_sandbox: &'a APNSPushNotification<T>,
- },
- /// iOS VoIP payload with APNS_VOIP and APNS_VOIP_SANDBOX keys.
- Voip {
- /// Default message text.
- default: String,
- /// Production APNS VoIP payload.
- #[serde(rename = "APNS_VOIP", serialize_with = "stringified_json")]
- apns_voip: &'a VoipPushPayload,
- /// Sandbox APNS VoIP payload.
- #[serde(rename = "APNS_VOIP_SANDBOX", serialize_with = "stringified_json")]
- apns_voip_sandbox: &'a VoipPushPayload,
- },
- /// Android payload with GCM key.
- Android {
- /// Default message text.
- default: String,
- /// FCM payload.
- #[serde(rename = "GCM", serialize_with = "stringified_json")]
- gcm: &'a FCMMessage<T>,
- },
-}
-
-fn stringified_json<T, S>(val: &T, ser: S) -> Result<S::Ok, S::Error>
-where
- S: Serializer,
- T: Serialize,
-{
- let s = serde_json::to_string(val).expect("json serialize cant fail");
- ser.serialize_str(&s)
-}
-
-impl<'a, T> SnsPayload<'a, T>
-where
- T: Serialize,
-{
- fn as_json(&self) -> Result<String, serde_json::Error> {
- serde_json::to_string(self)
- }
-}
-
-impl<T> SnsTarget<'_, T> {
- fn default_string(&self) -> String {
- match self {
- SnsTarget::Ios(apnspush_notification) => apnspush_notification
- .aps
- .alert
- .as_ref()
- .and_then(|a| match a {
- Alert::Simple(s) => Some(s.clone()),
- Alert::Dictionary(alert_dictionary) => alert_dictionary.title.clone(),
- })
- .unwrap_or(String::new()),
- SnsTarget::Voip(payload) => format!("Incoming call in {}", payload.channel_name),
- SnsTarget::Android(fcmmessage) => fcmmessage.android.notification.clone(),
- }
- }
-
- fn as_payload(&self) -> SnsPayload<'_, T> {
- match self {
- SnsTarget::Ios(apnspush_notification) => SnsPayload::Ios {
- default: self.default_string(),
- apns: apnspush_notification,
- apns_sandbox: apnspush_notification,
- },
- SnsTarget::Voip(payload) => SnsPayload::Voip {
- default: self.default_string(),
- apns_voip: payload,
- apns_voip_sandbox: payload,
- },
- SnsTarget::Android(fcmmessage) => SnsPayload::Android {
- default: self.default_string(),
- gcm: fcmmessage,
- },
- }
- }
-}
-
-impl<T: Serialize> SnsTarget<'_, T> {
- /// Serialize the target to JSON for SNS.
- pub fn as_json(&self) -> Result<String, serde_json::Error> {
- self.as_payload().as_json()
- }
-}
-
/// Used to build up the data to construct a [`HashedCollapseKey`].
///
/// Uses SHA-256 internally for stable hashing across Rust compiler versions.
diff --git a/crates/notification/src/domain/models/queue_message.rs b/crates/notification/src/domain/models/queue_message.rs
index d3508a6c80..57bb05f4b4 100644
--- a/crates/notification/src/domain/models/queue_message.rs
+++ b/crates/notification/src/domain/models/queue_message.rs
@@ -22,24 +22,27 @@ use uuid::Uuid;
#[cfg(test)]
mod test;
-/// Per-user iOS push delivery targets.
+/// Per-user push delivery targets. Legacy names preserve queued iOS messages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserApnsEndpoints {
/// The iOS device endpoint ARNs for this user.
pub endpoints: Vec<String>,
+ /// Android endpoints share the user's delivery/fallback decision with iOS.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub android_endpoints: Vec<String>,
/// State machine data if the ingress decision was indeterminate for this user.
#[serde(default)]
pub digest_state: Option<Box<BatchSend<PushNotificationsEnabled>>>,
}
-/// APNS push notification targets.
+/// Mobile push targets using the existing APNS content template and queue format.
#[derive(Debug, Serialize, Deserialize)]
pub struct APNSTargets<T> {
/// The APNS notification payload.
pub notif: APNSPushNotification<T>,
/// The APNS message attributes.
pub attributes: MessageAttributes,
- /// Per-user iOS device endpoints and optional state machine data.
+ /// Per-user iOS/Android endpoints and one shared fallback decision.
pub ios_device_endpoints: HashMap<MacroUserIdStr<'static>, UserApnsEndpoints>,
}
@@ -228,7 +231,7 @@ impl<'a, T: Notification> ConnGatewayNotification<'a, T> {
/// The delivery channel variants.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) enum NotificationChannel<'a, T, U> {
- /// Delivering to an iOS device with APNS.
+ /// Mobile push delivery; the legacy variant name preserves queued messages.
Ios(Box<APNSTargets<U>>),
/// Delivering to a user's email inbox.
Email(EmailNotification<'a>),
@@ -435,6 +438,8 @@ pub struct RawQueueMessage {
pub enum DeliverySuccess {
/// Delivered via iOS push.
Ios,
+ /// Delivered via Android push.
+ Android,
/// Delivered via connection gateway (WebSocket).
ConnGateway,
/// Delivered via email.
@@ -450,9 +455,9 @@ pub enum DeliveryFailure {
/// a timeout limit was reached trying to deliver the notif
#[error("A timeout was reached")]
Timeout,
- /// a delivery error occurred with apns
- #[error("An apns delivery error occurred")]
- Ios,
+ /// A mobile push delivery error occurred with APNS or FCM.
+ #[error("A mobile push delivery error occurred")]
+ Mobile,
/// A delivery error occurred.
#[error("A delivery error occured")]
Other,
diff --git a/crates/notification/src/domain/models/queue_message/test.rs b/crates/notification/src/domain/models/queue_message/test.rs
index 75369410ef..5655df6368 100644
--- a/crates/notification/src/domain/models/queue_message/test.rs
+++ b/crates/notification/src/domain/models/queue_message/test.rs
@@ -48,6 +48,7 @@ fn test_apns_targets_deserializes_with_per_user_endpoints() {
// Verify digest_state defaults to None when not present
for user_endpoints in targets.ios_device_endpoints.values() {
assert!(user_endpoints.digest_state.is_none());
+ assert!(user_endpoints.android_endpoints.is_empty());
}
}
diff --git a/crates/notification/src/domain/service/egress.rs b/crates/notification/src/domain/service/egress.rs
index 3732fbdb4a..5bcf41410d 100644
--- a/crates/notification/src/domain/service/egress.rs
+++ b/crates/notification/src/domain/service/egress.rs
@@ -3,14 +3,15 @@
//! This service handles the worker-facing side of notifications:
//! consuming from the queue and delivering via realtime, push, and email.
-use crate::domain::models::apple::APNSPushNotification;
+use crate::domain::models::android::FCMMessage;
+use crate::domain::models::apple::{APNSPushNotification, Alert};
use crate::domain::models::email_notification_digest::ports::{
ClaimResult, DigestBatch, DigestBatcher, MessageId, NotificationSendChecker,
};
use crate::domain::models::email_notification_digest::{
BulkDigestEgressStateMachine, ResumeMachineBRequest,
};
-use crate::domain::models::mobile::MessageAttributes;
+use crate::domain::models::mobile::{MessageAttributes, PushType};
use crate::domain::models::queue_message::{
APNSTargets, ConnGatewayNotification, DeliveryFailure, DeliverySuccess, EmailCreateBundle,
EmailNotification, NotificationChannel, QueueMessage,
@@ -32,25 +33,34 @@ use tracing::Level;
/// Maximum time to wait for a single notification delivery before timing out.
pub(crate) const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15);
-/// Wraps a single iOS push notification send for the bulk-digest state machine.
+/// Wraps a single mobile push notification send for the bulk-digest state machine.
///
/// The state machine calls [`NotificationSendChecker::send_notification`] to perform the actual
/// push delivery, then records the SNS message ID or queues for batch email on failure.
-struct IosPushSend<'a, M> {
+struct MobilePushSend<'a, M> {
mobile: &'a M,
endpoint_arn: &'a str,
- notif: &'a APNSPushNotification<serde_json::Value>,
+ notif: MobilePayload<'a>,
attributes: &'a MessageAttributes,
}
-impl<M: NotificationSender> NotificationSendChecker for IosPushSend<'_, M> {
+impl<M: NotificationSender> NotificationSendChecker for MobilePushSend<'_, M> {
type Ok = String;
type Err = Report;
async fn send_notification(self) -> Result<String, Report> {
- self.mobile
- .send_ios_push_notification(self.endpoint_arn, self.notif, self.attributes)
- .await
+ match self.notif {
+ MobilePayload::Ios(notif) => {
+ self.mobile
+ .send_ios_push_notification(self.endpoint_arn, notif, self.attributes)
+ .await
+ }
+ MobilePayload::Android(notif) => {
+ self.mobile
+ .send_android_push_notification(self.endpoint_arn, notif, self.attributes)
+ .await
+ }
+ }
}
fn extract_message_id(res: &String) -> MessageId {
@@ -58,6 +68,54 @@ impl<M: NotificationSender> NotificationSendChecker for IosPushSend<'_, M> {
}
}
+#[derive(Clone, Copy)]
+enum MobilePayload<'a> {
+ Ios(&'a APNSPushNotification<serde_json::Value>),
+ Android(&'a FCMMessage<serde_json::Value>),
+}
+
+impl MobilePayload<'_> {
+ fn success(self) -> DeliverySuccess {
+ match self {
+ Self::Ios(_) => DeliverySuccess::Ios,
+ Self::Android(_) => DeliverySuccess::Android,
+ }
+ }
+}
+
+fn android_notification(
+ apns: &APNSTargets<serde_json::Value>,
+ recipient_id: MacroUserIdStr<'static>,
+) -> FCMMessage<serde_json::Value> {
+ let data = apns.notif.push_notification_data.clone();
+ let identifier = apns.attributes.collapse_key.clone();
+ if matches!(apns.attributes.push_type, PushType::Background) {
+ return FCMMessage::clear(identifier, data, recipient_id);
+ }
+ let (mut title, body) = match &apns.notif.aps.alert {
+ Some(Alert::Simple(body)) => (String::new(), body.clone()),
+ Some(Alert::Dictionary(alert)) => (
+ [alert.title.as_deref(), alert.subtitle.as_deref()]
+ .into_iter()
+ .flatten()
+ .filter(|text| !text.trim().is_empty())
+ .collect::<Vec<_>>()
+ .join(" — "),
+ alert.body.clone().unwrap_or_default(),
+ ),
+ None => (String::new(), String::new()),
+ };
+ // Android rejects visible pushes without text. Keep silent clears above
+ // separate from alerts whose source payload omitted display content.
+ if title.trim().is_empty() && body.trim().is_empty() {
+ title = "New notification".to_owned();
+ }
+ FCMMessage::notification(title, body, identifier, data, recipient_id)
+}
+
+#[cfg(test)]
+mod test;
+
/// Service for delivering notifications (egress side).
///
/// Handles consuming from queue and delivering via realtime, push, and email.
@@ -111,10 +169,10 @@ where
.context(DeliveryFailure::Other)]),
NotificationChannel::Email(email) => Either::Left([self.deliver_email(email).await]),
NotificationChannel::Ios(apns) => Either::Right(
- self.deliver_ios(&apns)
+ self.deliver_mobile(&apns)
.await
.into_iter()
- .map(|r| r.context(DeliveryFailure::Ios)),
+ .map(|r| r.context(DeliveryFailure::Mobile)),
),
};
@@ -132,61 +190,70 @@ where
Ok(DeliverySuccess::ConnGateway)
}
- /// Deliver via iOS push (APNS).
+ /// Deliver mobile push (APNS and FCM) within one per-user fallback decision.
///
/// Iterates per-user. If a user has a digest state machine entry, all
/// endpoints are passed to [`BulkDigestEgressStateMachine::continue_machine`]
/// in a single call. The state machine records SNS message IDs for successes
/// and only queues a batch email if ALL endpoints fail.
/// Users without a state machine entry are sent directly.
- async fn deliver_ios(
+ async fn deliver_mobile(
&self,
apns: &APNSTargets<serde_json::Value>,
) -> Vec<Result<DeliverySuccess, Report>> {
let total: usize = apns
.ios_device_endpoints
.values()
- .map(|u| u.endpoints.len())
+ .map(|u| u.endpoints.len() + u.android_endpoints.len())
.sum();
let mut out = Vec::with_capacity(total);
- for user_apns in apns.ios_device_endpoints.values() {
+ for (user_id, user_apns) in &apns.ios_device_endpoints {
+ let android = (!user_apns.android_endpoints.is_empty())
+ .then(|| android_notification(apns, user_id.clone()));
+ let checkers: Vec<_> = user_apns
+ .endpoints
+ .iter()
+ .map(|endpoint| MobilePushSend {
+ mobile: &self.mobile,
+ endpoint_arn: endpoint,
+ notif: MobilePayload::Ios(&apns.notif),
+ attributes: &apns.attributes,
+ })
+ .chain(android.iter().flat_map(|android| {
+ user_apns
+ .android_endpoints
+ .iter()
+ .map(move |endpoint| MobilePushSend {
+ mobile: &self.mobile,
+ endpoint_arn: endpoint,
+ notif: MobilePayload::Android(android),
+ attributes: &apns.attributes,
+ })
+ }))
+ .collect();
if let Some(ref entry) = user_apns.digest_state {
- // Build all send checkers for this user's endpoints
- let checkers: Vec<_> = user_apns
- .endpoints
- .iter()
- .map(|endpoint| IosPushSend {
- mobile: &self.mobile,
- endpoint_arn: endpoint,
- notif: &apns.notif,
- attributes: &apns.attributes,
- })
- .collect();
-
+ let platforms: Vec<_> = checkers.iter().map(|checker| checker.notif).collect();
let req = ResumeMachineBRequest {
notification_enabled: entry.inner().clone(),
send_notifs: checkers,
};
-
let (results, batch_decision) = self.state_machine.continue_machine(req).await;
-
if let Either::Right(Err(ref batch_err)) = batch_decision {
tracing::error!(error=?batch_err, "failed to queue digest batch after all pushes failed");
}
-
- for result in results {
- out.push(result.map(|_| DeliverySuccess::Ios));
+ for (result, platform) in results.into_iter().zip(platforms) {
+ out.push(result.map(|_| platform.success()));
}
} else {
- // No state machine entry — send directly
- for endpoint in &user_apns.endpoints {
- let res = self
- .mobile
- .send_ios_push_notification(endpoint, &apns.notif, &apns.attributes)
- .await
- .map(|_| DeliverySuccess::Ios);
- out.push(res);
+ for checker in checkers {
+ let platform = checker.notif;
+ out.push(
+ checker
+ .send_notification()
+ .await
+ .map(|_| platform.success()),
+ );
}
}
}
@@ -299,8 +366,8 @@ where
for (receipt_handle, delivery_results) in outcomes {
let any_succeeded = delivery_results.iter().any(Result::is_ok);
- let all_ios_failed = delivery_results.iter().all(
- |e| matches!(e, Err(e) if matches!(e.current_context(), DeliveryFailure::Ios )),
+ let all_mobile_failed = delivery_results.iter().all(
+ |e| matches!(e, Err(e) if matches!(e.current_context(), DeliveryFailure::Mobile )),
);
let rate_limited = delivery_results.iter().any(|e| {
matches!(
@@ -310,10 +377,10 @@ where
});
// Delete from the queue if any delivery succeeded, all failures were
- // iOS failures, or delivery was rejected by the rate limit. Rate-limit
+ // mobile push failures, or delivery was rejected by the rate limit. Rate-limit
// rejection is terminal; retrying the same notification would only
// deliver stale notifications after the limit window expires.
- if (any_succeeded || all_ios_failed || rate_limited)
+ if (any_succeeded || all_mobile_failed || rate_limited)
&& let Err(e) = self.queue.delete_message(&receipt_handle).await
{
results.push(Err(e))
diff --git a/crates/notification/src/domain/service/egress/test.rs b/crates/notification/src/domain/service/egress/test.rs
new file mode 100644
index 0000000000..454ea67e78
--- /dev/null
+++ b/crates/notification/src/domain/service/egress/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+use crate::domain::models::apple::{AlertDictionary, Aps};
+use serde_json::json;
+
+fn notification(alert: Option<Alert>, push_type: PushType) -> FCMMessage<serde_json::Value> {
+ android_notification(
+ &APNSTargets {
+ notif: APNSPushNotification {
+ aps: Aps {
+ alert,
+ ..Default::default()
+ },
+ push_notification_data: json!({"notificationId": "notification-id"}),
+ },
+ attributes: MessageAttributes {
+ push_type,
+ collapse_key: "identifier".into(),
+ },
+ ios_device_endpoints: Default::default(),
+ },
+ MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned(),
+ )
+}
+
+#[test]
+fn empty_alerts_have_visible_fallback_text() {
+ for alert in [
+ None,
+ Some(Alert::Simple(String::new())),
+ Some(Alert::Simple(" \n".into())),
+ Some(Alert::Dictionary(AlertDictionary::default())),
+ Some(Alert::Dictionary(AlertDictionary {
+ title: Some(" ".into()),
+ subtitle: Some("\t".into()),
+ body: Some("\n".into()),
+ ..Default::default()
+ })),
+ ] {
+ let message = notification(alert, PushType::Alert);
+ assert_eq!(message.title.as_deref(), Some("New notification"));
+ assert_eq!(message.identifier, "identifier");
+ assert_eq!(message.data["notificationId"], "notification-id");
+ assert_eq!(message.recipient_id.as_ref(), "macro|[email protected]");
+ }
+}
+
+#[test]
+fn visible_alert_content_is_preserved() {
+ let simple = notification(Some(Alert::Simple("Hello".into())), PushType::Alert);
+ assert_eq!(simple.title.as_deref(), Some(""));
+ assert_eq!(simple.body.as_deref(), Some("Hello"));
+ let structured = notification(
+ Some(Alert::Dictionary(AlertDictionary {
+ title: Some("Alice".into()),
+ subtitle: Some("Project".into()),
+ body: Some("Hello".into()),
+ ..Default::default()
+ })),
+ PushType::Alert,
+ );
+ assert_eq!(structured.title.as_deref(), Some("Alice — Project"));
+ assert_eq!(structured.body.as_deref(), Some("Hello"));
+}
+
+#[test]
+fn silent_clear_does_not_get_fallback_text() {
+ let message = notification(None, PushType::Background);
+ assert!(message.title.is_none());
+ assert!(message.body.is_none());
+ assert_eq!(message.identifier, "identifier");
+}
diff --git a/crates/notification/src/domain/service/ingress.rs b/crates/notification/src/domain/service/ingress.rs
index 9d473cfe30..844c1ab997 100644
--- a/crates/notification/src/domain/service/ingress.rs
+++ b/crates/notification/src/domain/service/ingress.rs
@@ -347,7 +347,7 @@ where
));
}
- // APNS (iOS push): 1:M (single message for all recipients' device endpoints)
+ // Mobile push: one message with all platforms grouped by recipient.
if let Some(build_apns) = notification.build_apns.take() {
let recipients_vec: Vec<_> = notification.req.recipient_ids.iter().cloned().collect();
let device_endpoints = self
@@ -356,38 +356,16 @@ where
.await
.context(SendNotificationError::Other)?;
- let ios_endpoints: std::collections::HashMap<_, _> = device_endpoints
- .into_iter()
- .filter_map(|(user_id, endpoints)| {
- let ios: Vec<String> = endpoints
- .into_iter()
- .filter_map(|e| match e {
- DeviceEndpoint::Ios(arn) => Some(arn),
- DeviceEndpoint::Android(_) | DeviceEndpoint::IosVoip(_) => None,
- })
- .collect();
- if ios.is_empty() {
- None
- } else {
- Some((
- user_id,
- UserApnsEndpoints {
- endpoints: ios,
- digest_state: None,
- },
- ))
- }
- })
- .collect();
+ let mobile_endpoints = group_mobile_endpoints(device_endpoints);
- if !ios_endpoints.is_empty() {
+ if !mobile_endpoints.is_empty() {
let BuildApnsOutput { notif, attr } = build_apns;
apns_collapse_key = Some(attr.collapse_key.clone());
messages.push(QueueMessage::new_from_apns(
APNSTargets {
notif,
attributes: attr,
- ios_device_endpoints: ios_endpoints,
+ ios_device_endpoints: mobile_endpoints,
},
typename,
));
@@ -554,31 +532,9 @@ where
.get_device_endpoints(&[req.user_id.copied()])
.await?;
- let ios_endpoints: std::collections::HashMap<_, _> = device_endpoints
- .into_iter()
- .filter_map(|(user_id, endpoints)| {
- let ios: Vec<String> = endpoints
- .into_iter()
- .filter_map(|e| match e {
- DeviceEndpoint::Ios(arn) => Some(arn),
- DeviceEndpoint::Android(_) | DeviceEndpoint::IosVoip(_) => None,
- })
- .collect();
- if ios.is_empty() {
- None
- } else {
- Some((
- user_id,
- UserApnsEndpoints {
- endpoints: ios,
- digest_state: None,
- },
- ))
- }
- })
- .collect();
+ let mobile_endpoints = group_mobile_endpoints(device_endpoints);
- if ios_endpoints.is_empty() {
+ if mobile_endpoints.is_empty() {
return deserialize_updated_notifications(changed);
}
@@ -612,7 +568,7 @@ where
push_type: PushType::Background,
collapse_key,
},
- ios_device_endpoints: ios_endpoints.clone(),
+ ios_device_endpoints: mobile_endpoints.clone(),
},
&typename,
)
@@ -625,6 +581,38 @@ where
}
}
+/// Group a user's registered devices into push targets, dropping users with
+/// no push-capable device. VoIP endpoints are delivered separately.
+fn group_mobile_endpoints(
+ device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,
+) -> HashMap<MacroUserIdStr<'static>, UserApnsEndpoints> {
+ device_endpoints
+ .into_iter()
+ .filter_map(|(user_id, endpoints)| {
+ let mut ios = Vec::new();
+ let mut android = Vec::new();
+ for endpoint in endpoints {
+ match endpoint {
+ DeviceEndpoint::Ios(arn) => ios.push(arn),
+ DeviceEndpoint::Android(arn) => android.push(arn),
+ DeviceEndpoint::IosVoip(_) => {}
+ }
+ }
+ if ios.is_empty() && android.is_empty() {
+ return None;
+ }
+ Some((
+ user_id,
+ UserApnsEndpoints {
+ endpoints: ios,
+ android_endpoints: android,
+ digest_state: None,
+ },
+ ))
+ })
+ .collect()
+}
+
/// Deserialize updated rows from their persisted event-tagged metadata representation.
fn deserialize_updated_notifications<T: DeserializeOwned>(
notifications: Vec<UserNotificationRow<serde_json::Value>>,
diff --git a/crates/notification/src/domain/service/test.rs b/crates/notification/src/domain/service/test.rs
index 289b93938b..c030bc29d6 100644
--- a/crates/notification/src/domain/service/test.rs
+++ b/crates/notification/src/domain/service/test.rs
@@ -1,5 +1,6 @@
//! Unit tests for the notification services.
+mod android;
mod status_updates;
use crate::domain::models::apple::APNSPushNotification;
@@ -315,9 +316,14 @@ impl NotificationRepository for MockRepository {
async fn get_device_endpoints<'a>(
&self,
- _user_ids: &[MacroUserIdStr<'a>],
+ user_ids: &[MacroUserIdStr<'a>],
) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {
- Ok(self.device_endpoints.clone())
+ Ok(self
+ .device_endpoints
+ .iter()
+ .filter(|(user, _)| user_ids.contains(user))
+ .map(|(user, endpoints)| (user.clone(), endpoints.clone()))
+ .collect())
}
async fn mark_notifications_seen(
@@ -2258,6 +2264,7 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
(
user1,
UserApnsEndpoints {
+ android_endpoints: Vec::new(),
endpoints: vec![endpoint1.to_string(), endpoint2.to_string()],
digest_state: None,
},
@@ -2265,6 +2272,7 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
(
user2,
UserApnsEndpoints {
+ android_endpoints: Vec::new(),
endpoints: vec![endpoint3.to_string(), endpoint4.to_string()],
digest_state: None,
},
@@ -2714,6 +2722,7 @@ async fn test_poll_and_deliver_deletes_message_when_all_ios_failures() {
ios_device_endpoints: HashMap::from([(
user,
UserApnsEndpoints {
+ android_endpoints: Vec::new(),
endpoints: vec![
"arn:endpoint/device1".to_string(),
"arn:endpoint/device2".to_string(),
diff --git a/crates/notification/src/domain/service/test/android.rs b/crates/notification/src/domain/service/test/android.rs
new file mode 100644
index 0000000000..944b6431b6
--- /dev/null
+++ b/crates/notification/src/domain/service/test/android.rs
@@ -0,0 +1,242 @@
+use super::*;
+use crate::domain::models::android::FCMMessage;
+use crate::domain::models::email_notification_digest::ports::NotificationSendChecker;
+use crate::domain::models::email_notification_digest::{
+ BatchSend, BulkDigestEgressStateMachine, DontSend, ResumeMachineBRequest,
+};
+use crate::domain::models::mobile::MessageAttributes;
+use crate::domain::models::queue_message::DeliverySuccess;
+
+#[tokio::test]
+async fn queues_android_and_ios_together_after_recipient_filtering() {
+ let user = test_user_id("[email protected]");
+ let muted = test_user_id("[email protected]");
+ let queue = Arc::new(MockQueue::new());
+ let repo = Arc::new(
+ MockRepository::new()
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Ios("ios".into()))
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Android("android".into()))
+ .with_device_endpoint(user.clone(), DeviceEndpoint::IosVoip("voip".into()))
+ .with_device_endpoint(muted.clone(), DeviceEndpoint::Android("muted".into()))
+ .with_muted_user(muted.clone()),
+ );
+ let service = NotificationIngressService::new(repo.clone(), 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(), muted]),
+ }
+ .into_request()
+ .with_apns(),
+ )
+ .await
+ .unwrap();
+ let published = queue.get_published();
+ assert_eq!(published.len(), 1);
+ let recipients = published[0]["content"]["Ios"]["ios_device_endpoints"]
+ .as_object()
+ .unwrap();
+ assert_eq!(recipients.len(), 1);
+ assert_eq!(recipients[user.as_ref()]["endpoints"], json!(["ios"]));
+ assert_eq!(
+ recipients[user.as_ref()]["android_endpoints"],
+ json!(["android"])
+ );
+ assert!(repo.stored_collapse_keys.lock().unwrap()[0].1.is_some());
+}
+
+#[tokio::test]
+async fn android_only_alerts_keep_the_identifier_needed_for_clearing() {
+ let user = test_user_id("[email protected]");
+ let repo = Arc::new(
+ MockRepository::new()
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Android("android".into())),
+ );
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationIngressService::new(repo.clone(), 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]),
+ }
+ .into_request()
+ .with_apns(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(queue.get_published().len(), 1);
+ assert!(repo.stored_collapse_keys.lock().unwrap()[0].1.is_some());
+}
+
+#[derive(Default)]
+struct CaptureMobile {
+ android: Mutex<Vec<(String, serde_json::Value)>>,
+ ios: Mutex<Vec<String>>,
+}
+
+#[derive(Default)]
+struct CaptureFallback {
+ groups: Mutex<Vec<usize>>,
+ fallback_queued: Mutex<bool>,
+}
+
+impl BulkDigestEgressStateMachine for CaptureFallback {
+ async fn continue_machine<N: NotificationSendChecker>(
+ &self,
+ req: ResumeMachineBRequest<N>,
+ ) -> (
+ Vec<Result<N::Ok, N::Err>>,
+ either::Either<DontSend, Result<BatchSend<()>, Report>>,
+ ) {
+ self.groups.lock().unwrap().push(req.send_notifs.len());
+ let result = MockEgressStateMachine.continue_machine(req).await;
+ *self.fallback_queued.lock().unwrap() = result.1.is_right();
+ result
+ }
+}
+
+impl NotificationSender for CaptureMobile {
+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint: &str,
+ _: &APNSPushNotification<T>,
+ _: &MessageAttributes,
+ ) -> Result<String, Report> {
+ self.ios.lock().unwrap().push(endpoint.to_owned());
+ rootcause::bail!("simulated iOS failure")
+ }
+
+ async fn send_android_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ endpoint: &str,
+ notification: &FCMMessage<T>,
+ _: &MessageAttributes,
+ ) -> Result<String, Report> {
+ self.android
+ .lock()
+ .unwrap()
+ .push((endpoint.into(), serde_json::to_value(notification).unwrap()));
+ Ok("android-message-id".into())
+ }
+}
+
+#[tokio::test]
+async fn delivers_android_even_when_the_same_users_ios_endpoint_fails() {
+ let queue = Arc::new(MockQueue::new());
+ let user = test_user_id("[email protected]");
+ let ingress = NotificationIngressService::new(
+ MockRepository::new()
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Ios("ios".into()))
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Android("android".into())),
+ queue.clone(),
+ MockStateMachine,
+ );
+ ingress
+ .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(),
+ )
+ .await
+ .unwrap();
+ let egress = NotificationEgressService {
+ queue: MockQueue::new(),
+ repository: MockRepository::new(),
+ realtime: MockRealtimeSender,
+ mobile: CaptureMobile::default(),
+ email: MockEmailSender,
+ rate_limiter: allowing_rate_limiter(),
+ state_machine: CaptureFallback::default(),
+ digest_batcher: MockDigestBatcher,
+ };
+ let mut queued = queue.get_published().remove(0);
+ queued["content"]["Ios"]["ios_device_endpoints"][user.as_ref()]["digest_state"] = json!({
+ "inner": updated_notification(user.clone(), Uuid::now_v7(), false, None, Utc::now())
+ });
+ let message = serde_json::from_value(queued).unwrap();
+ let results = egress.deliver_notification(message).await;
+ assert_eq!(results.len(), 2);
+ assert!(
+ results
+ .iter()
+ .any(|result| matches!(result, Ok(DeliverySuccess::Android)))
+ );
+ assert!(results.iter().any(Result::is_err));
+ let android = egress.mobile.android.lock().unwrap();
+ assert_eq!(android.len(), 1);
+ assert_eq!(android[0].0, "android");
+ assert_eq!(android[0].1["data"]["message"], "Hello");
+ assert_eq!(egress.mobile.ios.lock().unwrap().as_slice(), ["ios"]);
+ assert_eq!(egress.state_machine.groups.lock().unwrap().as_slice(), [2]);
+ assert!(!*egress.state_machine.fallback_queued.lock().unwrap());
+}
+
+#[tokio::test]
+async fn seen_and_done_deliver_silent_clear_to_android_only_users() {
+ for status in [NotificationStatus::Seen, NotificationStatus::Done(true)] {
+ let user = test_user_id("[email protected]");
+ let id = Uuid::now_v7();
+ let queue = Arc::new(MockQueue::new());
+ let reader = NotificationReaderService {
+ repository: MockRepository::new()
+ .with_basic_notification(id, "identifier".into())
+ .with_device_endpoint(user.clone(), DeviceEndpoint::Android("android".into())),
+ queue: queue.clone(),
+ sns_endpoint: MockSnsEndpoint,
+ platform_config: test_platform_config(),
+ realtime: crate::domain::ports::NoopNotificationRealtimePublisher,
+ };
+ reader
+ .update_notifications(UpdateNotificationsRequest {
+ user_id: user,
+ notification_ids: &[id],
+ status,
+ })
+ .await
+ .unwrap();
+ let mut messages = queue.get_published();
+ if !cfg!(feature = "clear_ios_push") {
+ assert!(messages.is_empty());
+ continue;
+ }
+ assert_eq!(messages.len(), 1);
+ let egress = NotificationEgressService {
+ queue: MockQueue::new(),
+ repository: MockRepository::new(),
+ realtime: MockRealtimeSender,
+ mobile: CaptureMobile::default(),
+ email: MockEmailSender,
+ rate_limiter: allowing_rate_limiter(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: MockDigestBatcher,
+ };
+ let results = egress
+ .deliver_notification(serde_json::from_value(messages.remove(0)).unwrap())
+ .await;
+ assert!(matches!(results.as_slice(), [Ok(DeliverySuccess::Android)]));
+ let android = egress.mobile.android.lock().unwrap();
+ assert_eq!(android[0].1["identifier"], "identifier");
+ assert!(android[0].1["title"].is_null());
+ assert!(android[0].1["body"].is_null());
+ }
+}
diff --git a/crates/notification/src/domain/service/voip/test.rs b/crates/notification/src/domain/service/voip/test.rs
index 7d3ff0d710..8f8050710e 100644
--- a/crates/notification/src/domain/service/voip/test.rs
+++ b/crates/notification/src/domain/service/voip/test.rs
@@ -7,9 +7,9 @@ use rootcause::Report;
use serde::Serialize;
use crate::domain::models::apple::VoipPushPayload;
-use crate::domain::models::mobile::{DeviceEndpoint, SnsTarget};
+use crate::domain::models::mobile::DeviceEndpoint;
use crate::domain::ports::{NotificationRepository, VoipPushSender};
-use crate::outbound::mobile::{MobilePushAdapter, MobilePushOps};
+use crate::outbound::mobile::{MobilePushAdapter, MobilePushOps, SnsTarget};
use super::VoipPushServiceImpl;
diff --git a/crates/notification/src/outbound/mobile.rs b/crates/notification/src/outbound/mobile.rs
index 8145a89787..57db11f8b9 100644
--- a/crates/notification/src/outbound/mobile.rs
+++ b/crates/notification/src/outbound/mobile.rs
@@ -7,9 +7,12 @@ use std::collections::HashMap;
use crate::domain::models::android::FCMMessage;
use crate::domain::models::apple::{APNSPushNotification, VoipPushPayload};
-use crate::domain::models::mobile::{MessageAttributes, PushType, SnsTarget};
+use crate::domain::models::mobile::{MessageAttributes, PushType};
use crate::domain::ports::NotificationSender;
+mod payload;
+pub use payload::SnsTarget;
+
/// Mobile push notification adapter.
///
/// This adapter sends push notifications to mobile devices via APNS (iOS)
@@ -83,12 +86,11 @@ impl<P: MobilePushOps + Send + Sync + 'static> NotificationSender for MobilePush
&self,
endpoint_arn: &str,
notification: &FCMMessage<T>,
- attributes: &MessageAttributes,
+ _attributes: &MessageAttributes,
) -> Result<String, Report> {
let target = SnsTarget::Android(notification);
- let sns_attributes = build_sns_attributes(&self.apns_bundle_id, attributes);
self.push_service
- .push_notification(endpoint_arn, &target, sns_attributes)
+ .push_notification(endpoint_arn, &target, HashMap::new())
.await
}
}
diff --git a/crates/notification/src/outbound/mobile/payload.rs b/crates/notification/src/outbound/mobile/payload.rs
new file mode 100644
index 0000000000..fe696eb175
--- /dev/null
+++ b/crates/notification/src/outbound/mobile/payload.rs
@@ -0,0 +1,156 @@
+//! SNS wire payloads. Platform transport details stay in the outbound adapter.
+
+use crate::domain::models::{
+ android::FCMMessage,
+ apple::{APNSPushNotification, Alert, VoipPushPayload},
+};
+use serde::{Serialize, Serializer};
+
+#[cfg(test)]
+mod test;
+
+/// SNS target platform for push notifications.
+#[derive(Debug)]
+pub enum SnsTarget<'a, T> {
+ /// iOS target via APNS.
+ Ios(&'a APNSPushNotification<T>),
+ /// iOS VoIP target via APNS_VOIP.
+ Voip(&'a VoipPushPayload),
+ /// Android target via FCM.
+ Android(&'a FCMMessage<T>),
+}
+
+/// SNS payload formatted for platform-specific delivery.
+#[derive(Debug, Serialize)]
+#[serde(bound = "T: Serialize", untagged)]
+pub(crate) enum SnsPayload<'a, T> {
+ /// iOS payload with APNS and APNS_SANDBOX keys.
+ Ios {
+ /// Default message text.
+ default: String,
+ /// Production APNS payload.
+ #[serde(rename = "APNS", serialize_with = "stringified_json")]
+ apns: &'a APNSPushNotification<T>,
+ /// Sandbox APNS payload.
+ #[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]
+ apns_sandbox: &'a APNSPushNotification<T>,
+ },
+ /// iOS VoIP payload with APNS_VOIP and APNS_VOIP_SANDBOX keys.
+ Voip {
+ /// Default message text.
+ default: String,
+ /// Production APNS VoIP payload.
+ #[serde(rename = "APNS_VOIP", serialize_with = "stringified_json")]
+ apns_voip: &'a VoipPushPayload,
+ /// Sandbox APNS VoIP payload.
+ #[serde(rename = "APNS_VOIP_SANDBOX", serialize_with = "stringified_json")]
+ apns_voip_sandbox: &'a VoipPushPayload,
+ },
+ /// Android payload with GCM key.
+ Android {
+ /// Default message text.
+ default: String,
+ /// FCM payload.
+ #[serde(rename = "GCM", serialize_with = "stringified_fcm_json")]
+ gcm: &'a FCMMessage<T>,
+ },
+}
+
+fn stringified_json<T, S>(val: &T, ser: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+ T: Serialize,
+{
+ let s = serde_json::to_string(val).map_err(serde::ser::Error::custom)?;
+ ser.serialize_str(&s)
+}
+
+fn stringified_fcm_json<T: Serialize, S: Serializer>(
+ notification: &FCMMessage<T>,
+ ser: S,
+) -> Result<S::Ok, S::Error> {
+ // FCM data values must all be strings. Keep arbitrary client metadata in
+ // one JSON string rather than flattening nested objects into the data map.
+ let payload = serde_json::to_string(&notification.data).map_err(serde::ser::Error::custom)?;
+ let visible = notification.title.is_some() || notification.body.is_some();
+ let mut data = std::collections::BTreeMap::from([
+ (
+ "type",
+ if visible { "notification" } else { "clear" }.to_owned(),
+ ),
+ ("identifier", notification.identifier.clone()),
+ ("recipientId", notification.recipient_id.to_string()),
+ ("payload", payload),
+ ]);
+ if let Some(title) = &notification.title {
+ data.insert("title", title.clone());
+ }
+ if let Some(body) = &notification.body {
+ data.insert("body", body.clone());
+ }
+
+ // Data-only messages reach the native receive handler in foreground and
+ // background, giving it one owner for display, deduplication, and clearing.
+ let message = serde_json::json!({
+ "fcmV1Message": {
+ "message": {
+ "android": { "priority": if visible { "high" } else { "normal" } },
+ "data": data,
+ }
+ }
+ });
+ stringified_json(&message, ser)
+}
+
+impl<'a, T> SnsPayload<'a, T>
+where
+ T: Serialize,
+{
+ fn as_json(&self) -> Result<String, serde_json::Error> {
+ serde_json::to_string(self)
+ }
+}
+
+impl<T> SnsTarget<'_, T> {
+ fn default_string(&self) -> String {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => apnspush_notification
+ .aps
+ .alert
+ .as_ref()
+ .and_then(|a| match a {
+ Alert::Simple(s) => Some(s.clone()),
+ Alert::Dictionary(alert_dictionary) => alert_dictionary.title.clone(),
+ })
+ .unwrap_or(String::new()),
+ SnsTarget::Voip(payload) => format!("Incoming call in {}", payload.channel_name),
+ SnsTarget::Android(fcmmessage) => fcmmessage.title.clone().unwrap_or_default(),
+ }
+ }
+
+ fn as_payload(&self) -> SnsPayload<'_, T> {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => SnsPayload::Ios {
+ default: self.default_string(),
+ apns: apnspush_notification,
+ apns_sandbox: apnspush_notification,
+ },
+ SnsTarget::Voip(payload) => SnsPayload::Voip {
+ default: self.default_string(),
+ apns_voip: payload,
+ apns_voip_sandbox: payload,
+ },
+ SnsTarget::Android(fcmmessage) => SnsPayload::Android {
+ default: self.default_string(),
+ gcm: fcmmessage,
+ },
+ }
+ }
+}
+
+impl<T: Serialize> SnsTarget<'_, T> {
+ /// Serialize the target to JSON for SNS.
+ pub fn as_json(&self) -> Result<String, serde_json::Error> {
+ self.as_payload().as_json()
+ }
+}
diff --git a/crates/notification/src/outbound/mobile/payload/test.rs b/crates/notification/src/outbound/mobile/payload/test.rs
new file mode 100644
index 0000000000..e8ce3a6a9e
--- /dev/null
+++ b/crates/notification/src/outbound/mobile/payload/test.rs
@@ -0,0 +1,93 @@
+use super::*;
+use crate::domain::models::apple::{AlertDictionary, Aps, PushNotificationData};
+use serde_json::{Value, json};
+use uuid::Uuid;
+
+#[test]
+fn android_alert_uses_sns_fcm_v1_with_string_data() {
+ let id = Uuid::now_v7();
+ let notification = FCMMessage::notification(
+ "Alice mentioned you".into(),
+ "A message with \"quotes\" and 🦀".into(),
+ "stable-identifier".into(),
+ PushNotificationData {
+ notification_id: id,
+ sender_profile_picture_url: Some("https://example.com/avatar.png".into()),
+ },
+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ );
+ let sns: Value =
+ serde_json::from_str(&SnsTarget::Android(&notification).as_json().unwrap()).unwrap();
+ assert_eq!(sns["default"], "Alice mentioned you");
+ 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!(message.get("notification").is_none());
+ assert!(message["android"].get("notification").is_none());
+ let data = &message["data"];
+ assert!(data.as_object().unwrap().values().all(Value::is_string));
+ assert_eq!(data["type"], "notification");
+ assert_eq!(data["identifier"], "stable-identifier");
+ assert_eq!(data["recipientId"], "macro|[email protected]");
+ assert_eq!(data["body"], "A message with \"quotes\" and 🦀");
+ let metadata: Value = serde_json::from_str(data["payload"].as_str().unwrap()).unwrap();
+ assert_eq!(metadata["notificationId"], id.to_string());
+}
+
+#[test]
+fn android_clear_is_silent_and_preserves_the_display_identifier() {
+ let notification = FCMMessage::clear(
+ "stable-identifier".into(),
+ json!({}),
+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ );
+ let sns: Value =
+ serde_json::from_str(&SnsTarget::Android(&notification).as_json().unwrap()).unwrap();
+ let fcm: Value = serde_json::from_str(sns["GCM"].as_str().unwrap()).unwrap();
+ let message = &fcm["fcmV1Message"]["message"];
+ assert_eq!(message["android"]["priority"], "normal");
+ assert_eq!(message["data"]["type"], "clear");
+ assert_eq!(message["data"]["identifier"], "stable-identifier");
+ assert!(message["data"].get("title").is_none());
+ assert!(message["data"].get("body").is_none());
+ assert!(message.get("notification").is_none());
+}
+
+#[test]
+fn ios_payload_keeps_production_and_sandbox_envelopes() {
+ let notification = APNSPushNotification {
+ aps: Aps {
+ alert: Some(Alert::Dictionary(AlertDictionary {
+ title: Some("Title".into()),
+ body: Some("Body".into()),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: json!({"notificationId": "existing-id"}),
+ };
+ let sns: Value =
+ serde_json::from_str(&SnsTarget::Ios(&notification).as_json().unwrap()).unwrap();
+ assert_eq!(sns["default"], "Title");
+ assert_eq!(sns["APNS"], sns["APNS_SANDBOX"]);
+ assert_eq!(
+ serde_json::from_str::<Value>(sns["APNS"].as_str().unwrap()).unwrap(),
+ serde_json::to_value(&notification).unwrap()
+ );
+}
+
+#[test]
+fn payload_serialization_errors_are_returned_without_panicking() {
+ struct InvalidMetadata;
+ impl Serialize for InvalidMetadata {
+ fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
+ Err(serde::ser::Error::custom("invalid metadata"))
+ }
+ }
+ let notification = FCMMessage::clear(
+ "id".into(),
+ InvalidMetadata,
+ macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ );
+ assert!(SnsTarget::Android(&notification).as_json().is_err());
+}
diff --git a/docs/AGENT_GUIDE/login.md b/docs/AGENT_GUIDE/login.md
index 5b86e182b0..2804d22d64 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/AGENT_GUIDE/login.md
@@ -71,6 +71,18 @@ See [Android development](../ANDROID_DEVELOPMENT.md) for build commands and
certificate-dependent domain verification. Provider completion, account linking,
and verified links still require end-to-end qualification.
+## GitHub reconnect prompt
+
+On native mobile, the `Reconnect GitHub` prompt hides while the authentication
+browser is open. Canceling or failing authentication restores the prompt so the
+user can retry; successful reconnection keeps it hidden. Verify cancel followed
+by retry, browser failure, and failure to start OAuth. Repeated taps while a flow
+is pending must start only one attempt. On the web, a successful OAuth kickoff
+navigates away and the prompt stays hidden during that navigation.
+Use browser Back to return from GitHub: when the page is restored from BFCache,
+it refreshes link status and restores the retry prompt only if reconnection is
+still needed.
+
## Mailpit (local email)
- UI: `http://localhost:<mailpit-port>/`
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 64df6b979a..5778c7aa46 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1556,6 +1556,20 @@ session were not exercised by that UI check.
## Notifications
+On native Android, enable notifications in Settings while signed in. Android 13+
+also asks for system permission; the system's **Activity** notification channel
+must be enabled. Remote push owns system notification display after registration,
+so the same WebSocket event should not create a second local notification. Tapping
+a notification opens its target; simply receiving one does not navigate. Check
+this with the app foregrounded, backgrounded, and after ordinary process death.
+Logout clears delivered notifications and disables receipt for the old account.
+After a transient native listener failure, verify that notification taps recover
+without restarting the app. Android alerts without display text show
+`New notification`; silent read/done clears must remain silent.
+Also verify logout and notification opt-out while registration is pending: late
+backend or native completions must leave the receiver disabled. If a new account
+signs in before cleanup finishes, its registration must remain active afterward.
+
Toast regions are labeled `Notifications (alt+T)`; five empty live regions always exist in
the a11y tree (ignore them when parsing snapshots).
diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/ANDROID_DEVELOPMENT.md
index ad99e8511a..c81e56b701 100644
--- a/docs/ANDROID_DEVELOPMENT.md
+++ b/docs/ANDROID_DEVELOPMENT.md
@@ -97,6 +97,27 @@ its fingerprint to production associations before testing Play-installed links.
## Firebase
Debug builds work without Firebase configuration for auth/navigation development.
+Remote notifications require the matching Firebase configuration and Google Play
+services on the device. Notification permission alone does not register the
+device: sign in to Macro and enable notifications in Settings. Android 13 and
+newer show a runtime permission prompt; older versions use the app's system
+notification setting. The **Activity** channel can also be disabled separately.
+
+The Android push plugin receives data-only FCM messages and owns their display,
+replacement, and clearing. Taps are saved until the authenticated frontend can
+receive them. Logout disables the native receiver and clears its saved display
+and tap state before attempting network unregistration. The receiver checks the
+payload's recipient against the registered account to reject delayed pushes
+from an earlier session.
+
+For verification, test foreground, background, and ordinary process death
+separately. Background the app, then use `adb shell am kill com.macro.app.prod`
+for the process-dead case. Android force-stop is a different state that prevents
+FCM delivery until the user opens the app again. Also test permission and channel
+revocation, logout/account switching, repeated delivery, notification taps, and
+read/done clearing. Silent clearing uses normal-priority FCM and may be delayed
+by Doze. A local display test alone does not verify backend event delivery.
+
The launcher requires package **com.macro.app.prod** and validates these projects:
| Build command | Firebase project |