fix(notifications): unstick encrypted previews and follow Android notification conventions

This commit is contained in:
Erwan Leboucher authored and 7w1 committed 2026-08-06 08:33:55 -05:00
1 parent 8e35f349cc
commit fb3b7b2658
4 files changed
+311 -206

No files matched your search

@@ -20,6 +20,7 @@ export type TauriNotificationsApi = {
importance?: number;
vibration?: boolean;
}) => Promise<void>;
removeChannel: (id: string) => Promise<void>;
isPermissionGranted: () => Promise<boolean>;
requestPermission: () => Promise<NotificationPermission>;
sendNotification: (payload: Record<string, unknown>) => Promise<void>;
@@ -14,8 +14,10 @@ const notificationsApi = vi.hoisted(() => ({
sendNotification: vi.fn<(notification: Record<string, unknown>) => Promise<void>>(),
removeActive: vi.fn<(notifications: Array<{ id: number }>) => Promise<void>>(),
createChannel: vi.fn<() => void>(),
removeChannel: vi.fn<() => Promise<void>>(),
Importance: {
Default: 3,
High: 4,
},
}));
@@ -101,6 +103,7 @@ describe('UnifiedPushNotifications', () => {
notificationsApi.sendNotification.mockResolvedValue(undefined);
notificationsApi.removeActive.mockResolvedValue(undefined);
notificationsApi.createChannel.mockResolvedValue(undefined);
notificationsApi.removeChannel.mockResolvedValue(undefined);
getTauriNotificationsApi.mockResolvedValue(notificationsApi);
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
status: 'registered',
@@ -180,6 +183,55 @@ describe('UnifiedPushNotifications', () => {
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2));
});
it('posts message notifications as a conversation on the high-importance channel', async () => {
matrixClient.getRoom.mockReturnValue(makeRoom());
await listenAndPush({
type: 'm.room.message',
room_id: '!room:example.com',
room_name: 'Room',
event_id: '$plain:example.com',
sender: '@alice:example.com',
sender_display_name: 'Alice',
content: { body: 'hello' },
});
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());
expect(notificationsApi.sendNotification.mock.calls[0]?.[0]).toMatchObject({
channelId: 'messages.v2',
groupConversation: false,
messages: [{ body: 'hello', senderName: 'Alice', senderKey: '@alice:example.com' }],
});
});
it('posts invitations on their own channel', async () => {
await listenAndPush({
type: 'm.room.member',
room_id: '!room:example.com',
room_name: 'Room',
sender_display_name: 'Alice',
content: { membership: 'invite' },
});
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());
expect(notificationsApi.sendNotification.mock.calls[0]?.[0]).toMatchObject({
channelId: 'invites',
title: 'New Invitation',
});
});
it('creates the messages channel at high importance and drops the legacy one', async () => {
await tryEnableUnifiedPush(matrixClient as never);
expect(notificationsApi.createChannel).toHaveBeenCalledWith(
expect.objectContaining({ id: 'messages.v2', importance: 4 })
);
expect(notificationsApi.createChannel).toHaveBeenCalledWith(
expect.objectContaining({ id: 'invites' })
);
expect(notificationsApi.removeChannel).toHaveBeenCalledWith('messages');
});
it('silently updates the same notification after encrypted decryption succeeds', async () => {
matrixClient.getRoom.mockReturnValue(makeRoom());
matrixClient.getCrypto.mockReturnValue({
@@ -232,7 +284,7 @@ describe('UnifiedPushNotifications', () => {
expect(decryptEvent).not.toHaveBeenCalled();
});
it('discards encrypted enrichment that resolves after the observation deadline', async () => {
it('applies encrypted enrichment that only decrypts long after the baseline post', async () => {
vi.useFakeTimers();
try {
matrixClient.getRoom.mockReturnValue(makeRoom());
@@ -244,18 +296,50 @@ describe('UnifiedPushNotifications', () => {
decryptEvent: vi.fn<() => Promise<Record<string, unknown>>>().mockReturnValue(decryption),
});
await listenAndPush(encryptedPush('$deadline:example.com'));
await listenAndPush(encryptedPush('$late:example.com'));
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());
vi.advanceTimersByTime(2_500);
vi.advanceTimersByTime(30_000);
resolveDecryption({
clearEvent: {
type: 'm.room.message',
content: { body: 'late plaintext' },
},
});
await Promise.resolve();
await Promise.resolve();
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2));
expect(notificationsApi.sendNotification.mock.calls[1]?.[0]).toMatchObject({
body: 'You: late plaintext',
silent: true,
});
} finally {
vi.useRealTimers();
}
});
it('stops waiting for the room key once the retry window elapses', async () => {
vi.useFakeTimers();
try {
matrixClient.getRoom.mockReturnValue(makeRoom());
let resolveDecryption!: (content: Record<string, unknown>) => void;
const decryption = new Promise<Record<string, unknown>>((resolve) => {
resolveDecryption = resolve;
});
matrixClient.getCrypto.mockReturnValue({
decryptEvent: vi.fn<() => Promise<Record<string, unknown>>>().mockReturnValue(decryption),
});
await listenAndPush(encryptedPush('$expired:example.com'));
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());
await vi.advanceTimersByTimeAsync(5 * 60_000);
resolveDecryption({
clearEvent: {
type: 'm.room.message',
content: { body: 'far too late' },
},
});
await vi.advanceTimersByTimeAsync(0);
expect(notificationsApi.sendNotification).toHaveBeenCalledOnce();
} finally {
@@ -3,6 +3,7 @@ import {
type IPusherRequest,
type MatrixClient,
MatrixEvent,
MatrixEventEvent,
} from '$types/matrix-sdk';
import { EventType } from 'matrix-js-sdk/lib/@types/event';
import {
@@ -11,7 +12,6 @@ import {
} from '$utils/notificationStyle';
import { getMxIdLocalPart } from '$utils/matrix';
import { getStateEvent } from '$utils/room/hierarchy';
import { getMemberAvatarMxc } from '$utils/room/display';
import { createDebugLogger } from '$utils/debugLogger';
import {
registerUnifiedPushTransport,
@@ -56,6 +56,34 @@ type UnifiedPushPayload = {
const UP_REGISTER_TIMEOUT_MS = 30_000;
// Android freezes a channel's importance at creation, so raising `messages` from
// Default to High needs a new id. Mirrored in the plugin's UnifiedPushNotifier.
const MESSAGES_CHANNEL_ID = 'messages.v2';
const INVITES_CHANNEL_ID = 'invites';
const LEGACY_MESSAGES_CHANNEL_ID = 'messages';
async function ensureNotificationChannels(
notificationsApi: Awaited<ReturnType<typeof getTauriNotificationsApi>>
): Promise<void> {
await notificationsApi.createChannel({
id: MESSAGES_CHANNEL_ID,
name: 'Messages',
description: 'Matrix message notifications',
importance: notificationsApi.Importance.High,
vibration: true,
});
await notificationsApi.createChannel({
id: INVITES_CHANNEL_ID,
name: 'Invitations',
description: 'Room and space invitations',
importance: notificationsApi.Importance.Default,
vibration: true,
});
await notificationsApi.removeChannel(LEGACY_MESSAGES_CHANNEL_ID).catch(() => {
// Never created on this device, or already gone.
});
}
export type UnifiedPushTransportConfigInput = Pick<
PushTransportConfig,
'unifiedPushGatewayUrl' | 'unifiedPushAppID'
@@ -117,14 +145,7 @@ export async function tryEnableUnifiedPush(
config?: UnifiedPushTransportConfigInput
): Promise<EnableUnifiedPushResult> {
const notificationsApi = await getTauriNotificationsApi();
await notificationsApi.createChannel({
id: 'messages',
name: 'Messages',
description: 'Matrix message and invite notifications',
importance: notificationsApi.Importance.Default,
vibration: true,
});
await ensureNotificationChannels(notificationsApi);
const registration = await registerUnifiedPushWithTimeout(config?.vapidPublicKey);
@@ -305,12 +326,11 @@ type NotificationSettings = {
const NOTIF_GROUP_KEY = 'matrix_messages';
const MAX_MESSAGES = 10;
const MAX_SEEN_EVENT_IDS = 200;
const ENCRYPTED_PREVIEW_OBSERVATION_DEADLINE_MS = 2_500;
const ENCRYPTED_PREVIEW_RETRY_WINDOW_MS = 5 * 60_000;
type NotifPerson = {
name: string;
key?: string;
iconUrl?: string;
};
type NotifMessage = {
@@ -351,29 +371,55 @@ async function resolvePreviewEvent(
}
/**
* Decrypts the ciphertext from a rich push payload locally — no homeserver
* fetch needed. The Megolm session keys are in the crypto store. This is
* what makes encrypted notifications as fast as Element.
* Rebuilds the encrypted event from a rich push payload so it can be decrypted
* locally — no homeserver fetch needed, the Megolm keys are in the crypto store.
*/
async function decryptPreviewFromPayload(
mx: MatrixClient,
function buildEncryptedPreviewEvent(
roomId: string,
eventId: string,
pushData: UnifiedPushPayload
): Promise<MatrixEvent | undefined> {
const crypto = mx.getCrypto();
if (!crypto || !pushData.content) return undefined;
const mEvent = new MatrixEvent({
type: EventType.RoomMessageEncrypted,
): MatrixEvent | undefined {
if (!pushData.content) return undefined;
return new MatrixEvent({
type: 'm.room.encrypted',
content: pushData.content,
room_id: roomId,
event_id: eventId,
sender: pushData.sender,
origin_server_ts: Date.now(),
});
await mEvent.attemptDecryption(crypto as CryptoBackend);
if (mEvent.isDecryptionFailure()) throw new Error('Encrypted preview decryption failed');
return mEvent;
}
function holdsPlaintext(event: MatrixEvent): boolean {
return (
!event.isDecryptionFailure() && event.getType() !== EventType.RoomMessageEncrypted.toString()
);
}
/**
* Runs `apply` as soon as `event` holds plaintext: right away when it is already
* decrypted, or later once the Megolm key arrives — a backgrounded app routinely
* receives the push before the to-device key, and the SDK retries decryption on
* its own when the key lands.
*/
function whenDecrypted(event: MatrixEvent, apply: () => Promise<void>): void {
if (holdsPlaintext(event)) {
void apply();
return;
}
const onDecrypted = () => {
if (!holdsPlaintext(event)) return;
event.off(MatrixEventEvent.Decrypted, onDecrypted);
clearTimeout(retryWindowTimer);
void apply();
};
event.on(MatrixEventEvent.Decrypted, onDecrypted);
const retryWindowTimer = setTimeout(() => {
event.off(MatrixEventEvent.Decrypted, onDecrypted);
unifiedPushLog.warn('notification', 'Encrypted preview never decrypted within retry window');
}, ENCRYPTED_PREVIEW_RETRY_WINDOW_MS);
}
const roomNotifId = (userId: string, roomId: string) => hashCode(`${userId}\u0000${roomId}`);
@@ -425,14 +471,6 @@ function enqueueAccountSummaryOperation<T>(
return task;
}
function resolveAvatarUrl(mx: MatrixClient, roomId: string, userId: string): string | undefined {
const room = mx.getRoom(roomId);
if (!room) return undefined;
const mxcUrl = getMemberAvatarMxc(room, userId);
if (!mxcUrl) return undefined;
return mx.mxcUrlToHttp(mxcUrl, 96, 96, 'crop', false, true, true) ?? undefined;
}
function getOrCreateRoomCache(userId: string, roomId: string, roomName: string): RoomNotifCache {
const key = `${userId}\u0000${roomId}`;
let cache = roomNotifCaches.get(key);
@@ -517,7 +555,7 @@ async function refreshAccountSummary(
body: '',
summary: summaryText,
inboxLines: summaryLines.slice(-5),
channelId: 'messages',
channelId: MESSAGES_CHANNEL_ID,
group: NOTIF_GROUP_KEY,
groupSummary: true,
icon: 'notification_icon',
@@ -566,13 +604,21 @@ async function postRoomNotification(
id: roomNotifId(userId, roomId),
title: roomName,
body: latestBody,
channelId: 'messages',
channelId: MESSAGES_CHANNEL_ID,
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
extra,
...(isMobileTauri() ? { actionTypeId: 'sable-message' } : {}),
// Android renders these as a conversation; inbox/big-text covers the rest.
messages: messages.map((m) => ({
body: m.text,
timestamp: m.timestamp,
senderName: m.sender?.name,
senderKey: m.sender?.key,
})),
groupConversation: cache.isGroupConversation,
inboxLines: inboxLines.length > 1 ? inboxLines : undefined,
largeBody: inboxLines.length > 1 ? undefined : latestBody,
});
@@ -615,7 +661,7 @@ async function handleRichPushPayload(
await notificationsApi.sendNotification({
title: roomName,
body: senderName ? `${senderName}: ${previewText}` : previewText,
channelId: 'messages',
channelId: MESSAGES_CHANNEL_ID,
icon: 'notification_icon',
silent: isSilent,
autoCancel: true,
@@ -655,11 +701,7 @@ async function handleRichPushPayload(
}
const sender: NotifPerson | undefined = senderName
? {
name: senderName,
key: senderId,
iconUrl: senderId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
}
? { name: senderName, key: senderId }
: undefined;
const message: NotifMessage = {
@@ -749,7 +791,7 @@ async function handleRichPushPayload(
title: 'New Invitation',
body,
largeBody: body,
channelId: 'messages',
channelId: INVITES_CHANNEL_ID,
group: NOTIF_GROUP_KEY,
icon: 'notification_icon',
autoCancel: true,
@@ -779,102 +821,80 @@ function scheduleEncryptedPreviewEnrichment(
const initialSettings = getSettings();
if (!initialSettings.showMessageContent || !initialSettings.showEncryptedMessageContent) return;
let settled = false;
let deadlineExpired = false;
const deadlineTimer = setTimeout(() => {
if (!settled) {
deadlineExpired = true;
unifiedPushLog.warn(
'notification',
'Encrypted preview decryption exceeded observation deadline'
);
}
}, ENCRYPTED_PREVIEW_OBSERVATION_DEADLINE_MS);
const crypto = initialSettings.mx.getCrypto();
const decrypted = buildEncryptedPreviewEvent(roomId, eventId, pushData);
if (!crypto || !decrypted) return;
const enrichment = decryptPreviewFromPayload(initialSettings.mx, roomId, eventId, pushData);
void enrichment
.then(async (decrypted) => {
if (deadlineExpired || !decrypted) return;
const applyDecryptedPreview = async (): Promise<void> => {
await enqueueRoomOperation(cache.key, async () => {
const liveSettings = getSettings();
const isAllowed =
liveSettings.showMessageContent &&
liveSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && liveSettings.useInAppNotifications);
if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) {
return;
}
await enqueueRoomOperation(cache.key, async () => {
const liveSettings = getSettings();
const isAllowed =
liveSettings.showMessageContent &&
liveSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && liveSettings.useInAppNotifications);
if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) {
return;
}
const enrichedPreview = resolveNotificationPreviewText({
content: decrypted.getContent(),
eventType: decrypted.getType(),
isEncryptedRoom: true,
showMessageContent: liveSettings.showMessageContent,
showEncryptedMessageContent: liveSettings.showEncryptedMessageContent,
});
if (!enrichedPreview || enrichedPreview === ENCRYPTED_MESSAGE_PREVIEW) return;
const enrichedPreview = resolveNotificationPreviewText({
content: decrypted.getContent(),
eventType: decrypted.getType(),
isEncryptedRoom: true,
showMessageContent: liveSettings.showMessageContent,
showEncryptedMessageContent: liveSettings.showEncryptedMessageContent,
});
if (!enrichedPreview || enrichedPreview === ENCRYPTED_MESSAGE_PREVIEW) return;
const liveRoom = liveSettings.mx.getRoom(roomId);
const decryptedSender = decrypted.getSender();
const senderName = decryptedSender
? (liveRoom?.getMember(decryptedSender)?.name ??
getMxIdLocalPart(decryptedSender) ??
decryptedSender)
: undefined;
const previousText = message.text;
const previousSender = message.sender;
message.text = enrichedPreview;
message.sender = senderName ? { name: senderName, key: decryptedSender } : message.sender;
const liveRoom = liveSettings.mx.getRoom(roomId);
const decryptedSender = decrypted.getSender();
const senderName = decryptedSender
? (liveRoom?.getMember(decryptedSender)?.name ??
getMxIdLocalPart(decryptedSender) ??
decryptedSender)
: undefined;
const previousText = message.text;
const previousSender = message.sender;
message.text = enrichedPreview;
message.sender = senderName
? {
name: senderName,
key: decryptedSender,
iconUrl: decryptedSender
? resolveAvatarUrl(liveSettings.mx, roomId, decryptedSender)
: undefined,
}
: message.sender;
const current = () => {
const currentSettings = getSettings();
return (
isCurrentRoomCache(cache) &&
cache.messages.includes(message) &&
currentSettings.showMessageContent &&
currentSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && currentSettings.useInAppNotifications)
);
};
try {
const posted = await postRoomNotification(
userId,
roomId,
cache,
true,
{
room_id: roomId,
event_id: eventId,
user_id: pushData?.user_id,
},
current
);
if (!posted) {
message.text = previousText;
message.sender = previousSender;
}
} catch {
const current = () => {
const currentSettings = getSettings();
return (
isCurrentRoomCache(cache) &&
cache.messages.includes(message) &&
currentSettings.showMessageContent &&
currentSettings.showEncryptedMessageContent &&
!(document.visibilityState === 'visible' && currentSettings.useInAppNotifications)
);
};
try {
const posted = await postRoomNotification(
userId,
roomId,
cache,
true,
{
room_id: roomId,
event_id: eventId,
user_id: pushData?.user_id,
},
current
);
if (!posted) {
message.text = previousText;
message.sender = previousSender;
}
});
})
.catch(() => {
unifiedPushLog.warn('notification', 'Encrypted preview decryption failed');
})
.finally(() => {
settled = true;
clearTimeout(deadlineTimer);
} catch {
message.text = previousText;
message.sender = previousSender;
}
});
};
whenDecrypted(decrypted, applyDecryptedPreview);
void decrypted.attemptDecryption(crypto as CryptoBackend).catch(() => {
unifiedPushLog.warn('notification', 'Encrypted preview decryption failed');
});
}
/**
@@ -934,11 +954,7 @@ async function handleMinimalPushPayload(
}
const sender: NotifPerson | undefined = senderName
? {
name: senderName,
key: senderId,
iconUrl: senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
}
? { name: senderName, key: senderId }
: undefined;
const message: NotifMessage = {
@@ -999,81 +1015,76 @@ async function handleMinimalPushPayload(
(!isEncryptedRoom || settings.showEncryptedMessageContent)
) {
resolvePreviewEvent(settings.mx, roomId, eventId)
.then(async (fetched) => {
.then((fetched) => {
if (!fetched) return;
await enqueueRoomOperation(cache.key, async () => {
const liveSettings = getSettings();
const eventEncrypted = isEncryptedRoom || fetched.isEncrypted();
const isAllowed =
liveSettings.showMessageContent &&
(!eventEncrypted || liveSettings.showEncryptedMessageContent) &&
!(document.visibilityState === 'visible' && liveSettings.useInAppNotifications);
if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) {
return;
}
const applyFetchedPreview = () =>
enqueueRoomOperation(cache.key, async () => {
const liveSettings = getSettings();
const eventEncrypted = isEncryptedRoom || fetched.isEncrypted();
const isAllowed =
liveSettings.showMessageContent &&
(!eventEncrypted || liveSettings.showEncryptedMessageContent) &&
!(document.visibilityState === 'visible' && liveSettings.useInAppNotifications);
if (!isAllowed || !isCurrentRoomCache(cache) || !cache.messages.includes(message)) {
return;
}
const enrichedPreview = resolveNotificationPreviewText({
content: fetched.getContent(),
eventType: fetched.getType(),
isEncryptedRoom: eventEncrypted,
showMessageContent: liveSettings.showMessageContent,
showEncryptedMessageContent: liveSettings.showEncryptedMessageContent,
});
if (!enrichedPreview) return;
const enrichedPreview = resolveNotificationPreviewText({
content: fetched.getContent(),
eventType: fetched.getType(),
isEncryptedRoom: eventEncrypted,
showMessageContent: liveSettings.showMessageContent,
showEncryptedMessageContent: liveSettings.showEncryptedMessageContent,
});
if (!enrichedPreview) return;
const fetchedSender = fetched.getSender();
const liveRoom = liveSettings.mx.getRoom(roomId);
const nextSenderName = fetchedSender
? (liveRoom?.getMember(fetchedSender)?.name ??
getMxIdLocalPart(fetchedSender) ??
fetchedSender)
: undefined;
const previousText = message.text;
const previousSender = message.sender;
message.text = enrichedPreview;
message.sender = nextSenderName
? {
name: nextSenderName,
key: fetchedSender,
iconUrl: fetchedSender
? resolveAvatarUrl(liveSettings.mx, roomId, fetchedSender)
: undefined,
const fetchedSender = fetched.getSender();
const liveRoom = liveSettings.mx.getRoom(roomId);
const nextSenderName = fetchedSender
? (liveRoom?.getMember(fetchedSender)?.name ??
getMxIdLocalPart(fetchedSender) ??
fetchedSender)
: undefined;
const previousText = message.text;
const previousSender = message.sender;
message.text = enrichedPreview;
message.sender = nextSenderName ? { name: nextSenderName, key: fetchedSender } : sender;
const current = () => {
const currentSettings = getSettings();
return (
isCurrentRoomCache(cache) &&
cache.messages.includes(message) &&
currentSettings.showMessageContent &&
(!eventEncrypted || currentSettings.showEncryptedMessageContent) &&
!(document.visibilityState === 'visible' && currentSettings.useInAppNotifications)
);
};
try {
const sent = await postRoomNotification(
userId,
roomId,
cache,
true,
{
room_id: roomId,
event_id: eventId,
user_id: pushData?.user_id,
},
current
);
if (!sent) {
message.text = previousText;
message.sender = previousSender;
}
: sender;
const current = () => {
const currentSettings = getSettings();
return (
isCurrentRoomCache(cache) &&
cache.messages.includes(message) &&
currentSettings.showMessageContent &&
(!eventEncrypted || currentSettings.showEncryptedMessageContent) &&
!(document.visibilityState === 'visible' && currentSettings.useInAppNotifications)
);
};
try {
const sent = await postRoomNotification(
userId,
roomId,
cache,
true,
{
room_id: roomId,
event_id: eventId,
user_id: pushData?.user_id,
},
current
);
if (!sent) {
} catch {
message.text = previousText;
message.sender = previousSender;
}
} catch {
message.text = previousText;
message.sender = previousSender;
}
});
});
whenDecrypted(fetched, applyFetchedPreview);
})
.catch((error) => {
unifiedPushLog.warn(
+9
View File
@@ -9,6 +9,13 @@ declare module '@choochmeque/tauri-plugin-notifications-api' {
readonly High: 4;
};
export type NotificationMessage = {
body: string;
timestamp: number;
senderName?: string;
senderKey?: string;
};
export type NotificationOptions = {
id?: number;
channelId?: string;
@@ -22,6 +29,8 @@ declare module '@choochmeque/tauri-plugin-notifications-api' {
groupSummary?: boolean;
sound?: string;
inboxLines?: string[];
messages?: NotificationMessage[];
groupConversation?: boolean;
icon?: string;
largeIcon?: string;
iconColor?: string;