diff --git a/src/app/features/settings/notifications/NativePushNotifications.test.ts b/src/app/features/settings/notifications/NativePushNotifications.test.ts new file mode 100644 index 000000000..96dbfa3fd --- /dev/null +++ b/src/app/features/settings/notifications/NativePushNotifications.test.ts @@ -0,0 +1,213 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + disableNativePush, + enableNativePush, + ensureNativePushRegistered, + isNativePushPermissionGranted, + requestNativePushPermission, +} from './NativePushNotifications'; +import * as NativePushNotifications from './NativePushNotifications'; + +const nativePushApi = vi.hoisted(() => ({ + isPermissionGranted: vi.fn(), + requestPermission: vi.fn(), + registerForPushNotifications: vi.fn(), + unregisterForPushNotifications: vi.fn(), +})); + +const getNativePushNotificationsApi = vi.hoisted(() => vi.fn().mockResolvedValue(nativePushApi)); + +const matrixClient = vi.hoisted(() => ({ + setPusher: vi.fn().mockResolvedValue(undefined), + getDeviceId: vi.fn(() => 'DEVICE'), + getDevice: vi.fn().mockResolvedValue({ display_name: 'Pixel' }), + getPushers: vi.fn().mockResolvedValue({ pushers: [] }), +})); + +const nativePushClientConfig = { + pushNotificationDetails: { + nativePushAppID: 'moe.sable.mobile', + pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify', + }, +} as const; + +vi.mock('./NativePushNotificationsApiClient', () => ({ + getNativePushNotificationsApi, +})); + +afterEach(() => { + vi.clearAllMocks(); + localStorage.clear(); +}); + +describe('native push permission flow', () => { + it('does not expose the test-only api seam', () => { + expect('setNativePushNotificationsApiForTesting' in NativePushNotifications).toBe(false); + }); + + it('reports false when native permission is not yet granted', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(false); + + await expect(isNativePushPermissionGranted()).resolves.toBe(false); + }); + + it('forwards a permission request explicitly', async () => { + nativePushApi.requestPermission.mockResolvedValue('granted'); + + await expect(requestNativePushPermission()).resolves.toBe('granted'); + }); +}); + +describe('ensureNativePushRegistered', () => { + it('registers immediately when permission is already granted', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + + await expect(ensureNativePushRegistered()).resolves.toEqual({ + permission: 'granted', + token: 'native-token', + }); + expect(nativePushApi.requestPermission).not.toHaveBeenCalled(); + expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce(); + }); + + it('requests permission before registering and returns a token on grant', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(false); + nativePushApi.requestPermission.mockResolvedValue('granted'); + nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + + await expect(ensureNativePushRegistered()).resolves.toEqual({ + permission: 'granted', + token: 'native-token', + }); + expect(nativePushApi.requestPermission).toHaveBeenCalledOnce(); + expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce(); + }); + + it('returns denied without registering when permission is denied', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(false); + nativePushApi.requestPermission.mockResolvedValue('denied'); + + await expect(ensureNativePushRegistered()).resolves.toEqual({ + permission: 'denied', + token: null, + }); + expect(nativePushApi.registerForPushNotifications).not.toHaveBeenCalled(); + }); + + it('preserves a default permission result from the permission request', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(false); + nativePushApi.requestPermission.mockResolvedValue('default'); + + await expect(ensureNativePushRegistered()).resolves.toEqual({ + permission: 'default', + token: null, + }); + expect(nativePushApi.registerForPushNotifications).not.toHaveBeenCalled(); + }); +}); + +describe('native push pusher registration', () => { + it('registers a Matrix pusher with the native device token', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + + await expect(enableNativePush(matrixClient as never, nativePushClientConfig)).resolves.toBe( + 'native-token' + ); + expect(localStorage.getItem('nativePushToken')).toBe('native-token'); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: 'http', + app_id: 'moe.sable.mobile', + pushkey: 'native-token', + data: expect.objectContaining({ + url: 'https://sygnal.example/_matrix/push/v1/notify', + format: 'event_id_only', + }), + }) + ); + }); + + it('rejects native push enablement when the app id is missing', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + + await expect( + enableNativePush(matrixClient as never, { + pushNotificationDetails: { + pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify', + }, + }) + ).rejects.toThrow('nativePushAppID'); + }); + + it('removes native pushers and unregisters the platform token', async () => { + localStorage.setItem('nativePushToken', 'native-token'); + + await expect( + disableNativePush(matrixClient as never, nativePushClientConfig) + ).resolves.toBeUndefined(); + + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: null, + app_id: 'moe.sable.mobile', + pushkey: 'native-token', + }) + ); + expect(nativePushApi.unregisterForPushNotifications).toHaveBeenCalledOnce(); + expect(localStorage.getItem('nativePushToken')).toBeNull(); + }); + + it('recovers the current token before removing the Matrix pusher when local storage is empty', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(true); + nativePushApi.registerForPushNotifications.mockResolvedValue('native-token'); + + await expect( + disableNativePush(matrixClient as never, nativePushClientConfig) + ).resolves.toBeUndefined(); + + expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce(); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: null, + app_id: 'moe.sable.mobile', + pushkey: 'native-token', + }) + ); + }); + + it('falls back to removing current-device pushers when the token cannot be recovered', async () => { + nativePushApi.isPermissionGranted.mockResolvedValue(false); + matrixClient.getPushers.mockResolvedValue({ + pushers: [ + { + app_id: 'moe.sable.mobile', + pushkey: 'stale-native-token', + device_display_name: 'Pixel', + kind: 'http', + }, + { + app_id: 'moe.sable.mobile', + pushkey: 'other-device-token', + device_display_name: 'Other Phone', + kind: 'http', + }, + ], + }); + + await expect( + disableNativePush(matrixClient as never, nativePushClientConfig) + ).resolves.toBeUndefined(); + + expect(matrixClient.setPusher).toHaveBeenCalledTimes(1); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: null, + app_id: 'moe.sable.mobile', + pushkey: 'stale-native-token', + }) + ); + }); +}); diff --git a/src/app/features/settings/notifications/NativePushNotifications.ts b/src/app/features/settings/notifications/NativePushNotifications.ts new file mode 100644 index 000000000..e27e815f0 --- /dev/null +++ b/src/app/features/settings/notifications/NativePushNotifications.ts @@ -0,0 +1,199 @@ +import { IPusherRequest, MatrixClient } from '$types/matrix-sdk'; +import { ClientConfig } from '$hooks/useClientConfig'; +import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient'; + +const NATIVE_PUSH_TOKEN_STORAGE_KEY = 'nativePushToken'; + +export type NativePushRegistrationResult = + | { + permission: 'granted'; + token: string; + } + | { + permission: 'default' | 'denied'; + token: null; + }; + +export type { NativePushNotificationsApi } from './NativePushNotificationsApiClient'; + +function storeNativePushToken(token: string): void { + localStorage.setItem(NATIVE_PUSH_TOKEN_STORAGE_KEY, token); +} + +function getStoredNativePushToken(): string | null { + return localStorage.getItem(NATIVE_PUSH_TOKEN_STORAGE_KEY); +} + +function clearStoredNativePushToken(): void { + localStorage.removeItem(NATIVE_PUSH_TOKEN_STORAGE_KEY); +} + +function getNativePushAppId(clientConfig: ClientConfig): string { + const appId = clientConfig.pushNotificationDetails?.nativePushAppID; + if (!appId) { + throw new Error('Native push requires pushNotificationDetails.nativePushAppID in config.json.'); + } + return appId; +} + +function getPushGatewayUrl(clientConfig: ClientConfig): string { + const pushGatewayUrl = clientConfig.pushNotificationDetails?.pushNotifyUrl; + if (!pushGatewayUrl) { + throw new Error('Native push requires pushNotificationDetails.pushNotifyUrl in config.json.'); + } + return pushGatewayUrl; +} + +export async function isNativePushPermissionGranted(): Promise { + const api = await getNativePushNotificationsApi(); + return api.isPermissionGranted(); +} + +export async function requestNativePushPermission(): Promise { + const api = await getNativePushNotificationsApi(); + return api.requestPermission(); +} + +export async function ensureNativePushRegistered(): Promise { + const permission = (await isNativePushPermissionGranted()) + ? 'granted' + : await requestNativePushPermission(); + + if (permission !== 'granted') { + return { + permission, + token: null, + }; + } + + const api = await getNativePushNotificationsApi(); + const token = await api.registerForPushNotifications(); + return { + permission: 'granted', + token, + }; +} + +export async function ensureNativePushUnregistered(): Promise { + const api = await getNativePushNotificationsApi(); + await api.unregisterForPushNotifications(); +} + +async function getCurrentNativePushToken(): Promise { + const storedToken = getStoredNativePushToken(); + if (storedToken) { + return storedToken; + } + + if (!(await isNativePushPermissionGranted())) { + return null; + } + + try { + const api = await getNativePushNotificationsApi(); + const token = await api.registerForPushNotifications(); + if (!token) { + return null; + } + + storeNativePushToken(token); + return token; + } catch { + return null; + } +} + +async function removeNativePushersForCurrentDevice(mx: MatrixClient, appId: string): Promise { + const deviceId = mx.getDeviceId() ?? ''; + if (!deviceId) { + return; + } + + const currentDevice = await mx.getDevice(deviceId); + const deviceDisplayName = currentDevice?.display_name; + if (!deviceDisplayName) { + return; + } + + const response = await mx.getPushers(); + const pushers = response.pushers ?? []; + const currentDevicePushers = pushers.filter( + (pusher) => + pusher.app_id === appId && + pusher.device_display_name === deviceDisplayName && + pusher.kind === 'http' + ); + + if (currentDevicePushers.length === 0) { + return; + } + + await Promise.allSettled( + currentDevicePushers.map((pusher) => + mx.setPusher({ + kind: null, + app_id: pusher.app_id, + pushkey: pusher.pushkey, + } as unknown as IPusherRequest) + ) + ); +} + +export async function enableNativePush( + mx: MatrixClient, + clientConfig: ClientConfig +): Promise { + const registration = await ensureNativePushRegistered(); + + if (registration.permission !== 'granted' || !registration.token) { + throw new Error( + registration.permission === 'denied' + ? 'Native push permission denied' + : 'Native push permission dismissed' + ); + } + + const appId = getNativePushAppId(clientConfig); + const pushGatewayUrl = getPushGatewayUrl(clientConfig); + + await mx.setPusher({ + kind: 'http', + app_id: appId, + pushkey: registration.token, + app_display_name: 'Sable (Native Push)', + device_display_name: + (await mx.getDevice(mx.getDeviceId() ?? '')).display_name ?? 'Mobile Device', + lang: navigator.language || 'en', + data: { + url: pushGatewayUrl, + format: 'event_id_only', + }, + append: false, + } as unknown as IPusherRequest); + + storeNativePushToken(registration.token); + return registration.token; +} + +export async function disableNativePush( + mx: MatrixClient, + clientConfig: ClientConfig +): Promise { + const appId = clientConfig.pushNotificationDetails?.nativePushAppID; + if (appId) { + const token = await getCurrentNativePushToken(); + + if (token) { + await mx.setPusher({ + kind: null, + app_id: appId, + pushkey: token, + } as unknown as IPusherRequest); + } else { + await removeNativePushersForCurrentDevice(mx, appId); + } + } + + await ensureNativePushUnregistered(); + clearStoredNativePushToken(); +} diff --git a/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts new file mode 100644 index 000000000..240c847ae --- /dev/null +++ b/src/app/features/settings/notifications/NativePushNotificationsApiClient.ts @@ -0,0 +1,17 @@ +export type NativePushNotificationsApi = { + isPermissionGranted: () => Promise; + requestPermission: () => Promise; + registerForPushNotifications: () => Promise; + unregisterForPushNotifications: () => Promise; +}; + +let nativePushNotificationsApiPromise: Promise | null = null; + +export async function getNativePushNotificationsApi(): Promise { + if (!nativePushNotificationsApiPromise) { + nativePushNotificationsApiPromise = + import('@sableclient/tauri-plugin-notifications-api') as Promise; + } + + return nativePushNotificationsApiPromise; +} diff --git a/src/app/features/settings/notifications/NotificationTransport.test.ts b/src/app/features/settings/notifications/NotificationTransport.test.ts new file mode 100644 index 000000000..8406f70aa --- /dev/null +++ b/src/app/features/settings/notifications/NotificationTransport.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from 'vitest'; +import { mergePushConfig, resolveNotificationTransport } from './NotificationTransport'; + +describe('resolveNotificationTransport', () => { + it('returns no provider when background push is disabled', () => { + const result = resolveNotificationTransport({ + platform: 'android', + enabled: false, + mode: 'auto', + unifiedPush: { available: true, status: 'ready' }, + nativePush: { available: true, status: 'ready' }, + webPush: { available: true, status: 'ready' }, + }); + + expect(result.provider).toBeNull(); + expect(result.status).toBe('unavailable'); + expect(result.degraded).toBe(false); + }); + + it('prefers UnifiedPush on Android auto when it is available', () => { + const result = resolveNotificationTransport({ + platform: 'android', + enabled: true, + mode: 'auto', + unifiedPush: { available: true, status: 'ready' }, + nativePush: { available: true, status: 'ready' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBe('unifiedpush'); + expect(result.status).toBe('ready'); + expect(result.degraded).toBe(false); + }); + + it('falls back to native push when UnifiedPush hard-fails', () => { + const result = resolveNotificationTransport({ + platform: 'android', + enabled: true, + mode: 'auto', + unifiedPush: { available: true, status: 'hard-failed' }, + nativePush: { available: true, status: 'ready' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBe('native'); + expect(result.status).toBe('ready'); + expect(result.degraded).toBe(false); + }); + + it('does not fall back on temporary UnifiedPush unavailability', () => { + const result = resolveNotificationTransport({ + platform: 'android', + enabled: true, + mode: 'auto', + unifiedPush: { available: true, status: 'temp-unavailable' }, + nativePush: { available: true, status: 'ready' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBe('unifiedpush'); + expect(result.status).toBe('temp-unavailable'); + expect(result.degraded).toBe(true); + }); + + it('does not treat desktop auto mode as web push', () => { + const result = resolveNotificationTransport({ + platform: 'desktop', + enabled: true, + mode: 'auto', + unifiedPush: { available: false, status: 'unavailable' }, + nativePush: { available: false, status: 'unavailable' }, + webPush: { available: true, status: 'ready' }, + }); + + expect(result.provider).toBeNull(); + expect(result.status).toBe('unavailable'); + expect(result.degraded).toBe(false); + }); + + it('resolves browser web auto mode to web push when available', () => { + const result = resolveNotificationTransport({ + platform: 'web', + enabled: true, + mode: 'auto', + unifiedPush: { available: false, status: 'unavailable' }, + nativePush: { available: false, status: 'unavailable' }, + webPush: { available: true, status: 'ready' }, + }); + + expect(result.provider).toBe('web'); + expect(result.status).toBe('ready'); + expect(result.degraded).toBe(false); + }); + + it('resolves iOS auto mode to native push when available', () => { + const result = resolveNotificationTransport({ + platform: 'ios', + enabled: true, + mode: 'auto', + unifiedPush: { available: false, status: 'unavailable' }, + nativePush: { available: true, status: 'ready' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBe('native'); + expect(result.status).toBe('ready'); + expect(result.degraded).toBe(false); + }); + + it('does not resolve explicit native mode when native push is unavailable', () => { + const result = resolveNotificationTransport({ + platform: 'ios', + enabled: true, + mode: 'native', + unifiedPush: { available: false, status: 'unavailable' }, + nativePush: { available: false, status: 'unavailable' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBeNull(); + expect(result.status).toBe('unavailable'); + expect(result.degraded).toBe(false); + }); + + it('does not resolve explicit web mode when web push is unavailable', () => { + const result = resolveNotificationTransport({ + platform: 'desktop', + enabled: true, + mode: 'web', + unifiedPush: { available: false, status: 'unavailable' }, + nativePush: { available: false, status: 'unavailable' }, + webPush: { available: false, status: 'unavailable' }, + }); + + expect(result.provider).toBeNull(); + expect(result.status).toBe('unavailable'); + expect(result.degraded).toBe(false); + }); +}); + +describe('mergePushConfig', () => { + it('keeps config.json defaults until a user override exists', () => { + expect( + mergePushConfig( + { unifiedPushGatewayUrl: 'https://up.default.example', unifiedPushAppID: 'moe.sable.up' }, + { unifiedPushGatewayUrl: 'https://up.user.example' } + ) + ).toEqual({ + unifiedPushGatewayUrl: 'https://up.user.example', + unifiedPushAppID: 'moe.sable.up', + }); + }); +}); diff --git a/src/app/features/settings/notifications/NotificationTransport.ts b/src/app/features/settings/notifications/NotificationTransport.ts new file mode 100644 index 000000000..09f59adb7 --- /dev/null +++ b/src/app/features/settings/notifications/NotificationTransport.ts @@ -0,0 +1,187 @@ +export type NotificationTransportMode = 'auto' | 'unifiedpush' | 'native' | 'web'; + +export type NotificationTransportProvider = 'unifiedpush' | 'native' | 'web'; + +export type NotificationTransportPlatform = 'android' | 'ios' | 'desktop' | 'web'; + +export type NotificationTransportStatus = + | 'ready' + | 'temp-unavailable' + | 'hard-failed' + | 'unavailable'; + +export type PushTransportConfig = { + mode?: NotificationTransportMode; + unifiedPushGatewayUrl?: string; + unifiedPushAppID?: string; + unifiedPushDistributor?: string; +}; + +export type PushTransportOverrides = Omit; + +export type PushTransportAvailability = { + available: boolean; + status: NotificationTransportStatus; +}; + +export type ResolveNotificationTransportInput = { + platform: NotificationTransportPlatform; + enabled: boolean; + mode: NotificationTransportMode; + unifiedPush: PushTransportAvailability; + nativePush: PushTransportAvailability; + webPush: PushTransportAvailability; +}; + +export type ResolvedNotificationTransport = { + provider: NotificationTransportProvider | null; + status: NotificationTransportStatus; + degraded: boolean; +}; + +export type { + NativePushNotificationsApi, + NativePushRegistrationResult, +} from './NativePushNotifications'; + +export { + disableNativePush, + enableNativePush, + ensureNativePushRegistered, + ensureNativePushUnregistered, + isNativePushPermissionGranted, + requestNativePushPermission, +} from './NativePushNotifications'; + +export function getSupportedNotificationTransportModes( + platform: NotificationTransportPlatform +): NotificationTransportMode[] { + if (platform === 'android') { + return ['auto', 'unifiedpush', 'native']; + } + + if (platform === 'ios') { + return ['auto', 'native']; + } + + if (platform === 'web') { + return ['auto', 'web']; + } + + return []; +} + +export function normalizeNotificationTransportMode( + mode: NotificationTransportMode, + platform: NotificationTransportPlatform +): NotificationTransportMode { + const supportedModes = getSupportedNotificationTransportModes(platform); + if (supportedModes.includes(mode)) return mode; + return supportedModes[0] ?? 'auto'; +} + +export function resolvePreferredNotificationTransportProvider( + mode: NotificationTransportMode, + platform: NotificationTransportPlatform +): NotificationTransportProvider | null { + const normalizedMode = normalizeNotificationTransportMode(mode, platform); + + if (platform === 'desktop') return null; + + if (normalizedMode === 'web') return 'web'; + if (normalizedMode === 'native') return 'native'; + if (normalizedMode === 'unifiedpush') return 'unifiedpush'; + if (platform === 'web') return 'web'; + if (platform === 'android') return 'unifiedpush'; + if (platform === 'ios') return 'native'; + return null; +} + +export function deriveLegacyPushFlags( + enabled: boolean, + provider: NotificationTransportProvider | null +): { + usePushNotifications: boolean; + useUnifiedPush: boolean; +} { + return { + usePushNotifications: enabled && provider === 'web', + useUnifiedPush: enabled && provider === 'unifiedpush', + }; +} + +export function mergePushConfig( + defaults: PushTransportConfig, + overrides: Partial +): PushTransportConfig { + return { + mode: overrides.mode ?? defaults.mode, + unifiedPushGatewayUrl: overrides.unifiedPushGatewayUrl ?? defaults.unifiedPushGatewayUrl, + unifiedPushAppID: overrides.unifiedPushAppID ?? defaults.unifiedPushAppID, + unifiedPushDistributor: overrides.unifiedPushDistributor ?? defaults.unifiedPushDistributor, + }; +} + +function resolveProvider( + availability: PushTransportAvailability, + provider: ResolvedNotificationTransport['provider'] +): ResolvedNotificationTransport { + if (!availability.available) { + return { + provider: null, + status: 'unavailable', + degraded: false, + }; + } + + return { + provider, + status: availability.status, + degraded: availability.status === 'temp-unavailable', + }; +} + +export function resolveNotificationTransport( + input: ResolveNotificationTransportInput +): ResolvedNotificationTransport { + if (!input.enabled) { + return { provider: null, status: 'unavailable', degraded: false }; + } + + if (input.mode === 'web') { + return resolveProvider(input.webPush, 'web'); + } + + if (input.mode === 'native') { + return resolveProvider(input.nativePush, 'native'); + } + + if (input.mode === 'unifiedpush') { + return resolveProvider(input.unifiedPush, 'unifiedpush'); + } + + if (input.platform === 'android') { + if ( + input.unifiedPush.available && + (input.unifiedPush.status === 'ready' || input.unifiedPush.status === 'temp-unavailable') + ) { + return resolveProvider(input.unifiedPush, 'unifiedpush'); + } + + if (input.unifiedPush.status === 'hard-failed' && input.nativePush.available) { + return resolveProvider(input.nativePush, 'native'); + } + + return resolveProvider(input.nativePush, 'native'); + } + + if (input.platform === 'ios') { + return resolveProvider(input.nativePush, 'native'); + } + + if (input.platform === 'web') { + return resolveProvider(input.webPush, 'web'); + } + + return { provider: null, status: 'unavailable', degraded: false }; +} diff --git a/src/app/features/settings/notifications/NotificationTransportRuntime.test.ts b/src/app/features/settings/notifications/NotificationTransportRuntime.test.ts new file mode 100644 index 000000000..e3ab43946 --- /dev/null +++ b/src/app/features/settings/notifications/NotificationTransportRuntime.test.ts @@ -0,0 +1,127 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { NotificationTransportRuntimeContext } from './NotificationTransportRuntime'; +import { NotificationTransportRuntime } from './NotificationTransportRuntime'; + +const unifiedPushListener = vi.hoisted(() => vi.fn()); +const unifiedPushUnregister = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); + +vi.mock('./UnifiedPushNotifications', () => ({ + listenForUnifiedPushMessages: unifiedPushListener, +})); + +afterEach(() => { + vi.clearAllMocks(); +}); + +function createContext(): NotificationTransportRuntimeContext { + return { + mx: {} as never, + showMessageContent: true, + showEncryptedMessageContent: false, + notificationSoundEnabled: true, + useInAppNotifications: false, + }; +} + +describe('NotificationTransportRuntime', () => { + it('subscribes only to the resolved provider listener', async () => { + unifiedPushListener.mockResolvedValueOnce({ + unregister: unifiedPushUnregister, + }); + + const runtime = new NotificationTransportRuntime({ + unifiedpush: unifiedPushListener, + }); + + await runtime.sync('unifiedpush', () => createContext()); + + expect(unifiedPushListener).toHaveBeenCalledOnce(); + expect(unifiedPushListener).toHaveBeenCalledWith(expect.any(Function)); + expect(unifiedPushUnregister).not.toHaveBeenCalled(); + }); + + it('cleans up the active listener when the provider changes', async () => { + unifiedPushListener.mockResolvedValueOnce({ + unregister: unifiedPushUnregister, + }); + + const runtime = new NotificationTransportRuntime({ + unifiedpush: unifiedPushListener, + }); + + await runtime.sync('unifiedpush', () => createContext()); + await runtime.sync('native', () => createContext()); + + expect(unifiedPushUnregister).toHaveBeenCalledOnce(); + }); + + it('does not recreate the listener when the provider stays the same', async () => { + unifiedPushListener.mockResolvedValueOnce({ + unregister: unifiedPushUnregister, + }); + + const runtime = new NotificationTransportRuntime({ + unifiedpush: unifiedPushListener, + }); + + await runtime.sync('unifiedpush', () => createContext()); + await runtime.sync('unifiedpush', () => ({ + ...createContext(), + notificationSoundEnabled: false, + })); + + expect(unifiedPushListener).toHaveBeenCalledOnce(); + expect(unifiedPushUnregister).not.toHaveBeenCalled(); + }); + + it('disposes a stale listener registration when the provider changes mid-startup', async () => { + let resolveListener: (() => void) | undefined; + const lateUnregister = vi.fn().mockResolvedValue(undefined); + const lateListener = new Promise<{ unregister: typeof lateUnregister }>((resolve) => { + resolveListener = () => resolve({ unregister: lateUnregister }); + }); + const slowListener = vi.fn().mockReturnValueOnce(lateListener); + + const runtime = new NotificationTransportRuntime({ + unifiedpush: slowListener, + }); + + const firstSync = runtime.sync('unifiedpush', () => createContext()); + const secondSync = runtime.sync('native', () => createContext()); + resolveListener?.(); + + await Promise.all([firstSync, secondSync]); + + expect(lateUnregister).toHaveBeenCalledOnce(); + }); + + it('disposes the active listener when stopped', async () => { + unifiedPushListener.mockResolvedValueOnce({ + unregister: unifiedPushUnregister, + }); + + const runtime = new NotificationTransportRuntime({ + unifiedpush: unifiedPushListener, + }); + + await runtime.sync('unifiedpush', () => createContext()); + await runtime.dispose(); + + expect(unifiedPushUnregister).toHaveBeenCalledOnce(); + }); + + it('does not treat providers without listener factories as active', async () => { + const nativeListener = vi.fn().mockResolvedValue({ + unregister: vi.fn().mockResolvedValue(undefined), + }); + const listenerFactories: Record = {}; + const runtime = new NotificationTransportRuntime(listenerFactories); + + await runtime.sync('native', () => createContext()); + + listenerFactories.native = nativeListener; + await runtime.sync('native', () => createContext()); + + expect(nativeListener).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/features/settings/notifications/NotificationTransportRuntime.ts b/src/app/features/settings/notifications/NotificationTransportRuntime.ts new file mode 100644 index 000000000..09cfa540a --- /dev/null +++ b/src/app/features/settings/notifications/NotificationTransportRuntime.ts @@ -0,0 +1,89 @@ +import type { MatrixClient } from '$types/matrix-sdk'; + +export type NotificationTransportProvider = 'unifiedpush' | 'native' | 'web'; + +export type NotificationTransportRuntimeContext = { + mx: MatrixClient; + showMessageContent: boolean; + showEncryptedMessageContent: boolean; + notificationSoundEnabled: boolean; + useInAppNotifications: boolean; +}; + +export type NotificationTransportListenerHandle = { + unregister: () => Promise | void; +}; + +export type NotificationTransportListenerFactory = ( + getContext: () => NotificationTransportRuntimeContext +) => Promise; + +export type NotificationTransportListenerFactories = Partial< + Record +>; + +type NotificationTransportListenerCleanup = () => Promise | void; + +const defaultListenerFactories: NotificationTransportListenerFactories = { + unifiedpush: async (getContext) => { + const { listenForUnifiedPushMessages } = await import('./UnifiedPushNotifications'); + return listenForUnifiedPushMessages(getContext); + }, +}; + +export class NotificationTransportRuntime { + #listenerFactories: NotificationTransportListenerFactories; + + #activeProvider: NotificationTransportProvider | null = null; + + #activeGeneration = 0; + + #cleanup: NotificationTransportListenerCleanup | null = null; + + constructor( + listenerFactories: NotificationTransportListenerFactories = defaultListenerFactories + ) { + this.#listenerFactories = listenerFactories; + } + + async sync( + provider: NotificationTransportProvider | null, + getContext: () => NotificationTransportRuntimeContext + ): Promise { + if (provider === this.#activeProvider) return; + + const listenerFactory = provider ? this.#listenerFactories[provider] : undefined; + const nextActiveProvider = listenerFactory ? provider : null; + + const generation = this.#activeGeneration + 1; + this.#activeGeneration = generation; + const previousCleanup = this.#cleanup; + this.#cleanup = null; + this.#activeProvider = nextActiveProvider; + + if (previousCleanup) { + await Promise.resolve(previousCleanup()).catch(() => undefined); + } + + if (generation !== this.#activeGeneration) return; + if (!listenerFactory) return; + + const listener = await listenerFactory(getContext); + if (generation !== this.#activeGeneration || nextActiveProvider !== this.#activeProvider) { + await Promise.resolve(listener.unregister()).catch(() => undefined); + return; + } + + this.#cleanup = () => listener.unregister(); + } + + async dispose(): Promise { + this.#activeGeneration += 1; + const cleanup = this.#cleanup; + this.#cleanup = null; + this.#activeProvider = null; + + if (!cleanup) return; + await Promise.resolve(cleanup()).catch(() => undefined); + } +} diff --git a/src/app/features/settings/notifications/Notifications.tsx b/src/app/features/settings/notifications/Notifications.tsx index e034f6743..f8935b782 100644 --- a/src/app/features/settings/notifications/Notifications.tsx +++ b/src/app/features/settings/notifications/Notifications.tsx @@ -1,11 +1,9 @@ import { Box, Text, IconButton, Icon, Icons, Scroll } from 'folds'; import { Page, PageContent, PageHeader } from '$components/page'; -import { isTauri } from '@tauri-apps/api/core'; import { SystemNotification } from './SystemNotification'; import { AllMessagesNotifications } from './AllMessages'; import { SpecialMessagesNotifications } from './SpecialMessages'; import { KeywordMessagesNotifications } from './KeywordMessages'; -import UnifiedPushNotificationSetting from './UnifiedPushNotificationSetting'; type NotificationsProps = { requestClose: () => void; @@ -32,7 +30,6 @@ export function Notifications({ requestClose }: NotificationsProps) { - {isTauri() && } diff --git a/src/app/features/settings/notifications/SystemNotification.test.tsx b/src/app/features/settings/notifications/SystemNotification.test.tsx new file mode 100644 index 000000000..5d5ef8c6d --- /dev/null +++ b/src/app/features/settings/notifications/SystemNotification.test.tsx @@ -0,0 +1,473 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + deriveLegacyPushSync, + SystemNotification, + shouldRefreshBackgroundPushTransport, + switchBackgroundPushTransport, +} from './SystemNotification'; + +const { + settings, + mockIsTauri, + mockOsType, + mockMobileOrTablet, + mockUseSetting, + mockEnablePushNotifications, + mockDisablePushNotifications, + mockRequestBrowserNotificationPermission, + mockEnableUnifiedPush, + mockTryEnableUnifiedPush, + mockDisableUnifiedPush, + mockEnsureNativePushRegistered, + mockEnsureNativePushUnregistered, + mockLoadUnifiedPushDistributorState, + mockEnsureUnifiedPushDistributorSelection, + mockSwitchUnifiedPushDistributorSelection, + mockSetUnifiedPushDistributorSelection, + mockPushSubscriptionAtom, + mockUnifiedPushEndpointAtom, + mockPushSubscriptionTuple, + mockUnifiedPushEndpointTuple, +} = vi.hoisted(() => { + const baseSettings = { + useInAppNotifications: true, + useSystemNotifications: true, + isNotificationSounds: true, + showMessageContentInNotifications: false, + showMessageContentInEncryptedNotifications: false, + clearNotificationsOnRead: false, + showUnreadCounts: false, + badgeCountDMsOnly: true, + showPingCounts: true, + faviconForMentionsOnly: false, + highlightMentions: true, + backgroundPushEnabled: true, + backgroundPushProvider: null, + pushTransportMode: 'auto' as const, + pushTransportOverride: {}, + usePushNotifications: false, + useUnifiedPush: false, + }; + const settingsState = { ...baseSettings }; + const setterCache = new Map>(); + const useSettingMock = vi.fn((_: unknown, key: keyof typeof settingsState) => { + if (!setterCache.has(key)) { + setterCache.set( + key, + vi.fn((valueOrUpdater: unknown) => { + const current = settingsState[key]; + settingsState[key] = + typeof valueOrUpdater === 'function' + ? (valueOrUpdater as (currentValue: never) => never)(current as never) + : (valueOrUpdater as never); + }) + ); + } + + return [settingsState[key], setterCache.get(key)!]; + }); + + const pushSubscriptionAtomMock = {}; + const unifiedPushEndpointAtomMock = {}; + const pushSubscriptionTupleMock = [null, vi.fn()] as const; + const unifiedPushEndpointTupleMock = [null, vi.fn()] as const; + + return { + settings: settingsState, + mockIsTauri: vi.fn(), + mockOsType: vi.fn(), + mockMobileOrTablet: vi.fn(), + mockUseSetting: useSettingMock, + mockEnablePushNotifications: vi.fn(), + mockDisablePushNotifications: vi.fn(), + mockRequestBrowserNotificationPermission: vi.fn(), + mockEnableUnifiedPush: vi.fn(), + mockTryEnableUnifiedPush: vi.fn(), + mockDisableUnifiedPush: vi.fn(), + mockEnsureNativePushRegistered: vi.fn(), + mockEnsureNativePushUnregistered: vi.fn(), + mockLoadUnifiedPushDistributorState: vi.fn(), + mockEnsureUnifiedPushDistributorSelection: vi.fn(), + mockSwitchUnifiedPushDistributorSelection: vi.fn(), + mockSetUnifiedPushDistributorSelection: vi.fn(), + mockPushSubscriptionAtom: pushSubscriptionAtomMock, + mockUnifiedPushEndpointAtom: unifiedPushEndpointAtomMock, + mockPushSubscriptionTuple: pushSubscriptionTupleMock, + mockUnifiedPushEndpointTuple: unifiedPushEndpointTupleMock, + }; +}); + +vi.mock('folds', async () => { + const actual = await vi.importActual('folds'); + + return { + ...actual, + Switch: ({ + value, + onChange, + disabled, + }: { + value: boolean; + onChange: (nextValue: boolean) => void; + disabled?: boolean; + }) => ( + + setMenuCords(undefined), + clickOutsideDeactivates: true, + isKeyForward: (evt: KeyboardEvent) => + evt.key === 'ArrowDown' || evt.key === 'ArrowRight', + isKeyBackward: (evt: KeyboardEvent) => + evt.key === 'ArrowUp' || evt.key === 'ArrowLeft', + escapeDeactivates: stopPropagation, + }} + > + + + {options.map((option) => ( + handleSelect(option.value)} + > + + {option.label} + + + ))} + + + + } + /> + + ); +} + +function NotificationTransportOverrideInput({ + title, + description, + name, + value, + placeholder, + onSave, +}: { + title: string; + description: string; + name: string; + value: string; + placeholder: string; + onSave: (value: string) => void; +}) { + const [draftValue, setDraftValue] = useState(value); + + useEffect(() => { + setDraftValue(value); + }, [value]); + + const hasChanges = draftValue !== value; + + const handleReset = () => { + setDraftValue(value); + }; + + const handleSubmit = (evt: FormEvent) => { + evt.preventDefault(); + onSave(draftValue); + }; + + return ( + + + + + setDraftValue(evt.currentTarget.value)} + style={{ paddingRight: config.space.S200 }} + after={ + hasChanges && ( + + + + ) + } + /> + + - ) : browserPermission === 'granted' ? ( - - ) : null + + + + ); +} + +function labelUnifiedPushDistributorOption(distributor: string): string { + const lastSegment = distributor + .split(/[./]/) + .map((segment) => segment.trim()) + .filter(Boolean) + .at(-1); + + return lastSegment ?? distributor; +} + +function BackgroundPushNotificationSetting() { + const mx = useMatrixClient(); + const clientConfig = useClientConfig(); + const pushTransportDefaults = { + unifiedPushGatewayUrl: + clientConfig.pushTransport?.unifiedPushGatewayUrl ?? + clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl, + unifiedPushAppID: + clientConfig.pushTransport?.unifiedPushAppID ?? + clientConfig.pushNotificationDetails?.unifiedPushAppID, + unifiedPushDistributor: clientConfig.pushTransport?.unifiedPushDistributor, + }; + const [backgroundPushEnabled, setBackgroundPushEnabled] = useSetting( + settingsAtom, + 'backgroundPushEnabled' + ); + const [backgroundPushProvider, setBackgroundPushProvider] = useSetting( + settingsAtom, + 'backgroundPushProvider' + ); + const [pushTransportMode, setPushTransportMode] = useSetting(settingsAtom, 'pushTransportMode'); + const [pushTransportOverride, setPushTransportOverride] = useSetting( + settingsAtom, + 'pushTransportOverride' + ); + const [legacyPushNotifications, setLegacyPushNotifications] = useSetting( + settingsAtom, + 'usePushNotifications' + ); + const [legacyUnifiedPush, setLegacyUnifiedPush] = useSetting(settingsAtom, 'useUnifiedPush'); + const pushSubAtom = useAtom(pushSubscriptionAtom); + const [upEndpoint, setUpEndpoint] = useAtom(unifiedPushEndpointAtom); + const unifiedPushStateRef = useRef(upEndpoint); + const [isLoading, setIsLoading] = useState(true); + const [error, setError] = useState(null); + const [selectedDistributor, setSelectedDistributor] = useState( + pushTransportOverride.unifiedPushDistributor ?? '' + ); + const [availableDistributors, setAvailableDistributors] = useState([]); + const browserPermission = usePermissionState('notifications', getNotificationState()); + const isTauriRuntime = isTauri(); + const runtimePlatform = getBackgroundPushPlatform(isTauriRuntime); + const supportedModes = getSupportedNotificationTransportModes(runtimePlatform); + const selectedTransportMode = normalizeNotificationTransportMode( + pushTransportMode, + runtimePlatform + ); + const preferredKind = resolvePreferredNotificationTransportProvider( + selectedTransportMode, + runtimePlatform + ); + const effectiveKind = backgroundPushEnabled + ? (backgroundPushProvider ?? preferredKind) + : preferredKind; + const effectivePushTransport = mergePushConfig(pushTransportDefaults, pushTransportOverride); + const backgroundPushSupported = supportedModes.length > 0; + const showUnifiedPushSettings = + runtimePlatform === 'android' && + (selectedTransportMode === 'auto' || selectedTransportMode === 'unifiedpush'); + const nativePushConfigError = + effectiveKind === 'native' ? getNativePushConfigError(clientConfig) : null; + const modeOptions = supportedModes.map((mode) => ({ + value: mode, + label: labelTransportMode(mode), + })); + const distributorOptions = Array.from( + new Set( + [selectedDistributor, ...availableDistributors].filter( + (distributor): distributor is string => distributor.trim().length > 0 + ) + ) + ).map((distributor) => ({ + value: distributor, + label: labelUnifiedPushDistributorOption(distributor), + })); + + useEffect(() => { + unifiedPushStateRef.current = upEndpoint; + }, [upEndpoint]); + + useEffect(() => { + const sync = deriveLegacyPushSync({ + enabled: backgroundPushEnabled, + provider: backgroundPushEnabled ? (backgroundPushProvider ?? preferredKind) : null, + }); + + if (legacyPushNotifications !== sync.usePushNotifications) { + setLegacyPushNotifications(sync.usePushNotifications); + } + if (legacyUnifiedPush !== sync.useUnifiedPush) { + setLegacyUnifiedPush(sync.useUnifiedPush); + } + }, [ + backgroundPushEnabled, + backgroundPushProvider, + preferredKind, + legacyPushNotifications, + legacyUnifiedPush, + setLegacyPushNotifications, + setLegacyUnifiedPush, + ]); + + useEffect(() => { + if (runtimePlatform !== 'android') { + setAvailableDistributors([]); + setIsLoading(false); + return undefined; + } + + let active = true; + loadUnifiedPushDistributorState() + .then((state) => { + if (!active) return; + setAvailableDistributors(state.distributors); + const overrideDistributor = pushTransportOverride.unifiedPushDistributor; + const nextDistributor = overrideDistributor || state.selectedDistributor; + if (nextDistributor) { + setSelectedDistributor(nextDistributor); + if (!overrideDistributor) { + setPushTransportOverride((current) => + current.unifiedPushDistributor === nextDistributor + ? current + : { + ...current, + unifiedPushDistributor: nextDistributor, + } + ); + } + } + }) + .catch((caughtError) => { + if (!active) return; + setError(caughtError instanceof Error ? caughtError.message : String(caughtError)); + }) + .finally(() => { + if (active) setIsLoading(false); + }); + + return () => { + active = false; + }; + }, [runtimePlatform, pushTransportOverride.unifiedPushDistributor, setPushTransportOverride]); + + const updatePushTransportOverride = (patch: Partial) => { + setPushTransportOverride((current) => + cleanPushTransportOverrides({ + ...current, + ...patch, + }) + ); + }; + + const buildUnifiedPushTransportConfig = (): UnifiedPushTransportConfigInput => ({ + unifiedPushGatewayUrl: effectivePushTransport.unifiedPushGatewayUrl, + unifiedPushAppID: effectivePushTransport.unifiedPushAppID, + }); + + const buildRegisteredUnifiedPushState = ( + registration: { + endpoint: string; + instance: string; + distributor?: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; + }, + distributorOverride?: string + ): UnifiedPushState => ({ + endpoint: registration.endpoint, + instance: registration.instance, + appId: effectivePushTransport.unifiedPushAppID?.trim() ?? DEFAULT_UNIFIED_PUSH_APP_ID, + gatewayUrl: effectivePushTransport.unifiedPushGatewayUrl?.trim() ?? undefined, + status: 'registered', + distributor: distributorOverride ?? registration.distributor, + permissionState: 'granted', + pubKeySet: registration.pubKeySet, + }); + + const setUnifiedPushEndpointState = (endpoint: UnifiedPushState) => { + unifiedPushStateRef.current = endpoint; + setUpEndpoint(endpoint); + }; + + const ensureConfiguredUnifiedPushDistributor = async (): Promise => { + const distributor = await ensureUnifiedPushDistributorSelection( + availableDistributors, + selectedDistributor || effectivePushTransport.unifiedPushDistributor || '' + ); + + if (!distributor) { + return ''; + } + + setSelectedDistributor(distributor); + updatePushTransportOverride({ unifiedPushDistributor: distributor }); + return distributor; + }; + + const activateTransport = async (kind: BackgroundPushKind | null) => { + if (!kind) { + throw new Error('Background push is not available on this platform.'); + } + + if (kind === 'web') { + if (browserPermission === 'prompt') { + const permissionResult = await requestBrowserNotificationPermission(); + if (permissionResult !== 'granted') { + throw new Error('Browser notification permission was not granted.'); + } } - /> + await enablePushNotifications(mx, clientConfig, pushSubAtom); + return; + } + + if (kind === 'unifiedpush') { + const distributor = await ensureConfiguredUnifiedPushDistributor(); + if (!distributor) { + throw new Error('No UnifiedPush distributor selected.'); + } + const result = await enableUnifiedPush(mx, buildUnifiedPushTransportConfig()); + setUnifiedPushEndpointState( + buildRegisteredUnifiedPushState( + { + ...result, + }, + distributor + ) + ); + return; + } + + if (nativePushConfigError) { + throw new Error(nativePushConfigError); + } + + await enableNativePush(mx, clientConfig); + }; + + const deactivateTransport = async (kind: BackgroundPushKind | null) => { + if (!kind) return; + + if (kind === 'web') { + await disablePushNotifications(mx, clientConfig, pushSubAtom); + return; + } + + if (kind === 'unifiedpush') { + const currentUnifiedPushState = unifiedPushStateRef.current; + await disableUnifiedPush(mx, { + pushkey: currentUnifiedPushState?.endpoint, + config: { + unifiedPushAppID: + currentUnifiedPushState?.appId ?? effectivePushTransport.unifiedPushAppID, + }, + }); + setUnifiedPushEndpointState(null); + return; + } + + await disableNativePush(mx, clientConfig); + }; + + const activateAndroidAutoTransport = async ( + currentKind: BackgroundPushKind | null + ): 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'; + }; + + const distributor = await ensureConfiguredUnifiedPushDistributor(); + if (!distributor) { + return nativeFallback('UnifiedPush is not configured.'); + } + + const result = await tryEnableUnifiedPush(mx, buildUnifiedPushTransportConfig()); + if (result.status === 'registered') { + setUnifiedPushEndpointState(buildRegisteredUnifiedPushState(result)); + return 'unifiedpush'; + } + + if (result.status === 'temp-unavailable') { + throw new Error(result.error); + } + + return nativeFallback(result.error); + }; + + const activateMode = async ( + mode: NotificationTransportMode, + currentKind: BackgroundPushKind | null + ): Promise => { + const normalizedMode = normalizeNotificationTransportMode(mode, runtimePlatform); + const nextPreferredKind = resolvePreferredNotificationTransportProvider( + normalizedMode, + runtimePlatform + ); + + if (!nextPreferredKind) { + throw new Error('Selected transport is not available on this platform.'); + } + + if (normalizedMode === 'auto' && runtimePlatform === 'android') { + if (currentKind === 'unifiedpush') { + return 'unifiedpush'; + } + return activateAndroidAutoTransport(currentKind); + } + + if (currentKind === nextPreferredKind) { + return currentKind; + } + + await activateTransport(nextPreferredKind); + return nextPreferredKind; + }; + + const handleToggleBackgroundPush = async (wantsPush: boolean) => { + setIsLoading(true); + setError(null); + try { + if (!backgroundPushSupported) { + throw new Error('Background push is not available in the desktop Tauri build yet.'); + } + if (wantsPush) { + const nextKind = await activateMode(selectedTransportMode, null); + setBackgroundPushProvider(nextKind); + } else { + await deactivateTransport(backgroundPushProvider ?? preferredKind); + setBackgroundPushProvider(null); + } + setBackgroundPushEnabled(wantsPush); + } catch (caughtError) { + setError(caughtError instanceof Error ? caughtError.message : String(caughtError)); + } finally { + setIsLoading(false); + } + }; + + const handleModeChange = async (nextMode: NotificationTransportMode) => { + if (nextMode === selectedTransportMode) return; + setIsLoading(true); + setError(null); + const previousKind = backgroundPushEnabled ? (backgroundPushProvider ?? preferredKind) : null; + + try { + if (backgroundPushEnabled) { + const nextKind = await switchBackgroundPushTransport({ + previousKind, + activate: () => activateMode(nextMode, previousKind), + deactivate: deactivateTransport, + }); + setBackgroundPushProvider(nextKind); + } else { + setBackgroundPushProvider(null); + } + setPushTransportMode(nextMode); + } catch (caughtError) { + setError(caughtError instanceof Error ? caughtError.message : String(caughtError)); + } finally { + setIsLoading(false); + } + }; + + const handleDistributorChange = async (distributor: string) => { + if (distributor === selectedDistributor) return; + setIsLoading(true); + setError(null); + try { + const activeKind = backgroundPushEnabled ? (backgroundPushProvider ?? preferredKind) : null; + if (backgroundPushEnabled && activeKind === 'unifiedpush') { + const result = await switchUnifiedPushDistributorSelection( + distributor, + selectedDistributor, + () => enableUnifiedPush(mx, buildUnifiedPushTransportConfig()) + ); + setUnifiedPushEndpointState( + buildRegisteredUnifiedPushState( + { + ...result, + }, + distributor + ) + ); + } else { + await setUnifiedPushDistributorSelection(distributor); + } + setSelectedDistributor(distributor); + updatePushTransportOverride({ unifiedPushDistributor: distributor }); + } catch (caughtError) { + setError(caughtError instanceof Error ? caughtError.message : String(caughtError)); + } finally { + setIsLoading(false); + } + }; + + const transportDescription = (() => { + if (error) { + return ( + + {error} + + ); + } + + if (!backgroundPushSupported) { + return ( + + Background push is not available in the desktop Tauri build yet. + + ); + } + + if (!backgroundPushEnabled) { + return 'Receive notifications when the app is closed or in the background.'; + } + + if (nativePushConfigError) { + return ( + + {nativePushConfigError} + + ); + } + + if (browserPermission === 'denied' && effectiveKind === 'web') { + return ( + + Permission blocked. Please allow notifications in your browser settings. + + ); + } + + if (!effectiveKind) { + return 'Receive notifications when the app is closed or in the background.'; + } + + return `Background push is using ${labelTransportKind(effectiveKind)}.`; + })(); + + const renderTransportToggle = () => { + if (isLoading) { + return ; + } + + if (!backgroundPushSupported) { + return ; + } + + if (!backgroundPushEnabled && nativePushConfigError) { + return ; + } + + if (!backgroundPushEnabled && effectiveKind === 'web' && browserPermission === 'prompt') { + return ( + + ); + } + + return ; + }; + + return ( + <> + + {supportedModes.length > 2 && ( + + } + /> + )} + {showUnifiedPushSettings && ( + <> + 0 ? ( + + ) : undefined + } + > + {distributorOptions.length === 0 && ( + + No UnifiedPush distributors were detected yet. + + )} + + + updatePushTransportOverride({ unifiedPushGatewayUrl: nextValue }) + } + /> + updatePushTransportOverride({ unifiedPushAppID: nextValue })} + /> + + )} + ); } @@ -243,16 +1050,6 @@ export function SystemNotification() { /> )} - {mobileOrTablet() && ( - - - - )} {!mobileOrTablet() && ( )} + + + Promise | void; +}; + +export type TauriNotificationsApi = { + Importance: { + readonly Default: string; + }; + createChannel: (channel: { + id: string; + name: string; + description?: string; + importance?: string; + vibration?: boolean; + }) => Promise; + sendNotification: (payload: Record) => Promise; + removeActive: (payload: Array<{ id: number; tag?: string }>) => Promise; + onUnifiedPushMessage: ( + listener: (payload: Record) => void + ) => Promise | NotificationPluginListener; + onUnifiedPushEndpoint: ( + listener: (payload: { endpoint: string; instance: string }) => void + ) => Promise | NotificationPluginListener; +}; + +let notificationsApiPromise: Promise | null = null; + +export async function getTauriNotificationsApi(): Promise { + if (!notificationsApiPromise) { + notificationsApiPromise = + import('@sableclient/tauri-plugin-notifications-api') as Promise; + } + + return notificationsApiPromise; +} diff --git a/src/app/features/settings/notifications/UnifiedPushMessageListener.test.ts b/src/app/features/settings/notifications/UnifiedPushMessageListener.test.ts new file mode 100644 index 000000000..8bf1a67f1 --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushMessageListener.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createUnifiedPushMessageListener } from './UnifiedPushMessageListener'; + +describe('createUnifiedPushMessageListener', () => { + it('catches rejected payload handlers instead of leaking unhandled rejections', async () => { + const onError = vi.fn(); + const listener = createUnifiedPushMessageListener(async () => { + throw new Error('boom'); + }, onError); + + expect(listener({})).toBeUndefined(); + await Promise.resolve(); + + expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' })); + }); +}); diff --git a/src/app/features/settings/notifications/UnifiedPushMessageListener.ts b/src/app/features/settings/notifications/UnifiedPushMessageListener.ts new file mode 100644 index 000000000..b7e6d2640 --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushMessageListener.ts @@ -0,0 +1,11 @@ +export type UnifiedPushMessageHandler = (data: Record) => Promise; +export type UnifiedPushMessageErrorHandler = (error: unknown) => void; + +export function createUnifiedPushMessageListener( + handler: UnifiedPushMessageHandler, + onError: UnifiedPushMessageErrorHandler +) { + return (data: Record) => { + handler(data).catch(onError); + }; +} diff --git a/src/app/features/settings/notifications/UnifiedPushNotificationSetting.tsx b/src/app/features/settings/notifications/UnifiedPushNotificationSetting.tsx deleted file mode 100644 index 8e31d61cb..000000000 --- a/src/app/features/settings/notifications/UnifiedPushNotificationSetting.tsx +++ /dev/null @@ -1,181 +0,0 @@ -/* eslint-disable no-nested-ternary */ -import { MouseEventHandler, useEffect, useState } from 'react'; -import { Text, Switch, Spinner, Button, color, Menu, PopOut, MenuItem, RectCords } from 'folds'; -import FocusTrap from 'focus-trap-react'; -import { useAtom } from 'jotai'; -import { SettingTile } from '$components/setting-tile'; -import { useSetting } from '$state/hooks/settings'; -import { settingsAtom } from '$state/settings'; -import { useMatrixClient } from '$hooks/useMatrixClient'; -import { useClientConfig } from '$hooks/useClientConfig'; -import { unifiedPushEndpointAtom } from '$state/unifiedPushEndpoint'; -import { stopPropagation } from '$utils/keyboard'; -import { - enableUnifiedPush, - disableUnifiedPush, - getUnifiedPushDistributors, - getUnifiedPushDistributor, - saveUnifiedPushDistributor, -} from './UnifiedPushNotifications'; - -export default function UnifiedPushNotificationSetting() { - const mx = useMatrixClient(); - const clientConfig = useClientConfig(); - const [useUP, setUseUP] = useSetting(settingsAtom, 'useUnifiedPush'); - const [upEndpoint, setUpEndpoint] = useAtom(unifiedPushEndpointAtom); - const [isLoading, setIsLoading] = useState(false); - const [error, setError] = useState(null); - const [distributors, setDistributors] = useState([]); - const [currentDistributor, setCurrentDistributor] = useState(''); - const [menuCords, setMenuCords] = useState(); - - useEffect(() => { - Promise.all([ - getUnifiedPushDistributors().catch(() => ({ distributors: [] as string[] })), - getUnifiedPushDistributor().catch(() => ({ distributor: '' })), - ]).then(async ([distResult, savedResult]) => { - setDistributors(distResult.distributors); - setCurrentDistributor(savedResult.distributor); - - // Auto-save the only available distributor when none is saved yet. - // UP connector 3.x requires an explicit selection before register() works. - if (!savedResult.distributor && distResult.distributors.length === 1) { - await saveUnifiedPushDistributor(distResult.distributors[0]); - setCurrentDistributor(distResult.distributors[0]); - } - }); - }, []); - - const handleToggle = async (wantsUP: boolean) => { - setIsLoading(true); - setError(null); - try { - if (wantsUP) { - if (!currentDistributor && distributors.length > 0) { - await saveUnifiedPushDistributor(distributors[0]); - setCurrentDistributor(distributors[0]); - } - - const result = await enableUnifiedPush(mx, clientConfig); - setUpEndpoint(result); - setUseUP(true); - } else { - await disableUnifiedPush(mx, clientConfig, upEndpoint?.endpoint); - setUpEndpoint(null); - setUseUP(false); - } - } catch (e) { - const msg = e instanceof Error ? e.message : String(e); - console.error('UnifiedPush toggle failed:', e); - setError(msg); - } finally { - setIsLoading(false); - } - }; - - const handleSelectDistributor = async (distributor: string) => { - setMenuCords(undefined); - if (distributor === currentDistributor) return; - setIsLoading(true); - try { - if (useUP) { - await disableUnifiedPush(mx, clientConfig, upEndpoint?.endpoint); - } - await saveUnifiedPushDistributor(distributor); - setCurrentDistributor(distributor); - if (useUP) { - const result = await enableUnifiedPush(mx, clientConfig); - setUpEndpoint(result); - } - } catch (e) { - console.error('Distributor switch failed:', e); - } finally { - setIsLoading(false); - } - }; - - const distributorLabel = (pkg: string) => { - const parts = pkg.split('.'); - return parts[parts.length - 1] ?? pkg; - }; - - const handleDistributorMenu: MouseEventHandler = (evt) => { - setMenuCords(evt.currentTarget.getBoundingClientRect()); - }; - - return ( - <> - - {error} - - ) : distributors.length === 0 ? ( - - No UnifiedPush distributor installed. Install one (e.g. ntfy, NextPush) to use this - feature. - - ) : ( - 'Receive background notifications via UnifiedPush without Google Services.' - ) - } - after={ - isLoading ? ( - - ) : ( - - ) - } - /> - {distributors.length > 1 && ( - - setMenuCords(undefined), - clickOutsideDeactivates: true, - escapeDeactivates: stopPropagation, - }} - > - - {distributors.map((d) => ( - handleSelectDistributor(d)} - aria-pressed={d === currentDistributor} - > - {distributorLabel(d)} - - ))} - - - } - /> - - - } - /> - )} - - ); -} diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts new file mode 100644 index 000000000..21570951e --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.test.ts @@ -0,0 +1,151 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const notificationsApi = vi.hoisted(() => ({ + onUnifiedPushMessage: vi.fn(), + onUnifiedPushEndpoint: vi.fn(), + sendNotification: vi.fn(), + removeActive: vi.fn(), + createChannel: vi.fn(), + Importance: { + Default: 'default', + }, +})); + +const unifiedPushTransport = vi.hoisted(() => ({ + getUnifiedPushDistributor: vi.fn(), + getUnifiedPushDistributors: vi.fn(), + registerUnifiedPushTransport: vi.fn(), + saveUnifiedPushDistributor: vi.fn(), + unregisterUnifiedPushTransport: vi.fn(), +})); + +const getTauriNotificationsApi = vi.hoisted(() => vi.fn().mockResolvedValue(notificationsApi)); + +const matrixClient = vi.hoisted(() => ({ + setPusher: vi.fn().mockResolvedValue(undefined), + getDeviceId: vi.fn(() => 'DEVICE'), + getDevice: vi.fn().mockResolvedValue({ display_name: 'Pixel' }), + getPushers: vi.fn().mockResolvedValue({ pushers: [] }), +})); + +vi.mock('./UnifiedPushTransport', () => unifiedPushTransport); + +vi.mock('./TauriNotificationsApiClient', () => ({ + getTauriNotificationsApi, +})); + +async function loadUnifiedPushNotificationsModule() { + return import('./UnifiedPushNotifications'); +} + +describe('UnifiedPushNotifications', () => { + beforeEach(() => { + notificationsApi.createChannel.mockResolvedValue(undefined); + getTauriNotificationsApi.mockResolvedValue(notificationsApi); + unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({ + status: 'registered', + permissionState: 'granted', + endpoint: 'https://up.example/device', + instance: 'instance-1', + distributor: 'org.unifiedpush.distributor.ntfy', + }); + unifiedPushTransport.unregisterUnifiedPushTransport.mockResolvedValue(undefined); + matrixClient.setPusher.mockClear(); + matrixClient.getPushers.mockResolvedValue({ pushers: [] }); + vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('gateway probe failed'))); + }); + + afterEach(() => { + vi.clearAllMocks(); + vi.unstubAllGlobals(); + }); + + it('registers the Matrix pusher with the resolved UnifiedPush overrides', async () => { + const { tryEnableUnifiedPush } = await loadUnifiedPushNotificationsModule(); + + await expect( + tryEnableUnifiedPush(matrixClient as never, { + unifiedPushAppID: 'com.example.up', + unifiedPushGatewayUrl: ' https://gateway.example/_matrix/push/v1/notify ', + }) + ).resolves.toMatchObject({ + status: 'registered', + endpoint: 'https://up.example/device', + instance: 'instance-1', + }); + + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: 'http', + app_id: 'com.example.up', + pushkey: 'https://up.example/device', + data: expect.objectContaining({ + url: 'https://gateway.example/_matrix/push/v1/notify', + }), + }) + ); + }, 15_000); + + it('falls back to the default UnifiedPush app id when no override is provided', async () => { + const { DEFAULT_UNIFIED_PUSH_APP_ID, tryEnableUnifiedPush } = + await loadUnifiedPushNotificationsModule(); + + await tryEnableUnifiedPush(matrixClient as never); + + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + app_id: DEFAULT_UNIFIED_PUSH_APP_ID, + }) + ); + }); + + it('removes current-device UnifiedPush pushers when the cached endpoint is unavailable', async () => { + const { disableUnifiedPush } = await loadUnifiedPushNotificationsModule(); + + matrixClient.getPushers.mockResolvedValue({ + pushers: [ + { + app_id: 'com.example.up', + pushkey: 'stale-endpoint-1', + device_display_name: 'Pixel', + kind: 'http', + }, + { + app_id: 'com.example.up', + pushkey: 'stale-endpoint-2', + device_display_name: 'Pixel', + kind: 'http', + }, + { + app_id: 'com.example.up', + pushkey: 'other-device-endpoint', + device_display_name: 'Other Phone', + kind: 'http', + }, + ], + }); + + await disableUnifiedPush(matrixClient as never, { + config: { + unifiedPushAppID: 'com.example.up', + }, + }); + + expect(matrixClient.setPusher).toHaveBeenCalledTimes(2); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: null, + app_id: 'com.example.up', + pushkey: 'stale-endpoint-1', + }) + ); + expect(matrixClient.setPusher).toHaveBeenCalledWith( + expect.objectContaining({ + kind: null, + app_id: 'com.example.up', + pushkey: 'stale-endpoint-2', + }) + ); + expect(unifiedPushTransport.unregisterUnifiedPushTransport).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/features/settings/notifications/UnifiedPushNotifications.ts b/src/app/features/settings/notifications/UnifiedPushNotifications.ts index a6ce21c35..e98329f43 100644 --- a/src/app/features/settings/notifications/UnifiedPushNotifications.ts +++ b/src/app/features/settings/notifications/UnifiedPushNotifications.ts @@ -1,18 +1,4 @@ -import { MatrixClient } from '$types/matrix-sdk'; -import { ClientConfig } from '$hooks/useClientConfig'; -import { - registerForUnifiedPush, - unregisterFromUnifiedPush, - getUnifiedPushDistributors, - saveUnifiedPushDistributor, - getUnifiedPushDistributor, - onUnifiedPushMessage, - onUnifiedPushEndpoint, - sendNotification, - removeActive, - createChannel, - Importance, -} from '@sableclient/tauri-plugin-notifications-api'; +import { IPusherRequest, MatrixClient } from '$types/matrix-sdk'; import type { MessagingStyleMessage, MessagingStylePerson, @@ -21,11 +7,25 @@ import { EventType } from 'matrix-js-sdk/lib/@types/event'; import { resolveNotificationPreviewText } from '$utils/notificationStyle'; import { getMxIdLocalPart } from '$utils/matrix'; import { getStateEvent, getMemberAvatarMxc } from '$utils/room'; +import { createDebugLogger } from '$utils/debugLogger'; import { StateEvent } from '$types/matrix/room'; +import { + getUnifiedPushDistributor, + getUnifiedPushDistributors, + registerUnifiedPushTransport, + saveUnifiedPushDistributor, + type UnifiedPushRegistrationResult, + unregisterUnifiedPushTransport, +} from './UnifiedPushTransport'; +import { createUnifiedPushMessageListener } from './UnifiedPushMessageListener'; +import type { PushTransportConfig } from './NotificationTransport'; +import { getTauriNotificationsApi } from './TauriNotificationsApiClient'; export { getUnifiedPushDistributors, getUnifiedPushDistributor, saveUnifiedPushDistributor }; const UP_PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify'; +export const DEFAULT_UNIFIED_PUSH_APP_ID = 'moe.sable.up'; +const unifiedPushLog = createDebugLogger('unifiedpush'); /** * Probes the UP endpoint for a Matrix-compatible push gateway. @@ -55,32 +55,77 @@ async function discoverGateway(upEndpoint: string, unifiedPushGateway?: string): const UP_REGISTER_TIMEOUT_MS = 30_000; -export async function enableUnifiedPush( - mx: MatrixClient, - clientConfig: ClientConfig -): Promise<{ endpoint: string; instance: string }> { - await createChannel({ - id: 'messages', - name: 'Messages', - description: 'Matrix message and invite notifications', - importance: Importance.Default, - vibration: true, - }); +export type UnifiedPushTransportConfigInput = Pick< + PushTransportConfig, + 'unifiedPushGatewayUrl' | 'unifiedPushAppID' +>; +type UnifiedPushPusherConfig = { + appId: string; + gatewayUrl?: string; +}; + +function trimConfigValue(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed || undefined; +} + +function resolveUnifiedPushPusherConfig( + config?: UnifiedPushTransportConfigInput +): UnifiedPushPusherConfig { + return { + appId: trimConfigValue(config?.unifiedPushAppID) ?? DEFAULT_UNIFIED_PUSH_APP_ID, + gatewayUrl: trimConfigValue(config?.unifiedPushGatewayUrl), + }; +} + +export type EnableUnifiedPushResult = + | { + status: 'registered'; + endpoint: string; + instance: string; + distributor: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; + } + | Exclude; + +async function registerUnifiedPushWithTimeout(): Promise { const timeout = new Promise((_, reject) => { const id = setTimeout(() => { reject(new Error('UnifiedPush registration timed out')); clearTimeout(id); }, UP_REGISTER_TIMEOUT_MS); }); - const { endpoint, instance, pubKeySet } = await Promise.race([registerForUnifiedPush(), timeout]); - const appId = clientConfig.pushNotificationDetails?.unifiedPushAppID ?? 'moe.sable.up'; + return Promise.race([registerUnifiedPushTransport(), timeout]); +} - // Don't fall back to pushNotifyUrl (Sygnal) — it cannot forward to UP endpoints. - const unifiedPushGateway = clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl; +export async function tryEnableUnifiedPush( + mx: MatrixClient, + config?: UnifiedPushTransportConfigInput +): Promise { + const notificationsApi = await getTauriNotificationsApi(); - const gatewayUrl = await discoverGateway(endpoint, unifiedPushGateway); + await notificationsApi.createChannel({ + id: 'messages', + name: 'Messages', + description: 'Matrix message and invite notifications', + importance: notificationsApi.Importance.Default, + vibration: true, + }); + + const registration = await registerUnifiedPushWithTimeout(); + + if (registration.status !== 'registered') { + return registration; + } + + const { endpoint, instance, pubKeySet } = registration; + const resolvedConfig = resolveUnifiedPushPusherConfig(config); + const gatewayUrl = await discoverGateway(endpoint, resolvedConfig.gatewayUrl); const pusherData: Record = { url: gatewayUrl, @@ -94,7 +139,7 @@ export async function enableUnifiedPush( await mx.setPusher({ kind: 'http', - app_id: appId, + app_id: resolvedConfig.appId, pushkey: endpoint, app_display_name: 'Sable (UnifiedPush)', device_display_name: @@ -104,25 +149,102 @@ export async function enableUnifiedPush( append: false, } as any); - return { endpoint, instance }; + return { + status: 'registered', + endpoint, + instance, + distributor: registration.distributor, + pubKeySet, + }; } +export async function enableUnifiedPush( + mx: MatrixClient, + config?: UnifiedPushTransportConfigInput +): Promise<{ endpoint: string; instance: string }> { + const result = await tryEnableUnifiedPush(mx, config); + if (result.status !== 'registered') { + throw new Error(result.error ?? 'UnifiedPush registration failed'); + } + + return { + endpoint: result.endpoint, + instance: result.instance, + }; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0; +} + +async function getCurrentDeviceUnifiedPushPushkeys( + mx: MatrixClient, + appId: string +): Promise { + const deviceId = mx.getDeviceId() ?? ''; + if (!deviceId) { + return []; + } + + const currentDevice = await mx.getDevice(deviceId); + const deviceDisplayName = currentDevice?.display_name; + if (!deviceDisplayName) { + return []; + } + + const response = await mx.getPushers(); + const pushers = response.pushers ?? []; + return pushers + .filter( + (pusher) => + pusher.app_id === appId && + pusher.device_display_name === deviceDisplayName && + pusher.kind === 'http' && + isNonEmptyString(pusher.pushkey) + ) + .map((pusher) => pusher.pushkey); +} + +async function getUnifiedPushCleanupPushkeys( + mx: MatrixClient, + appId: string, + pushkey?: string +): Promise { + const pushkeys = new Set(); + + if (isNonEmptyString(pushkey)) { + pushkeys.add(pushkey); + } + + const currentDevicePushkeys = await getCurrentDeviceUnifiedPushPushkeys(mx, appId); + currentDevicePushkeys.forEach((candidate) => pushkeys.add(candidate)); + + return Array.from(pushkeys); +} + +export type DisableUnifiedPushOptions = { + config?: UnifiedPushTransportConfigInput; + pushkey?: string; +}; + export async function disableUnifiedPush( mx: MatrixClient, - clientConfig: ClientConfig, - pushkey?: string + options: DisableUnifiedPushOptions = {} ): Promise { - const appId = clientConfig.pushNotificationDetails?.unifiedPushAppID ?? 'moe.sable.up'; + const { appId } = resolveUnifiedPushPusherConfig(options.config); + const pushkeys = await getUnifiedPushCleanupPushkeys(mx, appId, options.pushkey); - if (pushkey) { - await mx.setPusher({ - kind: null, - app_id: appId, - pushkey, - } as any); - } + await Promise.allSettled( + pushkeys.map((pushkey) => + mx.setPusher({ + kind: null, + app_id: appId, + pushkey, + } as unknown as IPusherRequest) + ) + ); - await unregisterFromUnifiedPush(); + await unregisterUnifiedPushTransport(); } type NotificationSettings = { @@ -190,13 +312,15 @@ function getOrCreateRoomCache(roomId: string, roomName: string): RoomNotifCache export async function clearRoomNotification(roomId: string) { roomNotifCaches.delete(roomId); try { - await removeActive([{ id: roomNotifId(roomId) }]); + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.removeActive([{ id: roomNotifId(roomId) }]); } catch { // already dismissed } if (roomNotifCaches.size <= 1) { try { - await removeActive([{ id: SUMMARY_NOTIF_ID }]); + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.removeActive([{ id: SUMMARY_NOTIF_ID }]); } catch { // ignore } @@ -212,11 +336,12 @@ async function postRoomNotification( extra: Record, authToken?: string | null ) { + const notificationsApi = await getTauriNotificationsApi(); const { messages, roomName, isGroupConversation } = cache; const latestMsg = messages[messages.length - 1]; const latestBody = latestMsg ? `${latestMsg.sender?.name ?? 'You'}: ${latestMsg.text}` : ''; - await sendNotification({ + await notificationsApi.sendNotification({ id: roomNotifId(roomId), title: roomName, body: latestBody, @@ -253,7 +378,7 @@ async function postRoomNotification( inboxLines.push(`${c.roomName}: ${latest.sender?.name ?? 'You'}: ${latest.text}`); } }); - await sendNotification({ + await notificationsApi.sendNotification({ id: SUMMARY_NOTIF_ID, title: summaryText, body: '', @@ -305,7 +430,8 @@ async function handleRichPushPayload( }; if (!roomId) { - await sendNotification({ + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.sendNotification({ title: roomName, body: senderName ? `${senderName}: ${previewText}` : previewText, channelId: 'messages', @@ -370,7 +496,8 @@ async function handleRichPushPayload( else if (senderName) body = `from ${senderName}`; else if (roomName) body = `to ${roomName}`; - await sendNotification({ + const notificationsApi = await getTauriNotificationsApi(); + await notificationsApi.sendNotification({ title: 'New Invitation', body, channelId: 'messages', @@ -515,15 +642,28 @@ async function handleUnifiedPushPayload( } export function listenForUnifiedPushMessages(getSettings: () => NotificationSettings) { - return onUnifiedPushMessage((data: Record) => { - handleUnifiedPushPayload(data, getSettings); - }); + return getTauriNotificationsApi().then((notificationsApi) => + notificationsApi.onUnifiedPushMessage( + createUnifiedPushMessageListener( + (data) => handleUnifiedPushPayload(data, getSettings), + (error) => { + unifiedPushLog.error( + 'notification', + 'UnifiedPush payload handling failed', + error instanceof Error ? error : new Error(String(error)) + ); + } + ) + ) + ); } export function listenForUnifiedPushEndpointChanges( onEndpointChanged: (endpoint: string, instance: string) => void ) { - return onUnifiedPushEndpoint(({ endpoint, instance }) => { - onEndpointChanged(endpoint, instance); - }); + return getTauriNotificationsApi().then((notificationsApi) => + notificationsApi.onUnifiedPushEndpoint(({ endpoint, instance }) => { + onEndpointChanged(endpoint, instance); + }) + ); } diff --git a/src/app/features/settings/notifications/UnifiedPushTransport.test.ts b/src/app/features/settings/notifications/UnifiedPushTransport.test.ts new file mode 100644 index 000000000..76a8b3bee --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushTransport.test.ts @@ -0,0 +1,240 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + classifyUnifiedPushFailure, + ensureUnifiedPushDistributorSelection, + loadUnifiedPushDistributorState, + registerUnifiedPushTransport, + switchUnifiedPushDistributorSelection, + setUnifiedPushDistributorSelection, +} from './UnifiedPushTransport'; + +const unifiedPushApi = vi.hoisted(() => ({ + isPermissionGranted: vi.fn(), + requestPermission: vi.fn(), + registerForUnifiedPush: vi.fn(), + unregisterFromUnifiedPush: vi.fn(), + getUnifiedPushDistributors: vi.fn(), + getUnifiedPushDistributor: vi.fn(), + saveUnifiedPushDistributor: vi.fn(), +})); + +vi.mock('./UnifiedPushTransportApiClient', () => ({ + getUnifiedPushTransportApi: vi.fn().mockResolvedValue(unifiedPushApi), +})); + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe('classifyUnifiedPushFailure', () => { + it('treats temporary unavailability as a distinct failure', () => { + expect( + classifyUnifiedPushFailure(new Error('UnifiedPush registration temporarily unavailable')) + ).toBe('temp-unavailable'); + }); + + it('treats missing distributors as a distinct failure', () => { + expect(classifyUnifiedPushFailure(new Error('No UnifiedPush distributor installed'))).toBe( + 'missing-distributor' + ); + }); +}); + +describe('registerUnifiedPushTransport', () => { + it('requests permission before registering and saves the only available distributor', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(false); + unifiedPushApi.requestPermission.mockResolvedValue('granted'); + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: '' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.unifiedpush.distributor.ntfy'], + }); + unifiedPushApi.registerForUnifiedPush.mockResolvedValue({ + endpoint: 'https://up.example/endpoint', + instance: 'instance-1', + }); + + await expect(registerUnifiedPushTransport()).resolves.toEqual({ + status: 'registered', + permissionState: 'granted', + endpoint: 'https://up.example/endpoint', + instance: 'instance-1', + distributor: 'org.unifiedpush.distributor.ntfy', + }); + expect(unifiedPushApi.requestPermission).toHaveBeenCalledOnce(); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledOnce(); + expect(unifiedPushApi.registerForUnifiedPush).toHaveBeenCalledOnce(); + }); + + it('returns denied without registering when permission is denied', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(false); + unifiedPushApi.requestPermission.mockResolvedValue('denied'); + + await expect(registerUnifiedPushTransport()).resolves.toEqual({ + status: 'denied', + permissionState: 'denied', + error: 'UnifiedPush permission denied', + }); + expect(unifiedPushApi.registerForUnifiedPush).not.toHaveBeenCalled(); + }); + + it('returns missing-distributor without registering when none are available', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(true); + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: '' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ distributors: [] }); + + await expect(registerUnifiedPushTransport()).resolves.toEqual({ + status: 'missing-distributor', + permissionState: 'granted', + distributors: [], + error: 'No UnifiedPush distributor installed', + }); + expect(unifiedPushApi.registerForUnifiedPush).not.toHaveBeenCalled(); + }); + + it('classifies temporary-unavailable registration failures distinctly', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(true); + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: 'org.example.up' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.example.up'], + }); + unifiedPushApi.registerForUnifiedPush.mockRejectedValue( + new Error('UnifiedPush registration temporarily unavailable') + ); + + await expect(registerUnifiedPushTransport()).resolves.toEqual({ + status: 'temp-unavailable', + permissionState: 'granted', + distributor: 'org.example.up', + error: 'UnifiedPush registration temporarily unavailable', + }); + }); + + it('treats missing endpoint data as a hard failure', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(true); + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: 'org.example.up' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.example.up'], + }); + unifiedPushApi.registerForUnifiedPush.mockResolvedValue({ + endpoint: '', + instance: 'instance-1', + }); + + await expect(registerUnifiedPushTransport()).resolves.toMatchObject({ + status: 'hard-failure', + error: 'UnifiedPush registration returned an invalid endpoint', + distributor: 'org.example.up', + }); + }); + + it('treats missing instance data as a hard failure', async () => { + unifiedPushApi.isPermissionGranted.mockResolvedValue(true); + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: 'org.example.up' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.example.up'], + }); + unifiedPushApi.registerForUnifiedPush.mockResolvedValue({ + endpoint: 'https://up.example/endpoint', + instance: '', + }); + + await expect(registerUnifiedPushTransport()).resolves.toMatchObject({ + status: 'hard-failure', + error: 'UnifiedPush registration returned an invalid instance', + distributor: 'org.example.up', + }); + }); +}); + +describe('UnifiedPush distributor state helpers', () => { + it('loads distributor state and auto-saves the sole available distributor', async () => { + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ distributor: '' }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.unifiedpush.distributor.ntfy'], + }); + + await expect(loadUnifiedPushDistributorState()).resolves.toEqual({ + distributors: ['org.unifiedpush.distributor.ntfy'], + selectedDistributor: 'org.unifiedpush.distributor.ntfy', + }); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledOnce(); + }); + + it('drops a stale saved distributor that is no longer installed', async () => { + unifiedPushApi.getUnifiedPushDistributor.mockResolvedValue({ + distributor: 'org.unifiedpush.distributor.removed', + }); + unifiedPushApi.getUnifiedPushDistributors.mockResolvedValue({ + distributors: ['org.unifiedpush.distributor.ntfy'], + }); + + await expect(loadUnifiedPushDistributorState()).resolves.toEqual({ + distributors: ['org.unifiedpush.distributor.ntfy'], + selectedDistributor: 'org.unifiedpush.distributor.ntfy', + }); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledWith( + 'org.unifiedpush.distributor.ntfy' + ); + }); + + it('ensures a distributor selection by auto-saving the first available distributor', async () => { + await expect( + ensureUnifiedPushDistributorSelection( + ['org.unifiedpush.distributor.ntfy', 'org.unifiedpush.distributor.nextpush'], + '' + ) + ).resolves.toBe('org.unifiedpush.distributor.ntfy'); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledOnce(); + }); + + it('replaces a stale selected distributor with the first available one', async () => { + await expect( + ensureUnifiedPushDistributorSelection( + ['org.unifiedpush.distributor.ntfy', 'org.unifiedpush.distributor.nextpush'], + 'org.unifiedpush.distributor.removed' + ) + ).resolves.toBe('org.unifiedpush.distributor.ntfy'); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledWith( + 'org.unifiedpush.distributor.ntfy' + ); + }); + + it('persists a selected distributor through the transport helper', async () => { + await expect( + setUnifiedPushDistributorSelection('org.unifiedpush.distributor.nextpush') + ).resolves.toBeUndefined(); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenCalledWith( + 'org.unifiedpush.distributor.nextpush' + ); + }); + + it('surfaces backend errors while loading distributor state', async () => { + unifiedPushApi.getUnifiedPushDistributor.mockRejectedValue(new Error('backend unavailable')); + unifiedPushApi.getUnifiedPushDistributors.mockRejectedValue(new Error('backend unavailable')); + + await expect(loadUnifiedPushDistributorState()).rejects.toThrow('backend unavailable'); + }); + + it('restores the previous distributor when a switch registration fails', async () => { + unifiedPushApi.saveUnifiedPushDistributor.mockResolvedValue(undefined); + const register = vi.fn().mockRejectedValue(new Error('registration failed')); + + await expect( + switchUnifiedPushDistributorSelection( + 'org.unifiedpush.distributor.ntfy', + 'org.unifiedpush.distributor.nextpush', + register + ) + ).rejects.toThrow('registration failed'); + + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenNthCalledWith( + 1, + 'org.unifiedpush.distributor.ntfy' + ); + expect(unifiedPushApi.saveUnifiedPushDistributor).toHaveBeenNthCalledWith( + 2, + 'org.unifiedpush.distributor.nextpush' + ); + expect(register).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/app/features/settings/notifications/UnifiedPushTransport.ts b/src/app/features/settings/notifications/UnifiedPushTransport.ts new file mode 100644 index 000000000..68253eb71 --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushTransport.ts @@ -0,0 +1,312 @@ +import { getUnifiedPushTransportApi } from './UnifiedPushTransportApiClient'; + +export type UnifiedPushPermissionState = 'granted' | 'denied' | 'default'; + +export type UnifiedPushRegistrationStatus = + | 'registered' + | 'temp-unavailable' + | 'hard-failure' + | 'denied' + | 'missing-distributor'; + +export type UnifiedPushDistributorState = { + distributors: string[]; + selectedDistributor: string; +}; + +export type UnifiedPushRegistrationResult = + | { + status: 'registered'; + permissionState: 'granted'; + endpoint: string; + instance: string; + distributor: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; + } + | { + status: 'temp-unavailable'; + permissionState: UnifiedPushPermissionState; + distributor?: string; + error: string; + instance?: string; + } + | { + status: 'hard-failure'; + permissionState: UnifiedPushPermissionState; + distributor?: string; + error: string; + instance?: string; + } + | { + status: 'missing-distributor'; + permissionState: UnifiedPushPermissionState; + distributors: string[]; + error: string; + distributor?: string; + } + | { + status: 'denied'; + permissionState: Exclude; + error: string; + }; + +type UnifiedPushEndpointResponse = { + endpoint: string; + instance: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; +}; + +type UnifiedPushDistributorsResponse = { + distributors: string[]; +}; + +type UnifiedPushDistributorResponse = { + distributor: string; +}; + +type UnifiedPushSwitchRegistration = { + endpoint: string; + instance: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; +}; + +function normalizeErrorMessage(error: unknown): string { + if (error instanceof Error) return error.message; + if (typeof error === 'string') return error; + if (error && typeof error === 'object') { + const message = 'message' in error ? (error as { message?: unknown }).message : undefined; + if (typeof message === 'string') return message; + const code = 'code' in error ? (error as { code?: unknown }).code : undefined; + if (typeof code === 'string') return code; + } + return String(error); +} + +function normalizeErrorCode(error: unknown): string { + if (!error || typeof error !== 'object') return ''; + if ('code' in error && typeof (error as { code?: unknown }).code === 'string') { + return String((error as { code?: string }).code).toLowerCase(); + } + if ('name' in error && typeof (error as { name?: unknown }).name === 'string') { + return String((error as { name?: string }).name).toLowerCase(); + } + return ''; +} + +export function classifyUnifiedPushFailure( + error: unknown +): Exclude { + const message = normalizeErrorMessage(error).toLowerCase(); + const code = normalizeErrorCode(error); + + if ( + code.includes('temp_unavailable') || + code.includes('temporary_unavailable') || + message.includes('temp-unavailable') || + message.includes('temp unavailable') || + message.includes('temporarily unavailable') + ) { + return 'temp-unavailable'; + } + + if ( + code.includes('missing_distributor') || + message.includes('missing distributor') || + message.includes('no unifiedpush distributor') || + message.includes('no distributor') || + message.includes('distributor parameter is required') + ) { + return 'missing-distributor'; + } + + return 'hard-failure'; +} + +async function getUnifiedPushPermissionState(): Promise { + const api = await getUnifiedPushTransportApi(); + if (await api.isPermissionGranted()) return 'granted'; + + const permission = await api.requestPermission(); + return permission === 'granted' ? 'granted' : permission; +} + +export async function getUnifiedPushDistributors(): Promise { + const api = await getUnifiedPushTransportApi(); + return api.getUnifiedPushDistributors(); +} + +export async function getUnifiedPushDistributor(): Promise { + const api = await getUnifiedPushTransportApi(); + return api.getUnifiedPushDistributor(); +} + +export async function saveUnifiedPushDistributor(distributor: string): Promise { + const api = await getUnifiedPushTransportApi(); + await api.saveUnifiedPushDistributor(distributor); +} + +export async function loadUnifiedPushDistributorState(): Promise { + const [{ distributor: savedDistributor }, { distributors }] = await Promise.all([ + getUnifiedPushDistributor(), + getUnifiedPushDistributors(), + ]); + + if (savedDistributor && distributors.includes(savedDistributor)) { + return { distributors, selectedDistributor: savedDistributor }; + } + + if (distributors.length === 1) { + const [onlyDistributor] = distributors; + if (onlyDistributor) { + await saveUnifiedPushDistributor(onlyDistributor); + return { distributors, selectedDistributor: onlyDistributor }; + } + } + + return { distributors, selectedDistributor: '' }; +} + +export async function ensureUnifiedPushDistributorSelection( + distributors: string[], + selectedDistributor: string +): Promise { + if (selectedDistributor && distributors.includes(selectedDistributor)) { + return selectedDistributor; + } + + const [firstDistributor] = distributors; + if (!firstDistributor) return ''; + + await saveUnifiedPushDistributor(firstDistributor); + return firstDistributor; +} + +export async function setUnifiedPushDistributorSelection(distributor: string): Promise { + await saveUnifiedPushDistributor(distributor); +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.trim().length > 0; +} + +function validateUnifiedPushRegistrationResponse( + response: Partial +): { ok: true; value: UnifiedPushSwitchRegistration } | { ok: false; error: string } { + if (!isNonEmptyString(response.endpoint)) { + return { ok: false, error: 'UnifiedPush registration returned an invalid endpoint' }; + } + + if (!isNonEmptyString(response.instance)) { + return { ok: false, error: 'UnifiedPush registration returned an invalid instance' }; + } + + return { + ok: true, + value: { + endpoint: response.endpoint, + instance: response.instance, + pubKeySet: response.pubKeySet, + }, + }; +} + +export async function switchUnifiedPushDistributorSelection( + nextDistributor: string, + previousDistributor: string, + register: () => Promise +): Promise { + if (nextDistributor === previousDistributor) { + return register(); + } + + await saveUnifiedPushDistributor(nextDistributor); + + try { + return await register(); + } catch (error) { + await saveUnifiedPushDistributor(previousDistributor); + throw error; + } +} + +export async function registerUnifiedPushTransport(): Promise { + let permissionState: UnifiedPushPermissionState = 'default'; + let selectedDistributor: string | undefined; + + try { + permissionState = await getUnifiedPushPermissionState(); + if (permissionState !== 'granted') { + return { + status: 'denied', + permissionState, + error: + permissionState === 'denied' + ? 'UnifiedPush permission denied' + : 'UnifiedPush permission dismissed', + }; + } + + const { distributors, selectedDistributor: distributor } = + await loadUnifiedPushDistributorState(); + selectedDistributor = distributor || undefined; + if (!distributor) { + return { + status: 'missing-distributor', + permissionState: 'granted', + distributors, + error: + distributors.length === 0 + ? 'No UnifiedPush distributor installed' + : 'No UnifiedPush distributor selected', + }; + } + + const api = await getUnifiedPushTransportApi(); + const response = (await api.registerForUnifiedPush()) as Partial; + const validated = validateUnifiedPushRegistrationResponse(response); + if (!validated.ok) { + return { + status: 'hard-failure', + permissionState: 'granted', + error: validated.error, + ...(selectedDistributor ? { distributor: selectedDistributor } : {}), + }; + } + + return { + status: 'registered', + permissionState: 'granted', + endpoint: validated.value.endpoint, + instance: validated.value.instance, + distributor, + pubKeySet: validated.value.pubKeySet, + }; + } catch (error) { + const failureStatus = classifyUnifiedPushFailure(error); + return { + status: failureStatus, + permissionState, + error: normalizeErrorMessage(error), + ...(selectedDistributor ? { distributor: selectedDistributor } : {}), + ...(error && typeof error === 'object' && 'instance' in error + ? { + instance: String((error as { instance?: unknown }).instance ?? ''), + } + : {}), + } as UnifiedPushRegistrationResult; + } +} + +export async function unregisterUnifiedPushTransport(): Promise { + const api = await getUnifiedPushTransportApi(); + await api.unregisterFromUnifiedPush(); +} diff --git a/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts new file mode 100644 index 000000000..192279e31 --- /dev/null +++ b/src/app/features/settings/notifications/UnifiedPushTransportApiClient.ts @@ -0,0 +1,29 @@ +export type UnifiedPushTransportApi = { + isPermissionGranted: () => Promise; + requestPermission: () => Promise; + registerForUnifiedPush: () => Promise<{ + endpoint: string; + instance: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; + }>; + unregisterFromUnifiedPush: () => Promise; + getUnifiedPushDistributors: () => Promise<{ distributors: string[] }>; + getUnifiedPushDistributor: () => Promise<{ distributor: string }>; + saveUnifiedPushDistributor: (distributor: string) => Promise; +}; + +export async function getUnifiedPushTransportApi(): Promise { + const api = await import('@sableclient/tauri-plugin-notifications-api'); + return { + isPermissionGranted: api.isPermissionGranted, + requestPermission: api.requestPermission, + registerForUnifiedPush: api.registerForUnifiedPush, + unregisterFromUnifiedPush: api.unregisterFromUnifiedPush, + getUnifiedPushDistributors: api.getUnifiedPushDistributors, + getUnifiedPushDistributor: api.getUnifiedPushDistributor, + saveUnifiedPushDistributor: api.saveUnifiedPushDistributor, + }; +} diff --git a/src/app/hooks/useClientConfig.ts b/src/app/hooks/useClientConfig.ts index 3563b1518..5105b4729 100644 --- a/src/app/hooks/useClientConfig.ts +++ b/src/app/hooks/useClientConfig.ts @@ -1,4 +1,5 @@ import { createContext, useContext } from 'react'; +import type { PushTransportConfig } from '$features/settings/notifications/NotificationTransport'; export type HashRouterConfig = { enabled?: boolean; @@ -18,10 +19,13 @@ export type ClientConfig = { pushNotifyUrl?: string; vapidPublicKey?: string; webPushAppID?: string; + nativePushAppID?: string; unifiedPushAppID?: string; unifiedPushGatewayUrl?: string; }; + pushTransport?: PushTransportConfig; + slidingSync?: { enabled?: boolean; proxyBaseUrl?: string; diff --git a/src/app/pages/client/ClientNonUIFeatures.tsx b/src/app/pages/client/ClientNonUIFeatures.tsx index 7664ffd39..5d963688a 100644 --- a/src/app/pages/client/ClientNonUIFeatures.tsx +++ b/src/app/pages/client/ClientNonUIFeatures.tsx @@ -53,13 +53,24 @@ import { NotificationBanner } from '$components/notification-banner'; import { TelemetryConsentBanner } from '$components/telemetry-consent'; import { useCallSignaling } from '$hooks/useCallSignaling'; import { isTauri } from '@tauri-apps/api/core'; +import { type as osType } from '@tauri-apps/plugin-os'; import { getBlobCacheStats } from '$hooks/useBlobCache'; import { lastVisitedRoomIdAtom } from '$state/room/lastRoom'; import { useSettingsSyncEffect } from '$hooks/useSettingsSync'; import { getInboxInvitesPath } from '../pathUtils'; import { BackgroundNotifications } from './BackgroundNotifications'; +import { + NotificationTransportRuntime, + type NotificationTransportRuntimeContext, +} from '../../features/settings/notifications/NotificationTransportRuntime'; +import { + normalizeNotificationTransportMode, + resolvePreferredNotificationTransportProvider, + type NotificationTransportPlatform, +} from '../../features/settings/notifications/NotificationTransport'; const pushRelayLog = createDebugLogger('push-relay'); +const transportLog = createDebugLogger('push-transport'); function clearMediaSessionQuickly(): void { if (!('mediaSession' in navigator)) return; @@ -837,9 +848,20 @@ function PresenceFeature() { return null; } -function UnifiedPushManager() { +function getNotificationTransportRuntimePlatform(): NotificationTransportPlatform { + if (!isTauri()) return 'web'; + + const platform = osType(); + if (platform === 'android') return 'android'; + if (platform === 'ios') return 'ios'; + return 'desktop'; +} + +function NotificationTransportRuntimeFeature() { const mx = useMatrixClient(); - const [useUP] = useSetting(settingsAtom, 'useUnifiedPush'); + const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled'); + const [backgroundPushProvider] = useSetting(settingsAtom, 'backgroundPushProvider'); + const [pushTransportMode] = useSetting(settingsAtom, 'pushTransportMode'); const [isNotificationSounds] = useSetting(settingsAtom, 'isNotificationSounds'); const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications'); const [showEncryptedMessageContent] = useSetting( @@ -848,35 +870,57 @@ function UnifiedPushManager() { ); const [useInAppNotifications] = useSetting(settingsAtom, 'useInAppNotifications'); - useEffect(() => { - if (!isTauri() || !useUP) return undefined; - - let cleanup: (() => void) | undefined; - - (async () => { - const { listenForUnifiedPushMessages } = - await import('$features/settings/notifications/UnifiedPushNotifications'); - const listener = await listenForUnifiedPushMessages(() => ({ - mx, - showMessageContent, - showEncryptedMessageContent, - notificationSoundEnabled: isNotificationSounds, - useInAppNotifications, - })); - cleanup = () => listener.unregister(); - })(); - - return () => { - cleanup?.(); - }; - }, [ + const runtimeRef = useRef(null); + const contextRef = useRef({ mx, - useUP, - isNotificationSounds, showMessageContent, showEncryptedMessageContent, + notificationSoundEnabled: isNotificationSounds, useInAppNotifications, - ]); + }); + contextRef.current = { + mx, + showMessageContent, + showEncryptedMessageContent, + notificationSoundEnabled: isNotificationSounds, + useInAppNotifications, + }; + + if (!runtimeRef.current) { + runtimeRef.current = new NotificationTransportRuntime(); + } + + useEffect(() => { + if (!isTauri()) return undefined; + + const runtimePlatform = getNotificationTransportRuntimePlatform(); + const normalizedMode = normalizeNotificationTransportMode(pushTransportMode, runtimePlatform); + const provider = backgroundPushEnabled + ? (backgroundPushProvider ?? + resolvePreferredNotificationTransportProvider(normalizedMode, runtimePlatform)) + : null; + const runtime = runtimeRef.current; + if (!runtime) return undefined; + + const syncPromise = runtime.sync(provider, () => contextRef.current); + syncPromise.catch((error) => { + transportLog.error( + 'notification', + 'Notification transport runtime failed', + error instanceof Error ? error : new Error(String(error)) + ); + }); + return () => { + const cleanupPromise = runtime.dispose(); + cleanupPromise.catch((error) => { + transportLog.error( + 'notification', + 'Notification transport runtime cleanup failed', + error instanceof Error ? error : new Error(String(error)) + ); + }); + }; + }, [backgroundPushEnabled, backgroundPushProvider, pushTransportMode]); return null; } @@ -899,7 +943,7 @@ export function ClientNonUIFeatures({ children }: ClientNonUIFeaturesProps) { - + diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index e501aeffd..d5a405e1c 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -1,5 +1,10 @@ import { atom } from 'jotai'; import { mobileOrTablet } from '$utils/user-agent'; +import type { + NotificationTransportMode, + NotificationTransportProvider, + PushTransportOverrides, +} from '$features/settings/notifications/NotificationTransport'; const STORAGE_KEY = 'settings'; export type DateFormat = 'D MMM YYYY' | 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD' | ''; @@ -63,6 +68,10 @@ export interface Settings { showMessageContentInNotifications: boolean; showMessageContentInEncryptedNotifications: boolean; clearNotificationsOnRead: boolean; + backgroundPushEnabled: boolean; + backgroundPushProvider: NotificationTransportProvider | null; + pushTransportMode: NotificationTransportMode; + pushTransportOverride: PushTransportOverrides; hour24Clock: boolean; dateFormatString: string; @@ -160,6 +169,10 @@ const defaultSettings: Settings = { showMessageContentInNotifications: false, showMessageContentInEncryptedNotifications: false, clearNotificationsOnRead: false, + backgroundPushEnabled: mobileOrTablet(), + backgroundPushProvider: null, + pushTransportMode: 'auto', + pushTransportOverride: {}, hour24Clock: false, dateFormatString: 'D MMM YYYY', diff --git a/src/app/state/unifiedPushEndpoint.ts b/src/app/state/unifiedPushEndpoint.ts index 5defe38be..7e25eb947 100644 --- a/src/app/state/unifiedPushEndpoint.ts +++ b/src/app/state/unifiedPushEndpoint.ts @@ -1,4 +1,5 @@ import { atom } from 'jotai'; +import type { UnifiedPushRegistrationStatus } from '$features/settings/notifications/UnifiedPushTransport'; import { atomWithLocalStorage, getLocalStorageItem, @@ -7,9 +8,20 @@ import { const UP_ENDPOINT_KEY = 'unifiedPushEndpoint'; -type UnifiedPushState = { - endpoint: string; - instance: string; +export type UnifiedPushState = { + endpoint?: string; + instance?: string; + appId?: string; + gatewayUrl?: string; + status?: UnifiedPushRegistrationStatus; + distributor?: string; + error?: string; + permissionState?: 'granted' | 'denied' | 'default'; + distributors?: string[]; + pubKeySet?: { + pubKey: string; + auth: string; + }; } | null; const baseAtom = atomWithLocalStorage( diff --git a/src/app/utils/settingsSync.test.ts b/src/app/utils/settingsSync.test.ts index 66c4f5274..bcc048a98 100644 --- a/src/app/utils/settingsSync.test.ts +++ b/src/app/utils/settingsSync.test.ts @@ -24,6 +24,8 @@ describe('NON_SYNCABLE_KEYS', () => { it('contains all device-local and security-sensitive keys', () => { const expected = [ 'usePushNotifications', + 'backgroundPushEnabled', + 'backgroundPushProvider', 'useInAppNotifications', 'useSystemNotifications', 'pageZoom', @@ -127,15 +129,26 @@ describe('deserializeFromSync', () => { v: SETTINGS_SYNC_VERSION, settings: { pageZoom: 200, + backgroundPushEnabled: false, + backgroundPushProvider: 'native', isPeopleDrawer: false, settingsSyncEnabled: true, developerTools: true, }, }; - const local = { ...base, pageZoom: 100, isPeopleDrawer: true, settingsSyncEnabled: false }; + const local = { + ...base, + pageZoom: 100, + backgroundPushEnabled: true, + backgroundPushProvider: 'unifiedpush' as const, + isPeopleDrawer: true, + settingsSyncEnabled: false, + }; const result = deserializeFromSync(remote, local); expect(result).not.toBeNull(); expect(result!.pageZoom).toBe(100); + expect(result!.backgroundPushEnabled).toBe(true); + expect(result!.backgroundPushProvider).toBe('unifiedpush'); expect(result!.isPeopleDrawer).toBe(true); expect(result!.settingsSyncEnabled).toBe(false); expect(result!.developerTools).toBe(false); diff --git a/src/app/utils/settingsSync.ts b/src/app/utils/settingsSync.ts index a154ff92d..0ae8035e4 100644 --- a/src/app/utils/settingsSync.ts +++ b/src/app/utils/settingsSync.ts @@ -7,6 +7,8 @@ import { Settings } from '$state/settings'; export const NON_SYNCABLE_KEYS = new Set([ // Platform / permission-level — differ per device/browser 'usePushNotifications', + 'backgroundPushEnabled', + 'backgroundPushProvider', 'useInAppNotifications', 'useSystemNotifications', // Personal device-level preferences diff --git a/src/types/tauri-plugin-notifications-api.d.ts b/src/types/tauri-plugin-notifications-api.d.ts new file mode 100644 index 000000000..8b7b67365 --- /dev/null +++ b/src/types/tauri-plugin-notifications-api.d.ts @@ -0,0 +1,56 @@ +declare module '@sableclient/tauri-plugin-notifications-api' { + export const Importance: { + readonly Default: string; + }; + + export type MessagingStylePerson = { + name: string; + key?: string; + iconUrl?: string; + }; + + export type MessagingStyleMessage = { + text: string; + timestamp: number; + sender?: MessagingStylePerson; + }; + + export function isPermissionGranted(): Promise; + export function requestPermission(): Promise; + export function registerForPushNotifications(): Promise; + export function unregisterForPushNotifications(): Promise; + + export function registerForUnifiedPush(): Promise<{ + endpoint: string; + instance: string; + pubKeySet?: { + pubKey: string; + auth: string; + }; + }>; + export function unregisterFromUnifiedPush(): Promise; + export function getUnifiedPushDistributors(): Promise<{ distributors: string[] }>; + export function getUnifiedPushDistributor(): Promise<{ distributor: string }>; + export function saveUnifiedPushDistributor(distributor: string): Promise; + + export function createChannel(channel: { + id: string; + name: string; + description?: string; + importance?: string; + vibration?: boolean; + }): Promise; + + export function sendNotification(payload: Record): Promise; + export function removeActive(payload: Array<{ id: number }>): Promise; + + export function onUnifiedPushMessage(listener: (payload: Record) => void): { + unregister: () => Promise | void; + }; + + export function onUnifiedPushEndpoint( + listener: (payload: { endpoint: string; instance: string }) => void + ): { + unregister: () => Promise | void; + }; +}