From 014c4eb15a67892c5b5ad64adb82293cf7505ecd Mon Sep 17 00:00:00 2001 From: Erwan Leboucher Date: Fri, 24 Jul 2026 10:17:11 +0200 Subject: [PATCH] fix(notifications): route push transports by explicit provider --- .changeset/fix-push-transport-switch.md | 5 ++ .../DeregisterPushNotifications.tsx | 19 +++++ .../NativePushNotificationsApiClient.test.ts | 45 +++++++++++ .../NativePushNotificationsApiClient.ts | 2 + .../notifications/PushNotifications.test.ts | 59 +++++++++++++++ .../notifications/PushNotifications.tsx | 4 +- .../notifications/SystemNotification.test.ts | 63 ++++++++++++++++ .../notifications/SystemNotification.tsx | 47 ++++-------- .../notifications/UnifiedPushNotifications.ts | 75 +++++++++++++------ .../UnifiedPushTransportApiClient.test.ts | 27 +++++++ .../UnifiedPushTransportApiClient.ts | 1 + 11 files changed, 290 insertions(+), 57 deletions(-) create mode 100644 .changeset/fix-push-transport-switch.md create mode 100644 src/app/features/settings/notifications/NativePushNotificationsApiClient.test.ts create mode 100644 src/app/features/settings/notifications/PushNotifications.test.ts create mode 100644 src/app/features/settings/notifications/SystemNotification.test.ts create mode 100644 src/app/features/settings/notifications/UnifiedPushTransportApiClient.test.ts diff --git a/.changeset/fix-push-transport-switch.md b/.changeset/fix-push-transport-switch.md new file mode 100644 index 000000000..9d2bd3668 --- /dev/null +++ b/.changeset/fix-push-transport-switch.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Switching to native push notifications now correctly uses the platform's native delivery instead of keeping the old push app. diff --git a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx index bc90d746a..4a35cbc48 100644 --- a/src/app/features/settings/notifications/DeregisterPushNotifications.tsx +++ b/src/app/features/settings/notifications/DeregisterPushNotifications.tsx @@ -17,12 +17,16 @@ import { import { menuIcon, X } from '$components/icons/phosphor'; import { useAtom } from 'jotai'; import { useMatrixClient } from '../../../hooks/useMatrixClient'; +import { useClientConfig } from '../../../hooks/useClientConfig'; import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback'; import { useSetting } from '../../../state/hooks/settings'; import { settingsAtom } from '../../../state/settings'; import { pushSubscriptionAtom } from '../../../state/pushSubscription'; import { deRegisterAllPushers } from './PushNotifications'; +import { disableNativePush } from './NotificationTransport'; +import { disableUnifiedPush } from './UnifiedPushNotifications'; import { SettingTile } from '../../../components/setting-tile'; +import { isTauri } from '@tauri-apps/api/core'; type ConfirmDeregisterDialogProps = { onClose: () => void; @@ -78,9 +82,15 @@ function ConfirmDeregisterDialog({ onClose, onConfirm, isLoading }: ConfirmDereg export function DeregisterAllPushersSetting() { const mx = useMatrixClient(); + const clientConfig = useClientConfig(); const [deregisterState] = useAsyncCallback(deRegisterAllPushers); const [isConfirming, setIsConfirming] = useState(false); const [, setPushNotifications] = useSetting(settingsAtom, 'usePushNotifications'); + const [backgroundPushEnabled, setBackgroundPushEnabled] = useSetting( + settingsAtom, + 'backgroundPushEnabled' + ); + const [, setBackgroundPushProvider] = useSetting(settingsAtom, 'backgroundPushProvider'); const [, setPushSubscription] = useAtom(pushSubscriptionAtom); @@ -97,6 +107,15 @@ export function DeregisterAllPushersSetting() { await deRegisterAllPushers(mx); setPushNotifications(false); setPushSubscription(null); + + if (isTauri()) { + await Promise.allSettled([disableNativePush(mx, clientConfig), disableUnifiedPush(mx)]); + } + + if (backgroundPushEnabled) { + setBackgroundPushEnabled(false); + } + setBackgroundPushProvider(null); setIsConfirming(false); }; diff --git a/src/app/features/settings/notifications/NativePushNotificationsApiClient.test.ts b/src/app/features/settings/notifications/NativePushNotificationsApiClient.test.ts new file mode 100644 index 000000000..de78c4574 --- /dev/null +++ b/src/app/features/settings/notifications/NativePushNotificationsApiClient.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest'; + +const invoke = vi.hoisted(() => + vi.fn<(cmd: string, args?: Record) => Promise>() +); + +const isAndroidTauri = vi.hoisted(() => vi.fn<() => boolean>()); + +vi.mock('@tauri-apps/api/core', () => ({ invoke })); +vi.mock('./TauriNotificationsApiClient', () => ({ isAndroidTauri })); + +import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient'; + +describe('NativePushNotificationsApiClient', () => { + it('registers with provider: "fcm" on Android so the plugin bypasses a saved UnifiedPush distributor', async () => { + isAndroidTauri.mockReturnValue(true); + invoke.mockResolvedValueOnce({ + deviceToken: 'fcm-token', + p256dh: 'p256dh', + auth: 'auth', + }); + + const api = await getNativePushNotificationsApi(); + await api.registerForPushNotifications('vapid-pub'); + + expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', { + vapid: 'vapid-pub', + provider: 'fcm', + }); + }); + + it('omits the provider arg on iOS (APNs ignores it)', async () => { + isAndroidTauri.mockReturnValue(false); + invoke.mockResolvedValueOnce({ + deviceToken: 'apns-token', + }); + + const api = await getNativePushNotificationsApi(); + await api.registerForPushNotifications('vapid-pub'); + + expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', { + vapid: 'vapid-pub', + }); + }); +}); diff --git a/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts index e2ff5e7d7..269f72799 100644 --- a/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts +++ b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts @@ -1,4 +1,5 @@ import { invoke } from '@tauri-apps/api/core'; +import { isAndroidTauri } from './TauriNotificationsApiClient'; export type NativePushRegistration = { deviceToken: string; @@ -24,6 +25,7 @@ export async function getNativePushNotificationsApi(): Promise invoke('plugin:notifications|register_for_push_notifications', { vapid, + ...(isAndroidTauri() ? { provider: 'fcm' } : {}), }), unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications, }) diff --git a/src/app/features/settings/notifications/PushNotifications.test.ts b/src/app/features/settings/notifications/PushNotifications.test.ts new file mode 100644 index 000000000..dfb86f7a3 --- /dev/null +++ b/src/app/features/settings/notifications/PushNotifications.test.ts @@ -0,0 +1,59 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +const isTauri = vi.hoisted(() => vi.fn<() => boolean>()); + +vi.mock('@tauri-apps/api/core', () => ({ isTauri })); + +import { + enablePushNotifications, + disablePushNotifications, + togglePusher, +} from './PushNotifications'; + +const matrixClient = vi.hoisted(() => ({ + getAccessToken: vi.fn<() => string>(() => 'token'), +})); +const clientConfig = {} as never; + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('enablePushNotifications', () => { + it('no-ops in the Tauri runtime instead of throwing', async () => { + isTauri.mockReturnValue(true); + + await expect( + enablePushNotifications(matrixClient as never, clientConfig, [ + null, + vi.fn<(sub: unknown) => void>(), + ]) + ).resolves.toBeUndefined(); + }); +}); + +describe('disablePushNotifications', () => { + it('no-ops in the Tauri runtime', async () => { + isTauri.mockReturnValue(true); + + await expect( + disablePushNotifications(matrixClient as never, clientConfig, [ + null, + vi.fn<(sub: unknown) => void>(), + ]) + ).resolves.toBeUndefined(); + }); +}); + +describe('togglePusher', () => { + it('does not throw in the Tauri runtime when push is enabled', async () => { + isTauri.mockReturnValue(true); + + await expect( + togglePusher(matrixClient as never, clientConfig, true, true, [ + null, + vi.fn<(sub: unknown) => void>(), + ]) + ).resolves.toBeUndefined(); + }); +}); diff --git a/src/app/features/settings/notifications/PushNotifications.tsx b/src/app/features/settings/notifications/PushNotifications.tsx index f936f8c80..1d3dae30d 100644 --- a/src/app/features/settings/notifications/PushNotifications.tsx +++ b/src/app/features/settings/notifications/PushNotifications.tsx @@ -33,9 +33,7 @@ export async function enablePushNotifications( clientConfig: ClientConfig, pushSubscriptionAtom: PushSubscriptionState ): Promise { - if (isTauri()) { - throw new Error('Push notifications are disabled in Tauri runtime.'); - } + if (isTauri()) return; if (!('serviceWorker' in navigator) || !('PushManager' in window)) { debugLog.error( 'notification', diff --git a/src/app/features/settings/notifications/SystemNotification.test.ts b/src/app/features/settings/notifications/SystemNotification.test.ts new file mode 100644 index 000000000..d434caf42 --- /dev/null +++ b/src/app/features/settings/notifications/SystemNotification.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it, vi } from 'vitest'; +import { switchBackgroundPushTransport } from './SystemNotification'; +import type { NotificationTransportProvider } from './NotificationTransport'; + +describe('switchBackgroundPushTransport', () => { + it('deactivates the previous transport before activating the new one', async () => { + const order: string[] = []; + const deactivate = vi + .fn<(kind: NotificationTransportProvider | null) => Promise>() + .mockImplementation(async (kind) => { + order.push(`deactivate:${kind}`); + }); + const activate = vi + .fn<() => Promise>() + .mockImplementation(async () => { + order.push('activate'); + return 'native'; + }); + + const nextKind = await switchBackgroundPushTransport({ + previousKind: 'unifiedpush', + activate, + deactivate, + }); + + expect(nextKind).toBe('native'); + expect(order).toEqual(['deactivate:unifiedpush', 'activate']); + }); + + it('skips deactivate when there is no previous transport', async () => { + const deactivate = vi.fn<(kind: NotificationTransportProvider | null) => Promise>(); + const activate = vi + .fn<() => Promise>() + .mockResolvedValue('native'); + + const nextKind = await switchBackgroundPushTransport({ + previousKind: null, + activate, + deactivate, + }); + + expect(nextKind).toBe('native'); + expect(deactivate).not.toHaveBeenCalled(); + expect(activate).toHaveBeenCalledOnce(); + }); + + it('propagates a deactivate failure without activating', async () => { + const deactivate = vi + .fn<(kind: NotificationTransportProvider | null) => Promise>() + .mockRejectedValue(new Error('unregister failed')); + const activate = vi.fn<() => Promise>(); + + await expect( + switchBackgroundPushTransport({ + previousKind: 'unifiedpush', + activate, + deactivate, + }) + ).rejects.toThrow('unregister failed'); + + expect(activate).not.toHaveBeenCalled(); + }); +}); diff --git a/src/app/features/settings/notifications/SystemNotification.tsx b/src/app/features/settings/notifications/SystemNotification.tsx index 8ee60c4c0..c9b6bb2ea 100644 --- a/src/app/features/settings/notifications/SystemNotification.tsx +++ b/src/app/features/settings/notifications/SystemNotification.tsx @@ -93,33 +93,18 @@ export function deriveLegacyPushSync(input: { return deriveLegacyPushFlags(input.enabled, input.provider); } -export function shouldRefreshBackgroundPushTransport( - previousKind: BackgroundPushKind | null, - nextKind: BackgroundPushKind | null -): boolean { - return previousKind !== nextKind; -} - export async function switchBackgroundPushTransport(params: { previousKind: BackgroundPushKind | null; activate: () => Promise; deactivate: (kind: BackgroundPushKind | null) => Promise; }): Promise { const { previousKind, activate, deactivate } = params; - const nextKind = await activate(); - if (!shouldRefreshBackgroundPushTransport(previousKind, nextKind)) { - return nextKind; - } - - try { + if (previousKind) { await deactivate(previousKind); - } catch (error) { - await deactivate(nextKind).catch(() => undefined); - throw error; } - return nextKind; + return activate(); } function getNativePushConfigError(clientConfig: ReturnType): string | null { @@ -699,19 +684,13 @@ function BackgroundPushNotificationSetting() { await disableNativePush(mx, clientConfig); }; - const activateAndroidAutoTransport = async ( - currentKind: BackgroundPushKind | null - ): Promise => { + const activateAndroidAutoTransport = async (): Promise => { const nativeFallback = async (failureReason: string): Promise => { const configError = getNativePushConfigError(clientConfig); if (configError) { throw new Error(`${failureReason} Native push fallback is unavailable: ${configError}`); } - if (currentKind === 'native') { - return 'native'; - } - await activateTransport('native'); return 'native'; }; @@ -752,7 +731,7 @@ function BackgroundPushNotificationSetting() { if (currentKind === 'unifiedpush') { return 'unifiedpush'; } - return activateAndroidAutoTransport(currentKind); + return activateAndroidAutoTransport(); } if (currentKind === nextPreferredKind) { @@ -793,12 +772,18 @@ function BackgroundPushNotificationSetting() { try { if (backgroundPushEnabled) { - const nextKind = await switchBackgroundPushTransport({ - previousKind, - activate: () => activateMode(nextMode, previousKind), - deactivate: deactivateTransport, - }); - setBackgroundPushProvider(nextKind); + const plannedKind = resolvePreferredNotificationTransportProvider( + normalizeNotificationTransportMode(nextMode, runtimePlatform), + runtimePlatform + ); + if (plannedKind !== previousKind) { + const nextKind = await switchBackgroundPushTransport({ + previousKind, + activate: () => activateMode(nextMode, previousKind), + deactivate: deactivateTransport, + }); + setBackgroundPushProvider(nextKind); + } } else { setBackgroundPushProvider(null); } diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index c1425eee3..eb37e2d73 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -701,29 +701,7 @@ async function handleMinimalPushPayload( } } - if ( - !previewText && - eventId && - settings.showMessageContent && - (!isEncryptedRoom || settings.showEncryptedMessageContent) - ) { - const fetched = await resolvePreviewEvent(settings.mx, roomId, eventId); - if (fetched) { - const sender = fetched.getSender(); - if (sender) { - senderName = room?.getMember(sender)?.name ?? getMxIdLocalPart(sender) ?? sender; - senderId = sender; - } - previewText = resolveNotificationPreviewText({ - content: fetched.getContent(), - eventType: fetched.getType(), - isEncryptedRoom, - showMessageContent: settings.showMessageContent, - showEncryptedMessageContent: settings.showEncryptedMessageContent, - }); - } - } - + const hasInMemoryPreview = Boolean(previewText); if (!previewText) { previewText = isEncryptedRoom ? 'Encrypted message' : 'New message'; } @@ -762,6 +740,57 @@ async function handleMinimalPushPayload( event_id: eventId, user_id: pushData?.user_id, }); + + if ( + !hasInMemoryPreview && + eventId && + settings.showMessageContent && + (!isEncryptedRoom || settings.showEncryptedMessageContent) + ) { + resolvePreviewEvent(settings.mx, roomId, eventId) + .then((fetched) => { + if (!fetched || cache.latestEventId !== eventId) return; + const enrichedPreview = resolveNotificationPreviewText({ + content: fetched.getContent(), + eventType: fetched.getType(), + isEncryptedRoom, + showMessageContent: settings.showMessageContent, + showEncryptedMessageContent: settings.showEncryptedMessageContent, + }); + if (!enrichedPreview) return; + + const fetchedSender = fetched.getSender(); + if (fetchedSender) { + senderName = + room?.getMember(fetchedSender)?.name ?? + getMxIdLocalPart(fetchedSender) ?? + fetchedSender; + senderId = fetchedSender; + } + message.text = enrichedPreview; + message.sender = senderName + ? { + name: senderName, + key: senderId, + iconUrl: + senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined, + } + : sender; + + void postRoomNotification(userId, roomId, cache, true, { + room_id: roomId, + event_id: eventId, + user_id: pushData?.user_id, + }); + }) + .catch((error) => { + unifiedPushLog.warn( + 'notification', + 'Background preview fetch failed', + error instanceof Error ? error : new Error(String(error)) + ); + }); + } } async function handleUnifiedPushPayload( diff --git a/src/app/features/settings/notifications/UnifiedPushTransportApiClient.test.ts b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.test.ts new file mode 100644 index 000000000..1fa0d9294 --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it, vi } from 'vitest'; + +const invoke = vi.hoisted(() => + vi.fn<(cmd: string, args?: Record) => Promise>() +); + +vi.mock('@tauri-apps/api/core', () => ({ invoke })); + +import { getUnifiedPushTransportApi } from './UnifiedPushTransportApiClient'; + +describe('UnifiedPushTransportApiClient', () => { + it('registers with provider: "unifiedpush" so the plugin routes through the distributor explicitly', async () => { + invoke.mockResolvedValueOnce({ + deviceToken: 'up-endpoint', + p256dh: 'p256dh', + auth: 'auth', + }); + + const api = await getUnifiedPushTransportApi(); + await api.registerForPushNotifications('vapid-pub'); + + expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', { + vapid: 'vapid-pub', + provider: 'unifiedpush', + }); + }); +}); diff --git a/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts index 288da15de..0b71d16be 100644 --- a/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts +++ b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts @@ -24,6 +24,7 @@ export async function getUnifiedPushTransportApi(): Promise invoke('plugin:notifications|register_for_push_notifications', { vapid, + provider: 'unifiedpush', }), unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications, listDistributors: notificationsApi.listDistributors,