Skip to content

Commit 6e5e986

Browse files
Bil0000maria-rcks
andauthored
feat: badge background thread notifications on desktop and web (pingdotgg#11569)
Co-authored-by: maria-rcks <[email protected]>
1 parent dd6ba84 commit 6e5e986

10 files changed

Lines changed: 587 additions & 4 deletions

‎apps/desktop/src/ipc/DesktopIpcHandlers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Effect from "effect/Effect";
22

33
import * as DesktopIpc from "./DesktopIpc.ts";
4+
import { installNotificationBadge } from "./methods/notificationBadge.ts";
45
import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts";
56
import {
67
clearConnectionCatalog,
@@ -68,6 +69,7 @@ import { getWslState, setWslBackendEnabled, setWslDistro, setWslOnly } from "./m
6869

6970
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
7071
const ipc = yield* DesktopIpc.DesktopIpc;
72+
yield* installNotificationBadge();
7173
yield* PreviewIpc.installPreviewEventForwarding();
7274

7375
yield* ipc.handle(AppActivationIpc.setReady);

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
2+
export const SET_NOTIFICATION_BADGE_CHANNEL = "desktop:set-notification-badge";
23
export const PICK_PROJECT_FAVICON_CHANNEL = "desktop:pick-project-favicon";
34
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
45
export const SET_THEME_CHANNEL = "desktop:set-theme";
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
import * as Effect from "effect/Effect";
2+
import { beforeEach, expect, vi } from "vite-plus/test";
3+
import { it } from "@effect/vitest";
4+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
5+
6+
const native = vi.hoisted(() => ({
7+
setBadgeCount: vi.fn(),
8+
setOverlayIcon: vi.fn(),
9+
isDestroyed: vi.fn(() => false),
10+
getFocusedWindow: vi.fn(() => null as object | null),
11+
image: { isEmpty: vi.fn(() => false) },
12+
createFromDataURL: vi.fn(),
13+
webContents: { send: vi.fn() },
14+
listeners: new Map<string, () => void>(),
15+
}));
16+
vi.mock("electron", () => ({
17+
app: {
18+
setBadgeCount: native.setBadgeCount,
19+
on: (event: string, listener: () => void) => native.listeners.set(event, listener),
20+
removeListener: (event: string) => native.listeners.delete(event),
21+
},
22+
BrowserWindow: {
23+
getFocusedWindow: native.getFocusedWindow,
24+
getAllWindows: () => [native],
25+
},
26+
nativeImage: { createFromDataURL: native.createFromDataURL },
27+
}));
28+
29+
import * as ElectronApp from "../../electron/ElectronApp.ts";
30+
import * as DesktopIpc from "../DesktopIpc.ts";
31+
import { applyNotificationBadge, installNotificationBadge } from "./notificationBadge.ts";
32+
33+
const badge = { count: 2, image: "data:image/png;base64,aGVsbG8=" };
34+
35+
beforeEach(() => {
36+
vi.clearAllMocks();
37+
native.getFocusedWindow.mockReturnValue(null);
38+
native.isDestroyed.mockReturnValue(false);
39+
native.image.isEmpty.mockReturnValue(false);
40+
native.createFromDataURL.mockReturnValue(native.image);
41+
native.setBadgeCount.mockImplementation(() => true);
42+
native.listeners.clear();
43+
});
44+
45+
it.each(["darwin", "linux"] as const)("sets and clears the native %s count", (platform) => {
46+
applyNotificationBadge(platform, badge);
47+
applyNotificationBadge(platform, { count: 0, image: null });
48+
expect(native.setBadgeCount.mock.calls).toEqual([[2], [0]]);
49+
expect(native.createFromDataURL).not.toHaveBeenCalled();
50+
});
51+
52+
it("sets and clears the Windows taskbar overlay", () => {
53+
applyNotificationBadge("win32", badge);
54+
expect(native.setOverlayIcon).toHaveBeenLastCalledWith(
55+
native.image,
56+
"2 threads with new notifications",
57+
);
58+
applyNotificationBadge("win32", { count: 0, image: null });
59+
expect(native.setOverlayIcon).toHaveBeenLastCalledWith(null, "");
60+
});
61+
62+
it.each(["win32", "darwin", "linux"] as const)(
63+
"rejects a late positive count while %s is focused",
64+
(platform) => {
65+
native.getFocusedWindow.mockReturnValue({});
66+
applyNotificationBadge(platform, badge);
67+
if (platform === "win32") expect(native.setOverlayIcon).toHaveBeenCalledWith(null, "");
68+
else expect(native.setBadgeCount).toHaveBeenCalledWith(0);
69+
expect(native.createFromDataURL).not.toHaveBeenCalled();
70+
},
71+
);
72+
73+
it("ignores destroyed windows and clears invalid images", () => {
74+
native.isDestroyed.mockReturnValue(true);
75+
applyNotificationBadge("win32", badge);
76+
expect(native.setOverlayIcon).not.toHaveBeenCalled();
77+
native.isDestroyed.mockReturnValue(false);
78+
native.image.isEmpty.mockReturnValue(true);
79+
applyNotificationBadge("win32", badge);
80+
expect(native.setOverlayIcon.mock.calls[0]?.[0]).toBeNull();
81+
});
82+
83+
it("keeps notifications working when the native badge API fails", () => {
84+
native.setBadgeCount.mockImplementation(() => {
85+
throw new Error("Unavailable");
86+
});
87+
expect(() => applyNotificationBadge("linux", badge)).not.toThrow();
88+
});
89+
90+
it.effect("validates IPC and clears on native focus, quit, and disposal", () =>
91+
Effect.gen(function* () {
92+
const handlers = new Map<string, DesktopIpc.DesktopIpcHandleListener>();
93+
yield* Effect.scoped(
94+
Effect.gen(function* () {
95+
yield* installNotificationBadge();
96+
const handler = handlers.get("desktop:set-notification-badge")!;
97+
const event = { sender: { id: 1 } };
98+
for (const invalid of [
99+
{ ...badge, count: -1 },
100+
{ ...badge, count: 0.5 },
101+
{ ...badge, count: Infinity },
102+
{ ...badge, image: "https://example.com/icon.png" },
103+
{ ...badge, image: `data:image/png;base64,${"a".repeat(16_384)}` },
104+
]) {
105+
yield* Effect.promise(() => expect(handler(event, invalid)).rejects.toBeDefined());
106+
}
107+
expect(native.setBadgeCount).not.toHaveBeenCalled();
108+
yield* Effect.promise(() => Promise.resolve(handler(event, badge)));
109+
expect(native.setBadgeCount).toHaveBeenLastCalledWith(2);
110+
native.listeners.get("browser-window-focus")!();
111+
expect(native.setBadgeCount).toHaveBeenLastCalledWith(0);
112+
expect(native.webContents.send).toHaveBeenCalledWith("desktop:set-notification-badge");
113+
native.getFocusedWindow.mockReturnValue({});
114+
yield* Effect.promise(() => Promise.resolve(handler(event, badge)));
115+
expect(native.setBadgeCount).toHaveBeenLastCalledWith(0);
116+
expect(native.webContents.send).toHaveBeenCalledTimes(2);
117+
yield* Effect.promise(() => Promise.resolve(handler(event, { count: 0, image: null })));
118+
expect(native.webContents.send).toHaveBeenCalledTimes(2);
119+
native.getFocusedWindow.mockReturnValue(null);
120+
yield* Effect.promise(() => Promise.resolve(handler(event, badge)));
121+
native.listeners.get("before-quit")!();
122+
expect(native.setBadgeCount).toHaveBeenLastCalledWith(0);
123+
}),
124+
).pipe(
125+
Effect.provideService(HostProcessPlatform, "linux"),
126+
Effect.provide([
127+
ElectronApp.layer,
128+
DesktopIpc.layer({
129+
handle: (channel, handler) => {
130+
handlers.set(channel, handler);
131+
},
132+
removeHandler: (channel) => {
133+
handlers.delete(channel);
134+
},
135+
on: vi.fn(),
136+
removeAllListeners: vi.fn(),
137+
}),
138+
]),
139+
);
140+
expect(native.setBadgeCount).toHaveBeenLastCalledWith(0);
141+
expect(native.listeners.size).toBe(0);
142+
expect(handlers.size).toBe(0);
143+
}),
144+
);
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import * as Electron from "electron";
2+
import * as Effect from "effect/Effect";
3+
import * as Schema from "effect/Schema";
4+
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
5+
6+
import * as ElectronApp from "../../electron/ElectronApp.ts";
7+
import * as DesktopIpc from "../DesktopIpc.ts";
8+
import { SET_NOTIFICATION_BADGE_CHANNEL } from "../channels.ts";
9+
10+
const NotificationBadge = Schema.Struct({
11+
count: Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 2_147_483_647 })),
12+
image: Schema.NullOr(
13+
Schema.String.check(
14+
Schema.isMaxLength(16_384),
15+
Schema.isPattern(/^data:image\/png;base64,[a-z0-9+/]+={0,2}$/i),
16+
),
17+
),
18+
});
19+
20+
export function applyNotificationBadge(
21+
platform: NodeJS.Platform,
22+
{ count, image }: typeof NotificationBadge.Type,
23+
): void {
24+
try {
25+
if (Electron.BrowserWindow.getFocusedWindow()) count = 0;
26+
if (platform === "win32") {
27+
const overlay = count > 0 && image ? Electron.nativeImage.createFromDataURL(image) : null;
28+
for (const window of Electron.BrowserWindow.getAllWindows()) {
29+
if (!window.isDestroyed()) {
30+
window.setOverlayIcon(
31+
overlay?.isEmpty() ? null : overlay,
32+
count > 0 ? `${count} threads with new notifications` : "",
33+
);
34+
}
35+
}
36+
} else if (platform === "darwin" || platform === "linux") {
37+
Electron.app.setBadgeCount(count);
38+
}
39+
} catch (error) {
40+
Effect.runSync(Effect.logWarning("Could not update notification badge", error));
41+
}
42+
}
43+
44+
export const installNotificationBadge = Effect.fn("desktop.ipc.installNotificationBadge")(
45+
function* () {
46+
const ipc = yield* DesktopIpc.DesktopIpc;
47+
const app = yield* ElectronApp.ElectronApp;
48+
const platform = yield* HostProcessPlatform;
49+
const clear = () => {
50+
applyNotificationBadge(platform, { count: 0, image: null });
51+
for (const window of Electron.BrowserWindow.getAllWindows()) {
52+
if (!window.isDestroyed()) window.webContents.send(SET_NOTIFICATION_BADGE_CHANNEL);
53+
}
54+
};
55+
yield* ipc.handle(
56+
DesktopIpc.makeIpcMethod({
57+
channel: SET_NOTIFICATION_BADGE_CHANNEL,
58+
payload: NotificationBadge,
59+
result: Schema.Void,
60+
handler: (badge) =>
61+
Effect.sync(() => {
62+
if (badge.count > 0 && Electron.BrowserWindow.getFocusedWindow()) clear();
63+
else applyNotificationBadge(platform, badge);
64+
}),
65+
}),
66+
);
67+
yield* app.on("browser-window-focus", clear);
68+
yield* app.on("before-quit", clear);
69+
yield* Effect.addFinalizer(() => Effect.sync(clear));
70+
},
71+
);

‎apps/desktop/src/preload.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ contextBridge.exposeInMainWorld("desktopBridge", {
5757
return result as ReturnType<DesktopBridge["getAppBranding"]>;
5858
},
5959
getClientPlatform: () => clientPlatform,
60+
setNotificationBadge: (badge) =>
61+
ipcRenderer.invoke(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, badge),
62+
onNotificationBadgeClear: (listener) => {
63+
const handler = () => listener();
64+
ipcRenderer.on(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
65+
return () => ipcRenderer.removeListener(IpcChannels.SET_NOTIFICATION_BADGE_CHANNEL, handler);
66+
},
6067
getSystemLocale: () => {
6168
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
6269
return typeof result === "string" ? result : null;

0 commit comments

Comments
 (0)