feat: unify background push transport

This commit is contained in:
hazre committed 2026-03-27 00:06:37 +01:00
1 parent 647265253c
commit 08e044b1b6
26 files changed
+3500 -343

No files matched your search

@@ -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',
})
);
});
});
@@ -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<boolean> {
const api = await getNativePushNotificationsApi();
return api.isPermissionGranted();
}
export async function requestNativePushPermission(): Promise<NotificationPermission> {
const api = await getNativePushNotificationsApi();
return api.requestPermission();
}
export async function ensureNativePushRegistered(): Promise<NativePushRegistrationResult> {
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<void> {
const api = await getNativePushNotificationsApi();
await api.unregisterForPushNotifications();
}
async function getCurrentNativePushToken(): Promise<string | null> {
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<void> {
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<string> {
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<void> {
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();
}
@@ -0,0 +1,17 @@
export type NativePushNotificationsApi = {
isPermissionGranted: () => Promise<boolean>;
requestPermission: () => Promise<NotificationPermission>;
registerForPushNotifications: () => Promise<string>;
unregisterForPushNotifications: () => Promise<void>;
};
let nativePushNotificationsApiPromise: Promise<NativePushNotificationsApi> | null = null;
export async function getNativePushNotificationsApi(): Promise<NativePushNotificationsApi> {
if (!nativePushNotificationsApiPromise) {
nativePushNotificationsApiPromise =
import('@sableclient/tauri-plugin-notifications-api') as Promise<NativePushNotificationsApi>;
}
return nativePushNotificationsApiPromise;
}
@@ -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',
});
});
});
@@ -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<PushTransportConfig, 'mode'>;
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>
): 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 };
}
@@ -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<string, typeof nativeListener> = {};
const runtime = new NotificationTransportRuntime(listenerFactories);
await runtime.sync('native', () => createContext());
listenerFactories.native = nativeListener;
await runtime.sync('native', () => createContext());
expect(nativeListener).toHaveBeenCalledOnce();
});
});
@@ -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> | void;
};
export type NotificationTransportListenerFactory = (
getContext: () => NotificationTransportRuntimeContext
) => Promise<NotificationTransportListenerHandle>;
export type NotificationTransportListenerFactories = Partial<
Record<NotificationTransportProvider, NotificationTransportListenerFactory>
>;
type NotificationTransportListenerCleanup = () => Promise<void> | 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<void> {
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<void> {
this.#activeGeneration += 1;
const cleanup = this.#cleanup;
this.#cleanup = null;
this.#activeProvider = null;
if (!cleanup) return;
await Promise.resolve(cleanup()).catch(() => undefined);
}
}
@@ -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) {
<PageContent>
<Box direction="Column" gap="700">
<SystemNotification />
{isTauri() && <UnifiedPushNotificationSetting />}
<AllMessagesNotifications />
<SpecialMessagesNotifications />
<KeywordMessagesNotifications />
@@ -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<string, ReturnType<typeof vi.fn>>();
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<typeof import('folds')>('folds');
return {
...actual,
Switch: ({
value,
onChange,
disabled,
}: {
value: boolean;
onChange: (nextValue: boolean) => void;
disabled?: boolean;
}) => (
<button
type="button"
role="switch"
aria-label="mock-switch"
aria-checked={value}
disabled={disabled}
onClick={() => onChange(!value)}
/>
),
};
});
vi.mock('@tauri-apps/api/core', () => ({
isTauri: mockIsTauri,
}));
vi.mock('@tauri-apps/plugin-os', () => ({
type: mockOsType,
}));
vi.mock('jotai', () => ({
useAtom: (atom: unknown) => {
if (atom === mockPushSubscriptionAtom) return mockPushSubscriptionTuple;
if (atom === mockUnifiedPushEndpointAtom) return mockUnifiedPushEndpointTuple;
return [null, vi.fn()];
},
}));
vi.mock('$state/hooks/settings', () => ({
useSetting: mockUseSetting,
}));
vi.mock('$state/settings', () => ({
settingsAtom: {},
}));
vi.mock('$state/pushSubscription', () => ({
pushSubscriptionAtom: mockPushSubscriptionAtom,
}));
vi.mock('$state/unifiedPushEndpoint', () => ({
unifiedPushEndpointAtom: mockUnifiedPushEndpointAtom,
}));
vi.mock('$hooks/useEmailNotifications', () => ({
useEmailNotifications: () => [{ email: '[email protected]', enabled: false }, vi.fn()],
}));
vi.mock('$hooks/useMatrixClient', () => ({
useMatrixClient: () => ({
setPusher: vi.fn(),
getUserId: vi.fn(() => '@user:example.org'),
getDeviceId: vi.fn(() => 'DEVICE'),
getDevice: vi.fn().mockResolvedValue({ display_name: 'Device' }),
getPushers: vi.fn().mockResolvedValue({ pushers: [] }),
baseUrl: 'https://matrix.example',
getAccessToken: vi.fn(() => 'token'),
}),
}));
vi.mock('$hooks/useClientConfig', () => ({
useClientConfig: () => ({
pushNotificationDetails: {
unifiedPushGatewayUrl: 'https://default.example/up',
unifiedPushAppID: 'moe.sable.up',
webPushAppID: 'web-app',
nativePushAppID: 'moe.sable.mobile',
pushNotifyUrl: 'https://push.example/notify',
vapidPublicKey: 'PUBLIC_KEY',
},
pushTransport: {
unifiedPushGatewayUrl: 'https://default.example/up',
unifiedPushAppID: 'moe.sable.up',
},
}),
}));
vi.mock('$hooks/usePermission', () => ({
getNotificationState: () => 'granted',
usePermissionState: () => 'granted',
}));
vi.mock('$utils/user-agent', () => ({
mobileOrTablet: mockMobileOrTablet,
}));
vi.mock('./PushNotifications', () => ({
requestBrowserNotificationPermission: mockRequestBrowserNotificationPermission,
enablePushNotifications: mockEnablePushNotifications,
disablePushNotifications: mockDisablePushNotifications,
}));
vi.mock('./UnifiedPushNotifications', () => ({
enableUnifiedPush: mockEnableUnifiedPush,
tryEnableUnifiedPush: mockTryEnableUnifiedPush,
disableUnifiedPush: mockDisableUnifiedPush,
}));
vi.mock('./NotificationTransport', () => ({
enableNativePush: mockEnsureNativePushRegistered,
disableNativePush: mockEnsureNativePushUnregistered,
deriveLegacyPushFlags: (enabled: boolean, provider: string | null) => ({
usePushNotifications: enabled && provider === 'web',
useUnifiedPush: enabled && provider === 'unifiedpush',
}),
getSupportedNotificationTransportModes: (platform: string) => {
if (platform === 'android') return ['auto', 'unifiedpush', 'native'];
if (platform === 'ios') return ['auto', 'native'];
if (platform === 'web') return ['auto', 'web'];
return [];
},
mergePushConfig: (defaults: Record<string, unknown>, overrides: Record<string, unknown>) => ({
...defaults,
...overrides,
}),
normalizeNotificationTransportMode: (mode: string, platform: string) => {
if (platform === 'android')
return ['auto', 'unifiedpush', 'native'].includes(mode) ? mode : 'auto';
if (platform === 'ios') return ['auto', 'native'].includes(mode) ? mode : 'auto';
if (platform === 'web') return ['auto', 'web'].includes(mode) ? mode : 'auto';
return 'auto';
},
resolvePreferredNotificationTransportProvider: (mode: string, platform: string) => {
if (platform === 'desktop') return null;
if (mode === 'web') return 'web';
if (mode === 'native') return 'native';
if (mode === 'unifiedpush') return 'unifiedpush';
if (platform === 'web') return 'web';
if (platform === 'android') return 'unifiedpush';
if (platform === 'ios') return 'native';
return null;
},
}));
vi.mock('./UnifiedPushTransport', () => ({
loadUnifiedPushDistributorState: mockLoadUnifiedPushDistributorState,
ensureUnifiedPushDistributorSelection: mockEnsureUnifiedPushDistributorSelection,
switchUnifiedPushDistributorSelection: mockSwitchUnifiedPushDistributorSelection,
setUnifiedPushDistributorSelection: mockSetUnifiedPushDistributorSelection,
}));
vi.mock('./DeregisterPushNotifications', () => ({
DeregisterAllPushersSetting: () => <div data-testid="deregister-all-pushers" />,
}));
function renderSystemNotification() {
render(<SystemNotification />);
}
describe('SystemNotification background push surface', () => {
beforeEach(() => {
vi.clearAllMocks();
Object.assign(settings, {
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',
pushTransportOverride: {},
usePushNotifications: false,
useUnifiedPush: false,
});
mockIsTauri.mockReturnValue(true);
mockOsType.mockReturnValue('android');
mockMobileOrTablet.mockReturnValue(true);
mockRequestBrowserNotificationPermission.mockResolvedValue('granted');
mockEnablePushNotifications.mockResolvedValue(undefined);
mockDisablePushNotifications.mockResolvedValue(undefined);
mockEnableUnifiedPush.mockResolvedValue({
endpoint: 'https://push.example/endpoint',
instance: 'instance',
});
mockTryEnableUnifiedPush.mockResolvedValue({
status: 'registered',
endpoint: 'https://push.example/endpoint',
instance: 'instance',
distributor: 'org.unifiedpush.distributor.ntfy',
});
mockDisableUnifiedPush.mockResolvedValue(undefined);
mockEnsureNativePushRegistered.mockResolvedValue(undefined);
mockEnsureNativePushUnregistered.mockResolvedValue(undefined);
mockLoadUnifiedPushDistributorState.mockResolvedValue({
distributors: ['org.unifiedpush.distributor.ntfy'],
selectedDistributor: 'org.unifiedpush.distributor.ntfy',
});
mockEnsureUnifiedPushDistributorSelection.mockResolvedValue('org.unifiedpush.distributor.ntfy');
mockSwitchUnifiedPushDistributorSelection.mockResolvedValue({
endpoint: 'https://push.example/endpoint',
instance: 'instance',
});
mockSetUnifiedPushDistributorSelection.mockResolvedValue(undefined);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it('keeps iOS auto on the native legacy path without enabling web push', async () => {
mockOsType.mockReturnValue('ios');
renderSystemNotification();
await waitFor(() => {
expect(settings.usePushNotifications).toBe(false);
expect(settings.useUnifiedPush).toBe(false);
});
});
it('keeps Android auto on the UnifiedPush legacy path without enabling web push', async () => {
mockOsType.mockReturnValue('android');
renderSystemNotification();
await waitFor(() => {
expect(settings.usePushNotifications).toBe(false);
expect(settings.useUnifiedPush).toBe(true);
});
});
it('keeps legacy flags disabled when the active provider is native', () => {
expect(
deriveLegacyPushSync({
enabled: true,
provider: 'native',
})
).toEqual({
usePushNotifications: false,
useUnifiedPush: false,
});
});
it('does not churn transports when switching to a mode with the same effective kind', async () => {
expect(shouldRefreshBackgroundPushTransport('unifiedpush', 'unifiedpush')).toBe(false);
expect(shouldRefreshBackgroundPushTransport('native', 'native')).toBe(false);
expect(shouldRefreshBackgroundPushTransport('web', 'native')).toBe(true);
});
it('rolls back the newly activated transport when deactivating the previous one fails', async () => {
const activate = vi.fn().mockResolvedValue('native');
const deactivate = vi
.fn()
.mockRejectedValueOnce(new Error('old transport stuck'))
.mockResolvedValueOnce(undefined);
await expect(
switchBackgroundPushTransport({
previousKind: 'web',
activate,
deactivate,
})
).rejects.toThrow('old transport stuck');
expect(activate).toHaveBeenCalledOnce();
expect(deactivate).toHaveBeenNthCalledWith(1, 'web');
expect(deactivate).toHaveBeenNthCalledWith(2, 'native');
});
it('renders one background push section in the merged settings surface', async () => {
renderSystemNotification();
await waitFor(() => {
expect(screen.getAllByText('Background Push Notifications')).toHaveLength(1);
});
expect(screen.getByText('UnifiedPush Distributor')).toBeInTheDocument();
expect(screen.getByText('UnifiedPush Gateway URL')).toBeInTheDocument();
expect(screen.getByText('UnifiedPush App ID')).toBeInTheDocument();
expect(screen.queryByText('UnifiedPush Notifications')).not.toBeInTheDocument();
});
it('renders inline UnifiedPush override inputs with mobile-friendly labels', async () => {
renderSystemNotification();
await waitFor(() => {
expect(screen.getByRole('textbox', { name: 'UnifiedPush Gateway URL' })).toBeInTheDocument();
});
expect(screen.getByRole('textbox', { name: 'UnifiedPush App ID' })).toBeInTheDocument();
expect(screen.getAllByRole('button', { name: 'Save' })).toHaveLength(2);
});
it('only persists UnifiedPush override changes after pressing Save', async () => {
renderSystemNotification();
const gatewayInput = await screen.findByRole('textbox', { name: 'UnifiedPush Gateway URL' });
fireEvent.change(gatewayInput, { target: { value: 'https://ntfy.example/up' } });
expect(settings.pushTransportOverride).toEqual({
unifiedPushDistributor: 'org.unifiedpush.distributor.ntfy',
});
fireEvent.click(screen.getAllByRole('button', { name: 'Save' })[0]);
expect(settings.pushTransportOverride).toEqual({
unifiedPushDistributor: 'org.unifiedpush.distributor.ntfy',
unifiedPushGatewayUrl: 'https://ntfy.example/up',
});
});
it('renders transport mode and distributor with dropdown triggers', async () => {
renderSystemNotification();
await waitFor(() => {
expect(screen.getByRole('button', { name: 'Auto' })).toBeInTheDocument();
});
expect(screen.getByRole('button', { name: 'ntfy' })).toBeInTheDocument();
expect(screen.queryByText('Always use a UnifiedPush distributor.')).not.toBeInTheDocument();
expect(
screen.queryByText(
'Try UnifiedPush first, then fall back to native push if registration fails.'
)
).not.toBeInTheDocument();
});
it('hides UnifiedPush settings on iOS auto mode', async () => {
mockOsType.mockReturnValue('ios');
renderSystemNotification();
await waitFor(() => {
expect(screen.getAllByText('Background Push Notifications')).toHaveLength(1);
});
expect(screen.queryByText('UnifiedPush Distributor')).not.toBeInTheDocument();
expect(screen.queryByText('UnifiedPush Gateway URL')).not.toBeInTheDocument();
});
it('hides transport mode when the platform only has auto and one concrete transport', async () => {
mockIsTauri.mockReturnValue(false);
renderSystemNotification();
await waitFor(() => {
expect(screen.getAllByText('Background Push Notifications')).toHaveLength(1);
});
expect(screen.queryByText('Transport Mode')).not.toBeInTheDocument();
});
it('marks desktop tauri background push as unavailable', async () => {
mockOsType.mockReturnValue('linux');
mockMobileOrTablet.mockReturnValue(false);
renderSystemNotification();
await waitFor(() => {
expect(
screen.getByText('Background push is not available in the desktop Tauri build yet.')
).toBeInTheDocument();
});
});
});
@@ -1,6 +1,22 @@
/* eslint-disable no-nested-ternary */
import { useCallback, useEffect, useState } from 'react';
import { Box, Text, Switch, Button, color, Spinner, config } from 'folds';
import { type FormEvent, MouseEventHandler, useCallback, useEffect, useRef, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import {
Box,
Button,
color,
config,
Icon,
IconButton,
Icons,
Input,
Menu,
MenuItem,
PopOut,
RectCords,
Spinner,
Switch,
Text,
} from 'folds';
import { IPusherRequest } from '$types/matrix-sdk';
import { useAtom } from 'jotai';
import { SequenceCard } from '$components/sequence-card';
@@ -14,13 +30,106 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { useClientConfig } from '$hooks/useClientConfig';
import { SequenceCardStyle } from '$features/settings/styles.css';
import { pushSubscriptionAtom } from '$state/pushSubscription';
import { unifiedPushEndpointAtom, type UnifiedPushState } from '$state/unifiedPushEndpoint';
import { mobileOrTablet } from '$utils/user-agent';
import { stopPropagation } from '$utils/keyboard';
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import {
requestBrowserNotificationPermission,
enablePushNotifications,
disablePushNotifications,
} from './PushNotifications';
import { DeregisterAllPushersSetting } from './DeregisterPushNotifications';
import {
deriveLegacyPushFlags,
disableNativePush,
enableNativePush,
getSupportedNotificationTransportModes,
mergePushConfig,
normalizeNotificationTransportMode,
type NotificationTransportMode,
type NotificationTransportPlatform,
type NotificationTransportProvider,
type PushTransportOverrides,
resolvePreferredNotificationTransportProvider,
} from './NotificationTransport';
import {
DEFAULT_UNIFIED_PUSH_APP_ID,
disableUnifiedPush,
enableUnifiedPush,
tryEnableUnifiedPush,
type UnifiedPushTransportConfigInput,
} from './UnifiedPushNotifications';
import {
ensureUnifiedPushDistributorSelection,
loadUnifiedPushDistributorState,
setUnifiedPushDistributorSelection,
switchUnifiedPushDistributorSelection,
} from './UnifiedPushTransport';
type BackgroundPushKind = NotificationTransportProvider;
type BackgroundPushPlatform = NotificationTransportPlatform;
function getBackgroundPushPlatform(isTauriRuntime: boolean): BackgroundPushPlatform {
if (!isTauriRuntime) return 'web';
const platform = osType();
if (platform === 'android') return 'android';
if (platform === 'ios') return 'ios';
return 'desktop';
}
export function deriveLegacyPushSync(input: {
enabled: boolean;
provider: BackgroundPushKind | null;
}): {
usePushNotifications: boolean;
useUnifiedPush: boolean;
} {
return deriveLegacyPushFlags(input.enabled, input.provider);
}
export function shouldRefreshBackgroundPushTransport(
previousKind: BackgroundPushKind | null,
nextKind: BackgroundPushKind | null
): boolean {
return previousKind !== nextKind;
}
export async function switchBackgroundPushTransport(params: {
previousKind: BackgroundPushKind | null;
activate: () => Promise<BackgroundPushKind | null>;
deactivate: (kind: BackgroundPushKind | null) => Promise<void>;
}): Promise<BackgroundPushKind | null> {
const { previousKind, activate, deactivate } = params;
const nextKind = await activate();
if (!shouldRefreshBackgroundPushTransport(previousKind, nextKind)) {
return nextKind;
}
try {
await deactivate(previousKind);
} catch (error) {
await deactivate(nextKind).catch(() => undefined);
throw error;
}
return nextKind;
}
function getNativePushConfigError(clientConfig: ReturnType<typeof useClientConfig>): string | null {
if (!clientConfig.pushNotificationDetails?.nativePushAppID) {
return 'Native push requires pushNotificationDetails.nativePushAppID in config.json.';
}
if (!clientConfig.pushNotificationDetails?.pushNotifyUrl) {
return 'Native push requires pushNotificationDetails.pushNotifyUrl in config.json.';
}
return null;
}
function EmailNotification() {
const mx = useMatrixClient();
@@ -95,72 +204,770 @@ function EmailNotification() {
);
}
function WebPushNotificationSetting() {
const mx = useMatrixClient();
const clientConfig = useClientConfig();
const [isLoading, setIsLoading] = useState<boolean>(true);
const [usePushNotifications, setPushNotifications] = useSetting(
settingsAtom,
'usePushNotifications'
);
const pushSubAtom = useAtom(pushSubscriptionAtom);
function labelTransportMode(mode: NotificationTransportMode): string {
switch (mode) {
case 'auto':
return 'Auto';
case 'unifiedpush':
return 'UnifiedPush';
case 'native':
return 'Native';
case 'web':
return 'Web';
default:
return mode;
}
}
const browserPermission = usePermissionState('notifications', getNotificationState());
useEffect(() => {
setIsLoading(false);
}, []);
const handleRequestPermissionAndEnable = async () => {
setIsLoading(true);
try {
const permissionResult = await requestBrowserNotificationPermission();
if (permissionResult === 'granted') {
await enablePushNotifications(mx, clientConfig, pushSubAtom);
setPushNotifications(true);
}
} finally {
setIsLoading(false);
}
function labelTransportKind(kind: BackgroundPushKind): string {
switch (kind) {
case 'web':
return 'Web Push';
case 'native':
return 'Native Push';
case 'unifiedpush':
return 'UnifiedPush';
default:
return kind;
}
}
function cleanPushTransportOverrides(overrides: PushTransportOverrides): PushTransportOverrides {
const next: PushTransportOverrides = {};
if (overrides.unifiedPushGatewayUrl?.trim()) {
next.unifiedPushGatewayUrl = overrides.unifiedPushGatewayUrl.trim();
}
if (overrides.unifiedPushAppID?.trim()) {
next.unifiedPushAppID = overrides.unifiedPushAppID.trim();
}
if (overrides.unifiedPushDistributor?.trim()) {
next.unifiedPushDistributor = overrides.unifiedPushDistributor.trim();
}
return next;
}
type SettingMenuOption<T extends string> = {
value: T;
label: string;
};
function SettingMenuSelector<T extends string>({
value,
options,
onSelect,
disabled,
loading,
}: {
value: T;
options: SettingMenuOption<T>[];
onSelect: (value: T) => void;
disabled?: boolean;
loading?: boolean;
}) {
const [menuCords, setMenuCords] = useState<RectCords>();
const selectedLabel = options.find((option) => option.value === value)?.label ?? value;
const handleMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
setMenuCords(evt.currentTarget.getBoundingClientRect());
};
const handlePushSwitchChange = async (wantsPush: boolean) => {
setIsLoading(true);
try {
if (wantsPush) {
await enablePushNotifications(mx, clientConfig, pushSubAtom);
} else {
await disablePushNotifications(mx, clientConfig, pushSubAtom);
}
setPushNotifications(wantsPush);
} finally {
setIsLoading(false);
}
const handleSelect = (nextValue: T) => {
setMenuCords(undefined);
onSelect(nextValue);
};
return (
<SettingTile
title="Background Push Notifications"
description={
browserPermission === 'denied' ? (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
Permission blocked. Please allow notifications in your browser settings.
</Text>
) : (
'Receive notifications when the app is closed or in the background.'
)
}
after={
isLoading ? (
<Spinner variant="Secondary" />
) : browserPermission === 'prompt' ? (
<Button size="300" radii="300" onClick={handleRequestPermissionAndEnable}>
<Text size="B300">Enable</Text>
<>
<Button
size="300"
variant="Secondary"
outlined
fill="Soft"
radii="300"
after={
loading ? (
<Spinner variant="Secondary" size="300" />
) : (
<Icon size="300" src={Icons.ChevronBottom} />
)
}
onClick={handleMenu}
disabled={disabled || loading}
>
<Text size="T300">{selectedLabel}</Text>
</Button>
<PopOut
anchor={menuCords}
offset={5}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setMenuCords(undefined),
clickOutsideDeactivates: true,
isKeyForward: (evt: KeyboardEvent) =>
evt.key === 'ArrowDown' || evt.key === 'ArrowRight',
isKeyBackward: (evt: KeyboardEvent) =>
evt.key === 'ArrowUp' || evt.key === 'ArrowLeft',
escapeDeactivates: stopPropagation,
}}
>
<Menu>
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
{options.map((option) => (
<MenuItem
key={option.value}
size="300"
variant="Surface"
aria-selected={option.value === value}
radii="300"
onClick={() => handleSelect(option.value)}
>
<Box grow="Yes">
<Text size="T300">{option.label}</Text>
</Box>
</MenuItem>
))}
</Box>
</Menu>
</FocusTrap>
}
/>
</>
);
}
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<HTMLFormElement>) => {
evt.preventDefault();
onSave(draftValue);
};
return (
<SettingTile title={title} description={description}>
<Box direction="Column" grow="Yes" gap="100">
<Box as="form" gap="200" onSubmit={handleSubmit}>
<Box grow="Yes" direction="Column">
<Input
aria-label={title}
name={name}
radii="300"
variant="Secondary"
value={draftValue}
placeholder={placeholder}
onChange={(evt) => setDraftValue(evt.currentTarget.value)}
style={{ paddingRight: config.space.S200 }}
after={
hasChanges && (
<IconButton
size="300"
radii="300"
variant="Secondary"
type="reset"
title={`Reset ${title}`}
onClick={handleReset}
>
<Icon src={Icons.Cross} size="100" />
</IconButton>
)
}
/>
</Box>
<Button
size="400"
variant={hasChanges ? 'Success' : 'Secondary'}
fill={hasChanges ? 'Solid' : 'Soft'}
outlined
radii="300"
disabled={!hasChanges}
type="submit"
>
<Text size="B400">Save</Text>
</Button>
) : browserPermission === 'granted' ? (
<Switch value={usePushNotifications} onChange={handlePushSwitchChange} />
) : null
</Box>
</Box>
</SettingTile>
);
}
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<UnifiedPushState>(upEndpoint);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
const [selectedDistributor, setSelectedDistributor] = useState<string>(
pushTransportOverride.unifiedPushDistributor ?? ''
);
const [availableDistributors, setAvailableDistributors] = useState<string[]>([]);
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<PushTransportOverrides>) => {
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<string> => {
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<BackgroundPushKind> => {
const nativeFallback = async (failureReason: string): Promise<BackgroundPushKind> => {
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<BackgroundPushKind | null> => {
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 (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
{error}
</Text>
);
}
if (!backgroundPushSupported) {
return (
<Text as="span" style={{ color: color.Warning.Main }} size="T200">
Background push is not available in the desktop Tauri build yet.
</Text>
);
}
if (!backgroundPushEnabled) {
return 'Receive notifications when the app is closed or in the background.';
}
if (nativePushConfigError) {
return (
<Text as="span" style={{ color: color.Warning.Main }} size="T200">
{nativePushConfigError}
</Text>
);
}
if (browserPermission === 'denied' && effectiveKind === 'web') {
return (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
Permission blocked. Please allow notifications in your browser settings.
</Text>
);
}
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 <Spinner variant="Secondary" />;
}
if (!backgroundPushSupported) {
return <Switch value={false} disabled />;
}
if (!backgroundPushEnabled && nativePushConfigError) {
return <Switch value={false} disabled />;
}
if (!backgroundPushEnabled && effectiveKind === 'web' && browserPermission === 'prompt') {
return (
<Button size="300" radii="300" onClick={() => handleToggleBackgroundPush(true)}>
<Text size="B300">Enable</Text>
</Button>
);
}
return <Switch value={backgroundPushEnabled} onChange={handleToggleBackgroundPush} />;
};
return (
<>
<SettingTile
title="Background Push Notifications"
description={transportDescription}
after={renderTransportToggle()}
/>
{supportedModes.length > 2 && (
<SettingTile
title="Transport Mode"
description={`Current mode: ${labelTransportMode(
selectedTransportMode
)}${effectiveKind ? ` (${labelTransportKind(effectiveKind)})` : ''}`}
after={
<SettingMenuSelector
value={selectedTransportMode}
options={modeOptions}
onSelect={handleModeChange}
loading={isLoading}
/>
}
/>
)}
{showUnifiedPushSettings && (
<>
<SettingTile
title="UnifiedPush Distributor"
description={selectedDistributor || 'Not selected. Pick a distributor such as ntfy.'}
after={
distributorOptions.length > 0 ? (
<SettingMenuSelector
value={selectedDistributor}
options={distributorOptions}
onSelect={handleDistributorChange}
loading={isLoading}
/>
) : undefined
}
>
{distributorOptions.length === 0 && (
<Text size="T300" priority="300">
No UnifiedPush distributors were detected yet.
</Text>
)}
</SettingTile>
<NotificationTransportOverrideInput
title="UnifiedPush Gateway URL"
description={`Default: ${pushTransportDefaults.unifiedPushGatewayUrl ?? 'none'}`}
name="unifiedPushGatewayUrl"
value={pushTransportOverride.unifiedPushGatewayUrl ?? ''}
placeholder={pushTransportDefaults.unifiedPushGatewayUrl ?? 'https://gateway.example'}
onSave={(nextValue) =>
updatePushTransportOverride({ unifiedPushGatewayUrl: nextValue })
}
/>
<NotificationTransportOverrideInput
title="UnifiedPush App ID"
description={`Default: ${pushTransportDefaults.unifiedPushAppID ?? 'none'}`}
name="unifiedPushAppID"
value={pushTransportOverride.unifiedPushAppID ?? ''}
placeholder={pushTransportDefaults.unifiedPushAppID ?? 'moe.sable.up'}
onSave={(nextValue) => updatePushTransportOverride({ unifiedPushAppID: nextValue })}
/>
</>
)}
</>
);
}
@@ -243,16 +1050,6 @@ export function SystemNotification() {
/>
</SequenceCard>
)}
{mobileOrTablet() && (
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<WebPushNotificationSetting />
</SequenceCard>
)}
{!mobileOrTablet() && (
<SequenceCard
className={SequenceCardStyle}
@@ -267,6 +1064,14 @@ export function SystemNotification() {
/>
</SequenceCard>
)}
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<BackgroundPushNotificationSetting />
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
@@ -0,0 +1,35 @@
export type NotificationPluginListener = {
unregister: () => Promise<void> | void;
};
export type TauriNotificationsApi = {
Importance: {
readonly Default: string;
};
createChannel: (channel: {
id: string;
name: string;
description?: string;
importance?: string;
vibration?: boolean;
}) => Promise<void>;
sendNotification: (payload: Record<string, unknown>) => Promise<void>;
removeActive: (payload: Array<{ id: number; tag?: string }>) => Promise<void>;
onUnifiedPushMessage: (
listener: (payload: Record<string, unknown>) => void
) => Promise<NotificationPluginListener> | NotificationPluginListener;
onUnifiedPushEndpoint: (
listener: (payload: { endpoint: string; instance: string }) => void
) => Promise<NotificationPluginListener> | NotificationPluginListener;
};
let notificationsApiPromise: Promise<TauriNotificationsApi> | null = null;
export async function getTauriNotificationsApi(): Promise<TauriNotificationsApi> {
if (!notificationsApiPromise) {
notificationsApiPromise =
import('@sableclient/tauri-plugin-notifications-api') as Promise<TauriNotificationsApi>;
}
return notificationsApiPromise;
}
@@ -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' }));
});
});
@@ -0,0 +1,11 @@
export type UnifiedPushMessageHandler = (data: Record<string, unknown>) => Promise<void>;
export type UnifiedPushMessageErrorHandler = (error: unknown) => void;
export function createUnifiedPushMessageListener(
handler: UnifiedPushMessageHandler,
onError: UnifiedPushMessageErrorHandler
) {
return (data: Record<string, unknown>) => {
handler(data).catch(onError);
};
}
@@ -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<string | null>(null);
const [distributors, setDistributors] = useState<string[]>([]);
const [currentDistributor, setCurrentDistributor] = useState<string>('');
const [menuCords, setMenuCords] = useState<RectCords>();
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<HTMLButtonElement> = (evt) => {
setMenuCords(evt.currentTarget.getBoundingClientRect());
};
return (
<>
<SettingTile
title="UnifiedPush Notifications"
description={
error ? (
<Text as="span" style={{ color: color.Critical.Main }} size="T200">
{error}
</Text>
) : distributors.length === 0 ? (
<Text as="span" style={{ color: color.Warning.Main }} size="T200">
No UnifiedPush distributor installed. Install one (e.g. ntfy, NextPush) to use this
feature.
</Text>
) : (
'Receive background notifications via UnifiedPush without Google Services.'
)
}
after={
isLoading ? (
<Spinner variant="Secondary" />
) : (
<Switch value={useUP} onChange={handleToggle} disabled={distributors.length === 0} />
)
}
/>
{distributors.length > 1 && (
<SettingTile
title="Distributor"
description={currentDistributor ? distributorLabel(currentDistributor) : 'Not selected'}
after={
<>
<PopOut
anchor={menuCords}
position="Bottom"
align="End"
content={
<FocusTrap
focusTrapOptions={{
initialFocus: false,
onDeactivate: () => setMenuCords(undefined),
clickOutsideDeactivates: true,
escapeDeactivates: stopPropagation,
}}
>
<Menu>
{distributors.map((d) => (
<MenuItem
key={d}
radii="300"
onClick={() => handleSelectDistributor(d)}
aria-pressed={d === currentDistributor}
>
<Text size="B300">{distributorLabel(d)}</Text>
</MenuItem>
))}
</Menu>
</FocusTrap>
}
/>
<Button
size="300"
radii="300"
variant="Secondary"
fill="Soft"
onClick={handleDistributorMenu}
>
<Text size="B300">Change</Text>
</Button>
</>
}
/>
)}
</>
);
}
@@ -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();
});
});
@@ -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<UnifiedPushRegistrationResult, { status: 'registered' }>;
async function registerUnifiedPushWithTimeout(): Promise<UnifiedPushRegistrationResult> {
const timeout = new Promise<never>((_, 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<EnableUnifiedPushResult> {
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<string, string> = {
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<string[]> {
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<string[]> {
const pushkeys = new Set<string>();
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<void> {
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<string, unknown>,
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<string, unknown>) => {
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);
})
);
}
@@ -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();
});
});
@@ -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<UnifiedPushPermissionState, 'granted'>;
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<UnifiedPushRegistrationStatus, 'registered' | 'denied'> {
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<UnifiedPushPermissionState> {
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<UnifiedPushDistributorsResponse> {
const api = await getUnifiedPushTransportApi();
return api.getUnifiedPushDistributors();
}
export async function getUnifiedPushDistributor(): Promise<UnifiedPushDistributorResponse> {
const api = await getUnifiedPushTransportApi();
return api.getUnifiedPushDistributor();
}
export async function saveUnifiedPushDistributor(distributor: string): Promise<void> {
const api = await getUnifiedPushTransportApi();
await api.saveUnifiedPushDistributor(distributor);
}
export async function loadUnifiedPushDistributorState(): Promise<UnifiedPushDistributorState> {
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<string> {
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<void> {
await saveUnifiedPushDistributor(distributor);
}
function isNonEmptyString(value: unknown): value is string {
return typeof value === 'string' && value.trim().length > 0;
}
function validateUnifiedPushRegistrationResponse(
response: Partial<UnifiedPushSwitchRegistration>
): { 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<T>(
nextDistributor: string,
previousDistributor: string,
register: () => Promise<T>
): Promise<T> {
if (nextDistributor === previousDistributor) {
return register();
}
await saveUnifiedPushDistributor(nextDistributor);
try {
return await register();
} catch (error) {
await saveUnifiedPushDistributor(previousDistributor);
throw error;
}
}
export async function registerUnifiedPushTransport(): Promise<UnifiedPushRegistrationResult> {
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<UnifiedPushEndpointResponse>;
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<void> {
const api = await getUnifiedPushTransportApi();
await api.unregisterFromUnifiedPush();
}
@@ -0,0 +1,29 @@
export type UnifiedPushTransportApi = {
isPermissionGranted: () => Promise<boolean>;
requestPermission: () => Promise<NotificationPermission>;
registerForUnifiedPush: () => Promise<{
endpoint: string;
instance: string;
pubKeySet?: {
pubKey: string;
auth: string;
};
}>;
unregisterFromUnifiedPush: () => Promise<void>;
getUnifiedPushDistributors: () => Promise<{ distributors: string[] }>;
getUnifiedPushDistributor: () => Promise<{ distributor: string }>;
saveUnifiedPushDistributor: (distributor: string) => Promise<void>;
};
export async function getUnifiedPushTransportApi(): Promise<UnifiedPushTransportApi> {
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,
};
}
+4
View File
@@ -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;
+72 -28
View File
@@ -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<NotificationTransportRuntime | null>(null);
const contextRef = useRef<NotificationTransportRuntimeContext>({
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) {
<MessageNotifications />
<BackgroundNotifications />
<SyncNotificationSettingsWithServiceWorker />
<UnifiedPushManager />
<NotificationTransportRuntimeFeature />
<HandleDecryptPushEvent />
<NotificationBanner />
<TelemetryConsentBanner />
+13
View File
@@ -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',
+15 -3
View File
@@ -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<UnifiedPushState>(
+14 -1
View File
@@ -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);
+2
View File
@@ -7,6 +7,8 @@ import { Settings } from '$state/settings';
export const NON_SYNCABLE_KEYS = new Set<keyof Settings>([
// Platform / permission-level — differ per device/browser
'usePushNotifications',
'backgroundPushEnabled',
'backgroundPushProvider',
'useInAppNotifications',
'useSystemNotifications',
// Personal device-level preferences
+56
View File
@@ -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<boolean>;
export function requestPermission(): Promise<NotificationPermission>;
export function registerForPushNotifications(): Promise<string>;
export function unregisterForPushNotifications(): Promise<void>;
export function registerForUnifiedPush(): Promise<{
endpoint: string;
instance: string;
pubKeySet?: {
pubKey: string;
auth: string;
};
}>;
export function unregisterFromUnifiedPush(): Promise<void>;
export function getUnifiedPushDistributors(): Promise<{ distributors: string[] }>;
export function getUnifiedPushDistributor(): Promise<{ distributor: string }>;
export function saveUnifiedPushDistributor(distributor: string): Promise<void>;
export function createChannel(channel: {
id: string;
name: string;
description?: string;
importance?: string;
vibration?: boolean;
}): Promise<void>;
export function sendNotification(payload: Record<string, unknown>): Promise<void>;
export function removeActive(payload: Array<{ id: number }>): Promise<void>;
export function onUnifiedPushMessage(listener: (payload: Record<string, unknown>) => void): {
unregister: () => Promise<void> | void;
};
export function onUnifiedPushEndpoint(
listener: (payload: { endpoint: string; instance: string }) => void
): {
unregister: () => Promise<void> | void;
};
}