mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-27 12:26:29 -08:00
fix(notifications): route push transports by explicit provider
This commit is contained in:
11 files changed
+290
-57
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Switching to native push notifications now correctly uses the platform's native delivery instead of keeping the old push app.
|
||||
@@ -17,12 +17,16 @@ import {
|
||||
import { menuIcon, X } from '$components/icons/phosphor';
|
||||
import { useAtom } from 'jotai';
|
||||
import { useMatrixClient } from '../../../hooks/useMatrixClient';
|
||||
import { useClientConfig } from '../../../hooks/useClientConfig';
|
||||
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
|
||||
import { useSetting } from '../../../state/hooks/settings';
|
||||
import { settingsAtom } from '../../../state/settings';
|
||||
import { pushSubscriptionAtom } from '../../../state/pushSubscription';
|
||||
import { deRegisterAllPushers } from './PushNotifications';
|
||||
import { disableNativePush } from './NotificationTransport';
|
||||
import { disableUnifiedPush } from './UnifiedPushNotifications';
|
||||
import { SettingTile } from '../../../components/setting-tile';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
|
||||
type ConfirmDeregisterDialogProps = {
|
||||
onClose: () => void;
|
||||
@@ -78,9 +82,15 @@ function ConfirmDeregisterDialog({ onClose, onConfirm, isLoading }: ConfirmDereg
|
||||
|
||||
export function DeregisterAllPushersSetting() {
|
||||
const mx = useMatrixClient();
|
||||
const clientConfig = useClientConfig();
|
||||
const [deregisterState] = useAsyncCallback(deRegisterAllPushers);
|
||||
const [isConfirming, setIsConfirming] = useState(false);
|
||||
const [, setPushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
|
||||
const [backgroundPushEnabled, setBackgroundPushEnabled] = useSetting(
|
||||
settingsAtom,
|
||||
'backgroundPushEnabled'
|
||||
);
|
||||
const [, setBackgroundPushProvider] = useSetting(settingsAtom, 'backgroundPushProvider');
|
||||
|
||||
const [, setPushSubscription] = useAtom(pushSubscriptionAtom);
|
||||
|
||||
@@ -97,6 +107,15 @@ export function DeregisterAllPushersSetting() {
|
||||
await deRegisterAllPushers(mx);
|
||||
setPushNotifications(false);
|
||||
setPushSubscription(null);
|
||||
|
||||
if (isTauri()) {
|
||||
await Promise.allSettled([disableNativePush(mx, clientConfig), disableUnifiedPush(mx)]);
|
||||
}
|
||||
|
||||
if (backgroundPushEnabled) {
|
||||
setBackgroundPushEnabled(false);
|
||||
}
|
||||
setBackgroundPushProvider(null);
|
||||
setIsConfirming(false);
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const invoke = vi.hoisted(() =>
|
||||
vi.fn<(cmd: string, args?: Record<string, unknown>) => Promise<unknown>>()
|
||||
);
|
||||
|
||||
const isAndroidTauri = vi.hoisted(() => vi.fn<() => boolean>());
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke }));
|
||||
vi.mock('./TauriNotificationsApiClient', () => ({ isAndroidTauri }));
|
||||
|
||||
import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient';
|
||||
|
||||
describe('NativePushNotificationsApiClient', () => {
|
||||
it('registers with provider: "fcm" on Android so the plugin bypasses a saved UnifiedPush distributor', async () => {
|
||||
isAndroidTauri.mockReturnValue(true);
|
||||
invoke.mockResolvedValueOnce({
|
||||
deviceToken: 'fcm-token',
|
||||
p256dh: 'p256dh',
|
||||
auth: 'auth',
|
||||
});
|
||||
|
||||
const api = await getNativePushNotificationsApi();
|
||||
await api.registerForPushNotifications('vapid-pub');
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', {
|
||||
vapid: 'vapid-pub',
|
||||
provider: 'fcm',
|
||||
});
|
||||
});
|
||||
|
||||
it('omits the provider arg on iOS (APNs ignores it)', async () => {
|
||||
isAndroidTauri.mockReturnValue(false);
|
||||
invoke.mockResolvedValueOnce({
|
||||
deviceToken: 'apns-token',
|
||||
});
|
||||
|
||||
const api = await getNativePushNotificationsApi();
|
||||
await api.registerForPushNotifications('vapid-pub');
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', {
|
||||
vapid: 'vapid-pub',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { isAndroidTauri } from './TauriNotificationsApiClient';
|
||||
|
||||
export type NativePushRegistration = {
|
||||
deviceToken: string;
|
||||
@@ -24,6 +25,7 @@ export async function getNativePushNotificationsApi(): Promise<NativePushNotific
|
||||
registerForPushNotifications: (vapid?: string) =>
|
||||
invoke<NativePushRegistration>('plugin:notifications|register_for_push_notifications', {
|
||||
vapid,
|
||||
...(isAndroidTauri() ? { provider: 'fcm' } : {}),
|
||||
}),
|
||||
unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const isTauri = vi.hoisted(() => vi.fn<() => boolean>());
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ isTauri }));
|
||||
|
||||
import {
|
||||
enablePushNotifications,
|
||||
disablePushNotifications,
|
||||
togglePusher,
|
||||
} from './PushNotifications';
|
||||
|
||||
const matrixClient = vi.hoisted(() => ({
|
||||
getAccessToken: vi.fn<() => string>(() => 'token'),
|
||||
}));
|
||||
const clientConfig = {} as never;
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('enablePushNotifications', () => {
|
||||
it('no-ops in the Tauri runtime instead of throwing', async () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
enablePushNotifications(matrixClient as never, clientConfig, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('disablePushNotifications', () => {
|
||||
it('no-ops in the Tauri runtime', async () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
disablePushNotifications(matrixClient as never, clientConfig, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('togglePusher', () => {
|
||||
it('does not throw in the Tauri runtime when push is enabled', async () => {
|
||||
isTauri.mockReturnValue(true);
|
||||
|
||||
await expect(
|
||||
togglePusher(matrixClient as never, clientConfig, true, true, [
|
||||
null,
|
||||
vi.fn<(sub: unknown) => void>(),
|
||||
])
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -33,9 +33,7 @@ export async function enablePushNotifications(
|
||||
clientConfig: ClientConfig,
|
||||
pushSubscriptionAtom: PushSubscriptionState
|
||||
): Promise<void> {
|
||||
if (isTauri()) {
|
||||
throw new Error('Push notifications are disabled in Tauri runtime.');
|
||||
}
|
||||
if (isTauri()) return;
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
debugLog.error(
|
||||
'notification',
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { switchBackgroundPushTransport } from './SystemNotification';
|
||||
import type { NotificationTransportProvider } from './NotificationTransport';
|
||||
|
||||
describe('switchBackgroundPushTransport', () => {
|
||||
it('deactivates the previous transport before activating the new one', async () => {
|
||||
const order: string[] = [];
|
||||
const deactivate = vi
|
||||
.fn<(kind: NotificationTransportProvider | null) => Promise<void>>()
|
||||
.mockImplementation(async (kind) => {
|
||||
order.push(`deactivate:${kind}`);
|
||||
});
|
||||
const activate = vi
|
||||
.fn<() => Promise<NotificationTransportProvider | null>>()
|
||||
.mockImplementation(async () => {
|
||||
order.push('activate');
|
||||
return 'native';
|
||||
});
|
||||
|
||||
const nextKind = await switchBackgroundPushTransport({
|
||||
previousKind: 'unifiedpush',
|
||||
activate,
|
||||
deactivate,
|
||||
});
|
||||
|
||||
expect(nextKind).toBe('native');
|
||||
expect(order).toEqual(['deactivate:unifiedpush', 'activate']);
|
||||
});
|
||||
|
||||
it('skips deactivate when there is no previous transport', async () => {
|
||||
const deactivate = vi.fn<(kind: NotificationTransportProvider | null) => Promise<void>>();
|
||||
const activate = vi
|
||||
.fn<() => Promise<NotificationTransportProvider | null>>()
|
||||
.mockResolvedValue('native');
|
||||
|
||||
const nextKind = await switchBackgroundPushTransport({
|
||||
previousKind: null,
|
||||
activate,
|
||||
deactivate,
|
||||
});
|
||||
|
||||
expect(nextKind).toBe('native');
|
||||
expect(deactivate).not.toHaveBeenCalled();
|
||||
expect(activate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('propagates a deactivate failure without activating', async () => {
|
||||
const deactivate = vi
|
||||
.fn<(kind: NotificationTransportProvider | null) => Promise<void>>()
|
||||
.mockRejectedValue(new Error('unregister failed'));
|
||||
const activate = vi.fn<() => Promise<NotificationTransportProvider | null>>();
|
||||
|
||||
await expect(
|
||||
switchBackgroundPushTransport({
|
||||
previousKind: 'unifiedpush',
|
||||
activate,
|
||||
deactivate,
|
||||
})
|
||||
).rejects.toThrow('unregister failed');
|
||||
|
||||
expect(activate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -93,33 +93,18 @@ export function deriveLegacyPushSync(input: {
|
||||
return deriveLegacyPushFlags(input.enabled, input.provider);
|
||||
}
|
||||
|
||||
export function shouldRefreshBackgroundPushTransport(
|
||||
previousKind: BackgroundPushKind | null,
|
||||
nextKind: BackgroundPushKind | null
|
||||
): boolean {
|
||||
return previousKind !== nextKind;
|
||||
}
|
||||
|
||||
export async function switchBackgroundPushTransport(params: {
|
||||
previousKind: BackgroundPushKind | null;
|
||||
activate: () => Promise<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 {
|
||||
if (previousKind) {
|
||||
await deactivate(previousKind);
|
||||
} catch (error) {
|
||||
await deactivate(nextKind).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
|
||||
return nextKind;
|
||||
return activate();
|
||||
}
|
||||
|
||||
function getNativePushConfigError(clientConfig: ReturnType<typeof useClientConfig>): string | null {
|
||||
@@ -699,19 +684,13 @@ function BackgroundPushNotificationSetting() {
|
||||
await disableNativePush(mx, clientConfig);
|
||||
};
|
||||
|
||||
const activateAndroidAutoTransport = async (
|
||||
currentKind: BackgroundPushKind | null
|
||||
): Promise<BackgroundPushKind> => {
|
||||
const activateAndroidAutoTransport = async (): 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';
|
||||
};
|
||||
@@ -752,7 +731,7 @@ function BackgroundPushNotificationSetting() {
|
||||
if (currentKind === 'unifiedpush') {
|
||||
return 'unifiedpush';
|
||||
}
|
||||
return activateAndroidAutoTransport(currentKind);
|
||||
return activateAndroidAutoTransport();
|
||||
}
|
||||
|
||||
if (currentKind === nextPreferredKind) {
|
||||
@@ -793,12 +772,18 @@ function BackgroundPushNotificationSetting() {
|
||||
|
||||
try {
|
||||
if (backgroundPushEnabled) {
|
||||
const nextKind = await switchBackgroundPushTransport({
|
||||
previousKind,
|
||||
activate: () => activateMode(nextMode, previousKind),
|
||||
deactivate: deactivateTransport,
|
||||
});
|
||||
setBackgroundPushProvider(nextKind);
|
||||
const plannedKind = resolvePreferredNotificationTransportProvider(
|
||||
normalizeNotificationTransportMode(nextMode, runtimePlatform),
|
||||
runtimePlatform
|
||||
);
|
||||
if (plannedKind !== previousKind) {
|
||||
const nextKind = await switchBackgroundPushTransport({
|
||||
previousKind,
|
||||
activate: () => activateMode(nextMode, previousKind),
|
||||
deactivate: deactivateTransport,
|
||||
});
|
||||
setBackgroundPushProvider(nextKind);
|
||||
}
|
||||
} else {
|
||||
setBackgroundPushProvider(null);
|
||||
}
|
||||
|
||||
@@ -701,29 +701,7 @@ async function handleMinimalPushPayload(
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!previewText &&
|
||||
eventId &&
|
||||
settings.showMessageContent &&
|
||||
(!isEncryptedRoom || settings.showEncryptedMessageContent)
|
||||
) {
|
||||
const fetched = await resolvePreviewEvent(settings.mx, roomId, eventId);
|
||||
if (fetched) {
|
||||
const sender = fetched.getSender();
|
||||
if (sender) {
|
||||
senderName = room?.getMember(sender)?.name ?? getMxIdLocalPart(sender) ?? sender;
|
||||
senderId = sender;
|
||||
}
|
||||
previewText = resolveNotificationPreviewText({
|
||||
content: fetched.getContent(),
|
||||
eventType: fetched.getType(),
|
||||
isEncryptedRoom,
|
||||
showMessageContent: settings.showMessageContent,
|
||||
showEncryptedMessageContent: settings.showEncryptedMessageContent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const hasInMemoryPreview = Boolean(previewText);
|
||||
if (!previewText) {
|
||||
previewText = isEncryptedRoom ? 'Encrypted message' : 'New message';
|
||||
}
|
||||
@@ -762,6 +740,57 @@ async function handleMinimalPushPayload(
|
||||
event_id: eventId,
|
||||
user_id: pushData?.user_id,
|
||||
});
|
||||
|
||||
if (
|
||||
!hasInMemoryPreview &&
|
||||
eventId &&
|
||||
settings.showMessageContent &&
|
||||
(!isEncryptedRoom || settings.showEncryptedMessageContent)
|
||||
) {
|
||||
resolvePreviewEvent(settings.mx, roomId, eventId)
|
||||
.then((fetched) => {
|
||||
if (!fetched || cache.latestEventId !== eventId) return;
|
||||
const enrichedPreview = resolveNotificationPreviewText({
|
||||
content: fetched.getContent(),
|
||||
eventType: fetched.getType(),
|
||||
isEncryptedRoom,
|
||||
showMessageContent: settings.showMessageContent,
|
||||
showEncryptedMessageContent: settings.showEncryptedMessageContent,
|
||||
});
|
||||
if (!enrichedPreview) return;
|
||||
|
||||
const fetchedSender = fetched.getSender();
|
||||
if (fetchedSender) {
|
||||
senderName =
|
||||
room?.getMember(fetchedSender)?.name ??
|
||||
getMxIdLocalPart(fetchedSender) ??
|
||||
fetchedSender;
|
||||
senderId = fetchedSender;
|
||||
}
|
||||
message.text = enrichedPreview;
|
||||
message.sender = senderName
|
||||
? {
|
||||
name: senderName,
|
||||
key: senderId,
|
||||
iconUrl:
|
||||
senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
|
||||
}
|
||||
: sender;
|
||||
|
||||
void postRoomNotification(userId, roomId, cache, true, {
|
||||
room_id: roomId,
|
||||
event_id: eventId,
|
||||
user_id: pushData?.user_id,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
unifiedPushLog.warn(
|
||||
'notification',
|
||||
'Background preview fetch failed',
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnifiedPushPayload(
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const invoke = vi.hoisted(() =>
|
||||
vi.fn<(cmd: string, args?: Record<string, unknown>) => Promise<unknown>>()
|
||||
);
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({ invoke }));
|
||||
|
||||
import { getUnifiedPushTransportApi } from './UnifiedPushTransportApiClient';
|
||||
|
||||
describe('UnifiedPushTransportApiClient', () => {
|
||||
it('registers with provider: "unifiedpush" so the plugin routes through the distributor explicitly', async () => {
|
||||
invoke.mockResolvedValueOnce({
|
||||
deviceToken: 'up-endpoint',
|
||||
p256dh: 'p256dh',
|
||||
auth: 'auth',
|
||||
});
|
||||
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
await api.registerForPushNotifications('vapid-pub');
|
||||
|
||||
expect(invoke).toHaveBeenCalledWith('plugin:notifications|register_for_push_notifications', {
|
||||
vapid: 'vapid-pub',
|
||||
provider: 'unifiedpush',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -24,6 +24,7 @@ export async function getUnifiedPushTransportApi(): Promise<UnifiedPushTransport
|
||||
registerForPushNotifications: (vapid?: string) =>
|
||||
invoke<UnifiedPushRegistration>('plugin:notifications|register_for_push_notifications', {
|
||||
vapid,
|
||||
provider: 'unifiedpush',
|
||||
}),
|
||||
unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications,
|
||||
listDistributors: notificationsApi.listDistributors,
|
||||
|
||||
Reference in new issue
Block a user