Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { EnvironmentId } from "@t3tools/contracts";
3import * as DateTime from "effect/DateTime";
4import * as Option from "effect/Option";
5import { Atom, AtomRegistry } from "effect/reactivity";
6import { act } from "react";
7import { createRoot, type Root } from "react-dom/client";
8import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
9
10const state = vi.hoisted(() => ({
11 mode: "notifications",
12 inApp: false,
13 toast: vi.fn(),
14 shells: null as unknown as { set: (id: string, value: unknown) => void },
15 navigate: vi.fn(),
16 sound: vi.fn(),
17 badge: vi.fn(),
18 environmentIds: ["one", "two"],
19}));
20vi.mock(import("@tanstack/react-router"), async (original) => ({
21 ...(await original()),
22 useNavigate: (() => state.navigate) as never,
23 useParams: (() => ({})) as never,
24}));
25vi.mock(import("./ui/toast"), async (original) => {
26 const actual = await original();
27 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast as never } };
28});
29vi.mock(import("../state/shell"), async (original) => {
30 const actual = await original();
31 return {
32 ...actual,
33 environmentShell: {
34 ...actual.environmentShell,
35 stateValueAtom: ((id: string) => shellAtom(id)) as never,
36 },
37 };
38});
39vi.mock(import("../state/environments"), async (original) => ({
40 ...(await original()),
41 useEnvironmentIds: (() => state.environmentIds) as never,
42}));
43vi.mock(import("../hooks/useSettings"), async (original) => ({
44 ...(await original()),
45 useClientSettings: ((
46 select: (settings: { notificationMode: string; inAppNotificationsEnabled: boolean }) => unknown,
47 ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,
48 getClientSettings: (() => ({ notificationMode: state.mode })) as never,
49}));
50vi.mock(import("../threadNotifications"), async (original) => ({
51 ...(await original()),
52 playNotificationSound: state.sound,
53 unlockNotificationAudio: vi.fn(),
54 setNotificationBadge: state.badge,
55}));
56
57import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
58
59let registry: AtomRegistry.AtomRegistry;
60const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));
61state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };
62
63class TestNotification extends EventTarget {
64 static permission = "granted";
65 static sent: TestNotification[] = [];
66 close = vi.fn();
67 get tag() {
68 return this.options.tag ?? "";
69 }
70 constructor(
71 readonly title: string,
72 readonly options: NotificationOptions,
73 ) {
74 super();
75 TestNotification.sent.push(this);
76 }
77}
78
79const thread = {
80 id: "thread",
81 title: "Test thread",
82 archivedAt: null as string | null,
83 hasPendingApprovals: false,
84 hasPendingUserInput: false,
85 session: null as { status: string } | null,
86 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
87};
88let root: Root;
89let focused = false;
90let visibility = "visible";
91
92const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T07:00:00.000Z");
93
94function toV2ThreadShell(input: typeof thread) {
95 const latestTurn = input.latestTurn;
96 return {
97 id: input.id,
98 projectId: "project",
99 title: input.title,
100 providerInstanceId: "codex",
101 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
102 runtimeMode: "full-access",
103 interactionMode: "default",
104 branch: null,
105 worktreePath: null,
106 activeProviderThreadId: null,
107 lineage: {
108 rootThreadId: input.id,
109 parentThreadId: null,
110 relationshipToParent: null,
111 },
112 forkedFrom: null,
113 createdBy: "user",
114 creationSource: "web",
115 latestRunId: latestTurn.turnId,
116 activeRunId: null,
117 status:
118 latestTurn.state === "completed"
119 ? "completed"
120 : latestTurn.state === "error" || input.session?.status === "error"
121 ? "failed"
122 : "running",
123 pendingRuntimeRequest: input.hasPendingUserInput
124 ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW }
125 : input.hasPendingApprovals
126 ? { id: "request-1", kind: "command", createdAt: SHELL_NOW }
127 : null,
128 latestVisibleMessage: null,
129 latestUserMessageAt: null,
130 hasActionableProposedPlan: false,
131 itemCount: 0,
132 visibleItemCount: 0,
133 createdAt: SHELL_NOW,
134 updatedAt: SHELL_NOW,
135 latestRunRequestedAt: SHELL_NOW,
136 latestRunStartedAt: SHELL_NOW,
137 latestRunCompletedAt: latestTurn.completedAt
138 ? DateTime.makeUnsafe(latestTurn.completedAt)
139 : undefined,
140 archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null,
141 settledOverride: null,
142 settledAt: null,
143 lastVisitedAt: null,
144 deletedAt: null,
145 };
146}
147
148function shell(overrides: Partial<typeof thread> = {}) {
149 return {
150 status: "live",
151 snapshot: Option.some({ threads: [toV2ThreadShell({ ...thread, ...overrides })] }),
152 };
153}
154function complete(environment = "one", completedAt = "2026-09-13T08:00:00Z") {
155 state.shells.set(
156 environment,
157 shell({ latestTurn: { turnId: "turn", state: "completed", completedAt } }),
158 );
159}
160async function render() {
161 await act(async () =>
162 root.render(
163 <RegistryContext.Provider value={registry}>
164 <ThreadNotificationCoordinator />
165 </RegistryContext.Provider>,
166 ),
167 );
168}
169
170beforeEach(() => {
171 vi.clearAllMocks();
172 registry = AtomRegistry.make();
173 state.mode = "notifications";
174 state.inApp = false;
175 state.environmentIds = ["one", "two"];
176 state.shells.set("one", shell());
177 state.shells.set("two", shell());
178 focused = false;
179 visibility = "visible";
180 TestNotification.permission = "granted";
181 TestNotification.sent = [];
182 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
183 vi.stubGlobal("Notification", TestNotification);
184 vi.spyOn(window, "focus").mockImplementation(() => undefined);
185 vi.spyOn(document, "hasFocus").mockImplementation(() => focused);
186 vi.spyOn(document, "visibilityState", "get").mockImplementation(
187 () => visibility as DocumentVisibilityState,
188 );
189 root = createRoot(document.createElement("div"));
190});
191
192afterEach(async () => {
193 await act(async () => root.unmount());
194 delete window.desktopBridge;
195 registry.dispose();
196 vi.restoreAllMocks();
197 vi.unstubAllGlobals();
198});
199
200it("counts notifying threads across environments, replaces repeat alerts, and clears on focus", async () => {
201 await render();
202 complete();
203 await render();
204 expect(state.badge).toHaveBeenLastCalledWith(1);
205 complete("one", "2026-09-13T08:01:00Z");
206 complete("two");
207 await render();
208 expect(state.badge).toHaveBeenLastCalledWith(2);
209 expect(TestNotification.sent[0]!.close).toHaveBeenCalledOnce();
210 focused = true;
211 window.dispatchEvent(new Event("focus"));
212 expect(state.badge).toHaveBeenLastCalledWith(0);
213 expect(
214 TestNotification.sent.every((notification) => notification.close.mock.calls.length > 0),
215 ).toBe(true);
216 focused = false;
217 complete("two", "2026-09-13T08:02:00Z");
218 await render();
219 expect(state.badge).toHaveBeenLastCalledWith(1);
220});
221
222it("does not badge old completions on first load or reconnect", async () => {
223 complete();
224 await render();
225 state.shells.set("one", { status: "connecting", snapshot: Option.none() });
226 await render();
227 complete("one", "2026-09-13T08:01:00Z");
228 await render();
229 expect(TestNotification.sent).toHaveLength(0);
230 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
231});
232
233it("removes alerts only from environments that leave the client", async () => {
234 await render();
235 complete("one");
236 complete("two");
237 await render();
238 expect(state.badge).toHaveBeenLastCalledWith(2);
239 const [removed, retained] = TestNotification.sent;
240 state.environmentIds = ["two"];
241 await render();
242 expect(state.badge).toHaveBeenLastCalledWith(1);
243 expect(removed!.close).toHaveBeenCalledOnce();
244 expect(retained!.close).not.toHaveBeenCalled();
245 await render();
246 expect(removed!.close).toHaveBeenCalledOnce();
247 state.environmentIds = [];
248 await render();
249 expect(state.badge).toHaveBeenLastCalledWith(0);
250 expect(retained!.close).toHaveBeenCalledOnce();
251});
252
253it("starts a fresh count after another native app window gains focus", async () => {
254 let clear: (() => void) | undefined;
255 const unsubscribe = vi.fn();
256 Object.assign(window, {
257 desktopBridge: {
258 onNotificationBadgeClear: (listener: () => void) => {
259 clear = listener;
260 return unsubscribe;
261 },
262 },
263 });
264 await render();
265 complete();
266 await render();
267 clear!();
268 expect(state.badge).toHaveBeenLastCalledWith(0);
269 complete("two");
270 await render();
271 expect(state.badge).toHaveBeenLastCalledWith(1);
272 await act(async () => root.unmount());
273 root = createRoot(document.createElement("div"));
274 expect(unsubscribe).toHaveBeenCalledOnce();
275 expect(state.badge).toHaveBeenLastCalledWith(0);
276});
277
278it.each(["off", "sound", "focused", "denied", "archived"])(
279 "does not show visual alerts when %s",
280 async (condition) => {
281 if (condition === "off" || condition === "sound") state.mode = condition;
282 if (condition === "focused") focused = true;
283 if (condition === "denied") TestNotification.permission = "denied";
284 await render();
285 complete();
286 if (condition === "archived")
287 state.shells.set(
288 "one",
289 shell({
290 archivedAt: "2026-09-13T08:00:00Z",
291 hasPendingApprovals: true,
292 }),
293 );
294 await render();
295 expect(TestNotification.sent).toHaveLength(0);
296 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
297 },
298);
299
300it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
301 "badges %s and clears when notifications are disabled",
302 async (flag) => {
303 await render();
304 state.shells.set("one", shell({ [flag]: true }));
305 await render();
306 expect(state.badge).toHaveBeenLastCalledWith(1);
307 const notification = TestNotification.sent[0]!;
308 notification.dispatchEvent(new Event("click"));
309 expect(state.navigate).toHaveBeenCalledWith({
310 to: "/$environmentId/$threadId",
311 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
312 });
313 state.mode = "sound";
314 await render();
315 expect(state.badge).toHaveBeenLastCalledWith(0);
316 expect(notification.close).toHaveBeenCalled();
317 },
318);
319
320it("shows in-app alerts without adding a badge while focused", async () => {
321 state.inApp = true;
322 focused = true;
323 await render();
324 complete();
325 await render();
326 expect(state.toast).toHaveBeenCalledOnce();
327 expect(TestNotification.sent).toHaveLength(0);
328 expect(state.badge.mock.calls.every(([count]) => count === 0)).toBe(true);
329});
330
331it("badges background failures with in-app notifications enabled", async () => {
332 state.inApp = true;
333 await render();
334 state.shells.set("one", shell({ latestTurn: { ...thread.latestTurn, state: "error" } }));
335 await render();
336 expect(TestNotification.sent[0]?.title).toBe("Thread failed");
337 expect(state.badge).toHaveBeenLastCalledWith(1);
338 expect(state.toast).not.toHaveBeenCalled();
339});