Open History to see the last commit
1import { EnvironmentId } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import { act } from "react";
4import { create, type ReactTestRenderer } from "react-test-renderer";
5import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6
7const state = vi.hoisted(() => ({
8 mode: "notifications",
9 inApp: false,
10 toast: vi.fn(),
11 shells: new Map(),
12 navigate: vi.fn(),
13 sound: vi.fn(),
14 badge: vi.fn(),
15 environmentIds: ["one", "two"],
16}));
17vi.mock("@effect/atom-react", () => ({ useAtomValue: (id: string) => state.shells.get(id) }));
18vi.mock("@tanstack/react-router", () => ({
19 useNavigate: () => state.navigate,
20 useParams: () => ({}),
21}));
22vi.mock("./ui/toast", () => ({ toastManager: { add: state.toast } }));
23vi.mock("../state/shell", () => ({ environmentShell: { stateValueAtom: (id: string) => id } }));
24vi.mock("../state/environments", () => ({
25 useEnvironments: () => ({
26 environments: state.environmentIds.map((environmentId) => ({ environmentId })),
27 }),
28}));
29vi.mock("../hooks/useSettings", () => ({
30 useClientSettings: (
31 select: (settings: { notificationMode: string; inAppNotificationsEnabled: boolean }) => unknown,
32 ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp }),
33 getClientSettings: () => ({ notificationMode: state.mode }),
34}));
35vi.mock("../threadNotifications", async (importOriginal) => ({
36 ...(await importOriginal<typeof import("../threadNotifications")>()),
37 playNotificationSound: state.sound,
38 unlockNotificationAudio: vi.fn(),
39 setNotificationBadge: state.badge,
40}));
41
42import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
43
44class TestNotification extends EventTarget {
45 static permission = "granted";
46 static sent: TestNotification[] = [];
47 close = vi.fn();
48 get tag() {
49 return this.options.tag ?? "";
50 }
51 constructor(
52 readonly title: string,
53 readonly options: NotificationOptions,
54 ) {
55 super();
56 TestNotification.sent.push(this);
57 }
58}
59
60const thread = {
61 id: "thread",
62 title: "Test thread",
63 archivedAt: null as string | null,
64 hasPendingApprovals: false,
65 hasPendingUserInput: false,
66 session: null,
67 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
68};
69let renderer: ReactTestRenderer | undefined;
70let focused = false;
71let visibility = "visible";
72
73function shell(overrides: Partial<typeof thread> = {}) {
74 return { status: "live", snapshot: Option.some({ threads: [{ ...thread, ...overrides }] }) };
75}
76function complete(environment = "one", completedAt = "2026-09-13T08:00:00Z") {
77 state.shells.set(
78 environment,
79 shell({ latestTurn: { turnId: "turn", state: "completed", completedAt } }),
80 );
81}
82async function render() {
83 await act(async () => {
84 if (renderer) renderer.update(<ThreadNotificationCoordinator />);
85 else renderer = create(<ThreadNotificationCoordinator />);
86 });
87}
88
89beforeEach(() => {
90 vi.clearAllMocks();
91 state.mode = "notifications";
92 state.inApp = false;
93 state.environmentIds = ["one", "two"];
94 state.shells.set("one", shell());
95 state.shells.set("two", shell());
96 focused = false;
97 visibility = "visible";
98 TestNotification.permission = "granted";
99 TestNotification.sent = [];
100 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
101 vi.stubGlobal("Notification", TestNotification);
102 vi.stubGlobal("window", Object.assign(new EventTarget(), { focus: vi.fn() }));
103 vi.stubGlobal(
104 "document",
105 Object.assign(new EventTarget(), {
106 hasFocus: () => focused,
107 get visibilityState() {
108 return visibility;
109 },
110 }),
111 );
112});
113
114afterEach(async () => {
115 await act(async () => renderer?.unmount());
116 renderer = undefined;
117 vi.unstubAllGlobals();
118});
119
120it("counts notifying threads across environments, replaces repeat alerts, and clears on focus", async () => {
121 await render();
122 complete();
123 await render();
124 expect(state.badge).toHaveBeenLastCalledWith(1);
125 complete("one", "2026-09-13T08:01:00Z");
126 complete("two");
127 await render();
128 expect(state.badge).toHaveBeenLastCalledWith(2);
129 expect(TestNotification.sent[0]!.close).toHaveBeenCalledOnce();
130 focused = true;
131 window.dispatchEvent(new Event("focus"));
132 expect(state.badge).toHaveBeenLastCalledWith(0);
133 expect(
134 TestNotification.sent.every((notification) => notification.close.mock.calls.length > 0),
135 ).toBe(true);
136 focused = false;
137 complete("two", "2026-09-13T08:02:00Z");
138 await render();
139 expect(state.badge).toHaveBeenLastCalledWith(1);
140});
141
142it("does not badge old completions on first load or reconnect", async () => {
143 complete();
144 await render();
145 state.shells.set("one", { status: "connecting", snapshot: Option.none() });
146 await render();
147 complete("one", "2026-09-13T08:01:00Z");
148 await render();
149 expect(TestNotification.sent).toHaveLength(0);
150 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
151});
152
153it("removes alerts only from environments that leave the client", async () => {
154 await render();
155 complete("one");
156 complete("two");
157 await render();
158 expect(state.badge).toHaveBeenLastCalledWith(2);
159 const [removed, retained] = TestNotification.sent;
160 state.environmentIds = ["two"];
161 await render();
162 expect(state.badge).toHaveBeenLastCalledWith(1);
163 expect(removed!.close).toHaveBeenCalledOnce();
164 expect(retained!.close).not.toHaveBeenCalled();
165 await render();
166 expect(removed!.close).toHaveBeenCalledOnce();
167 state.environmentIds = [];
168 await render();
169 expect(state.badge).toHaveBeenLastCalledWith(0);
170 expect(retained!.close).toHaveBeenCalledOnce();
171});
172
173it("starts a fresh count after another native app window gains focus", async () => {
174 let clear: (() => void) | undefined;
175 const unsubscribe = vi.fn();
176 Object.assign(window, {
177 desktopBridge: {
178 onNotificationBadgeClear: (listener: () => void) => {
179 clear = listener;
180 return unsubscribe;
181 },
182 },
183 });
184 await render();
185 complete();
186 await render();
187 clear!();
188 expect(state.badge).toHaveBeenLastCalledWith(0);
189 complete("two");
190 await render();
191 expect(state.badge).toHaveBeenLastCalledWith(1);
192 await act(async () => renderer!.unmount());
193 renderer = undefined;
194 expect(unsubscribe).toHaveBeenCalledOnce();
195 expect(state.badge).toHaveBeenLastCalledWith(0);
196});
197
198it.each(["off", "sound", "focused", "denied", "archived"])(
199 "does not show visual alerts when %s",
200 async (condition) => {
201 if (condition === "off" || condition === "sound") state.mode = condition;
202 if (condition === "focused") focused = true;
203 if (condition === "denied") TestNotification.permission = "denied";
204 await render();
205 complete();
206 if (condition === "archived")
207 state.shells.set(
208 "one",
209 shell({
210 archivedAt: "2026-09-13T08:00:00Z",
211 hasPendingApprovals: true,
212 }),
213 );
214 await render();
215 expect(TestNotification.sent).toHaveLength(0);
216 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
217 },
218);
219
220it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
221 "badges %s and clears when notifications are disabled",
222 async (flag) => {
223 await render();
224 state.shells.set("one", shell({ [flag]: true }));
225 await render();
226 expect(state.badge).toHaveBeenLastCalledWith(1);
227 const notification = TestNotification.sent[0]!;
228 notification.dispatchEvent(new Event("click"));
229 expect(state.navigate).toHaveBeenCalledWith({
230 to: "/$environmentId/$threadId",
231 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
232 });
233 state.mode = "sound";
234 await render();
235 expect(state.badge).toHaveBeenLastCalledWith(0);
236 expect(notification.close).toHaveBeenCalled();
237 },
238);
239
240it("shows in-app alerts without adding a badge while focused", async () => {
241 state.inApp = true;
242 focused = true;
243 await render();
244 complete();
245 await render();
246 expect(state.toast).toHaveBeenCalledOnce();
247 expect(TestNotification.sent).toHaveLength(0);
248 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
249});
250
251it("badges background failures with in-app notifications enabled", async () => {
252 state.inApp = true;
253 await render();
254 state.shells.set("one", shell({ latestTurn: { ...thread.latestTurn, state: "error" } }));
255 await render();
256 expect(TestNotification.sent[0]?.title).toBe("Thread failed");
257 expect(state.badge).toHaveBeenLastCalledWith(1);
258 expect(state.toast).not.toHaveBeenCalled();
259});