Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -91,12 +91,12 @@ windows = { version = "0.61", features = [
tauri-plugin-single-instance = { version = "2.4.3", features = ["deep-link"] }

[target.'cfg(any(windows, target_os = "linux"))'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620" }
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51" }

# default-features = false drops notify-rust so macOS uses the native
# UNUserNotificationCenter backend (needs a signed .app to deliver).
[target.'cfg(target_os = "macos")'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", default-features = false }
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", default-features = false }

[target.'cfg(not(any(target_os = "android", target_os = "ios")))'.dependencies]
tauri-plugin-updater = { version = "2", optional = true }
Expand All @@ -119,7 +119,7 @@ cef = { version = "=150.2.1", optional = true }
libloading = "0.8"

[target.'cfg(any(target_os = "android", target_os = "ios"))'.dependencies]
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "0175b5ec58a31ab15397e981a67f47fa32254620", features = [
tauri-plugin-notifications = { git = "https://github.com/SableClient/tauri-plugin-notifications.git", rev = "057d323862d815a0c7459a1f1acd5a3c08750a51", features = [
"push-notifications",
] }
tauri-plugin-edge-to-edge = { git = "https://github.com/SableClient/tauri-plugin-edge-to-edge.git", rev = "33c6116c27be28c06df5a9d02231ecc5fdeb93c5" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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>;
Expand Down
218 changes: 110 additions & 108 deletions src/app/features/settings/notifications/UnifiedPushNotifications.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
}));

Expand Down Expand Up @@ -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',
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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());
Expand All @@ -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 {
Expand Down Expand Up @@ -386,129 +470,47 @@ describe('UnifiedPushNotifications', () => {
);
});

it('serializes cross-room summary writes and refreshes from current caches', async () => {
it('posts one notification per room and no account-level summary', async () => {
matrixClient.getRoom.mockReturnValue(makeRoom());
const summaryPosts: Record<string, unknown>[] = [];
let releaseFirstSummary!: () => void;
const firstSummary = new Promise<void>((resolve) => {
releaseFirstSummary = resolve;
});
notificationsApi.sendNotification.mockImplementation(async (notification) => {
if (notification.groupSummary) {
summaryPosts.push(notification);
if (summaryPosts.length === 1) await firstSummary;
}
});

await listenForUnifiedPushMessages(() => makeSettings() as never);
const roomPayload = (roomId: string, eventId: string, roomName: string) => ({
...encryptedPush(eventId),
room_id: roomId,
room_name: roomName,
});
pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a', 'Room A')) });
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());
pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B')) });
await vi.waitFor(() => expect(summaryPosts).toHaveLength(1));

pushHandler({ message: JSON.stringify(roomPayload('!room-c:example.com', '$c', 'Room C')) });
releaseFirstSummary();
await vi.waitFor(() => expect(summaryPosts).toHaveLength(2));

expect(summaryPosts[0]).toMatchObject({ title: '2 messages in 2 chats' });
expect(summaryPosts[1]).toMatchObject({ title: '3 messages in 3 chats' });
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledTimes(2));
const posted = notificationsApi.sendNotification.mock.calls.map(
([notification]) => notification
);
expect(posted.some((notification) => notification.groupSummary)).toBe(false);
expect(new Set(posted.map((notification) => notification.title))).toEqual(
new Set(['Room A', 'Room B'])
);
expect(new Set(posted.map((notification) => notification.id)).size).toBe(2);
});

it('compensates a summary that observed a baseline pending for another room', async () => {
matrixClient.getRoom.mockReturnValue(makeRoom());
let rejectFailedPost!: (error: Error) => void;
let failedPostStarted!: () => void;
const failedPost = new Promise<never>((_, reject) => {
rejectFailedPost = reject;
});
const failedPostStartedPromise = new Promise<void>((resolve) => {
failedPostStarted = resolve;
});
const summaryPosts: Record<string, unknown>[] = [];
notificationsApi.sendNotification.mockImplementation(async (notification) => {
const eventId = (notification.extra as Record<string, unknown> | undefined)?.event_id;
if (eventId === '$a-failed') {
failedPostStarted();
await failedPost;
return;
}
if (notification.groupSummary) summaryPosts.push(notification);
});

it('dismisses a group summary left behind by an older version', async () => {
await listenForUnifiedPushMessages(() => makeSettings() as never);
const roomPayload = (
roomId: string,
eventId: string,
roomName: string,
sender_display_name: string
) => ({
...encryptedPush(eventId),
room_id: roomId,
room_name: roomName,
sender_display_name,
});
pushHandler({
message: JSON.stringify(
roomPayload('!room-a:example.com', '$a-old', 'Room A', 'Old message')
),
});
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());

pushHandler({
message: JSON.stringify(
roomPayload('!room-a:example.com', '$a-failed', 'Room A', 'Failed message')
),
});
await failedPostStartedPromise;
pushHandler({
message: JSON.stringify(roomPayload('!room-b:example.com', '$b', 'Room B', 'B message')),
});
await vi.waitFor(() => expect(summaryPosts).toHaveLength(1));

rejectFailedPost(new Error('pending baseline failed'));
await vi.waitFor(() => expect(summaryPosts).toHaveLength(2));

expect(summaryPosts[0]?.inboxLines).toEqual(
expect.arrayContaining(['Room A: Failed message: Encrypted message'])
);
expect(summaryPosts[1]?.inboxLines).toEqual(
expect.arrayContaining(['Room A: Old message: Encrypted message'])
);
expect(summaryPosts[1]?.inboxLines).not.toEqual(
expect.arrayContaining(['Room A: Failed message: Encrypted message'])
);
await vi.waitFor(() => expect(notificationsApi.removeActive).toHaveBeenCalledOnce());
expect(notificationsApi.removeActive.mock.calls[0]?.[0]).toEqual([{ id: expect.any(Number) }]);
});

it('still cleans up the account summary when child removal fails', async () => {
it('clears a room even when dismissing its notification fails', async () => {
matrixClient.getRoom.mockReturnValue(makeRoom());
await listenForUnifiedPushMessages(() => makeSettings() as never);
const roomPayload = (roomId: string, eventId: string) => ({
...encryptedPush(eventId),
room_id: roomId,
});
pushHandler({ message: JSON.stringify(roomPayload('!room-a:example.com', '$a')) });
pushHandler({ message: JSON.stringify(roomPayload('!room-b:example.com', '$b')) });
await vi.waitFor(() =>
expect(
notificationsApi.sendNotification.mock.calls.some(
([notification]) => notification.groupSummary
)
).toBe(true)
);

let removeAttempts = 0;
notificationsApi.removeActive.mockImplementation(async () => {
removeAttempts += 1;
if (removeAttempts === 1) throw new Error('child removal failed');
pushHandler({
message: JSON.stringify({ ...encryptedPush('$a'), room_id: '!room-a:example.com' }),
});
await clearRoomNotification('@user:example.com', '!room-a:example.com');
await vi.waitFor(() => expect(notificationsApi.sendNotification).toHaveBeenCalledOnce());

expect(removeAttempts).toBe(2);
notificationsApi.removeActive.mockRejectedValueOnce(new Error('child removal failed'));
await expect(
clearRoomNotification('@user:example.com', '!room-a:example.com')
).resolves.toBeUndefined();
});

it('checks preview policy again after a minimal event resolves', async () => {
Expand Down
Loading
Loading