Open History to see the last commit
1import type { ClientSettings } from "@t3tools/contracts/settings";
2import * as DateTime from "effect/DateTime";
3import * as Option from "effect/Option";
4import { act } from "react";
5import { createRoot, type Root } from "react-dom/client";
6import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7
8const state = vi.hoisted(() => ({
9 mode: "off" as ClientSettings["notificationMode"],
10 inApp: true,
11 active: { environmentId: "env-1", threadId: "other-thread" },
12 focused: true,
13 visible: "visible",
14 live: true,
15 completedAt: null as string | null,
16 archivedAt: null as string | null,
17 input: false,
18 approval: false,
19 sessionError: false,
20 turnError: false,
21 limited: false,
22 subagent: false,
23 background: [] as Array<{ taskId: string; kind: "command" | "monitor" }>,
24 delegatedChild: null as "running" | "approval" | null,
25 add: vi.fn(
26 (_toast: { title: string; description: string; actionProps: { onClick: () => void } }) =>
27 "toast-1",
28 ),
29 close: vi.fn(),
30 navigate: vi.fn(),
31 sound: vi.fn(),
32 notification: vi.fn(function (_title: string, options: NotificationOptions) {
33 return Object.assign(new EventTarget(), { tag: options.tag, close: vi.fn() });
34 }),
35}));
36
37const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T09:00:00.000Z");
38
39function mockThreadShell() {
40 return {
41 id: "thread-1",
42 projectId: "project-1",
43 title: "Fix the login form",
44 providerInstanceId: "codex",
45 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
46 runtimeMode: "full-access",
47 interactionMode: "default",
48 branch: null,
49 worktreePath: null,
50 activeProviderThreadId: null,
51 lineage: {
52 rootThreadId: "thread-1",
53 parentThreadId: state.subagent ? "parent" : null,
54 relationshipToParent: state.subagent ? "subagent" : null,
55 },
56 forkedFrom: null,
57 createdBy: "user",
58 creationSource: "web",
59 latestRunId: "run-1",
60 activeRunId: null,
61 status: state.completedAt
62 ? "completed"
63 : state.sessionError || state.turnError || state.limited
64 ? "failed"
65 : "running",
66 lastErrorClass: state.limited ? "usage_limit" : null,
67 pendingRuntimeRequest: state.input
68 ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW }
69 : state.approval
70 ? { id: "request-1", kind: "command", createdAt: SHELL_NOW }
71 : null,
72 latestVisibleMessage: null,
73 latestUserMessageAt: null,
74 hasActionableProposedPlan: false,
75 pendingBackgroundTasks: state.background,
76 itemCount: 0,
77 visibleItemCount: 0,
78 createdAt: SHELL_NOW,
79 updatedAt: SHELL_NOW,
80 latestRunRequestedAt: SHELL_NOW,
81 latestRunStartedAt: SHELL_NOW,
82 latestRunCompletedAt: state.completedAt ? DateTime.makeUnsafe(state.completedAt) : undefined,
83 archivedAt: state.archivedAt ? DateTime.makeUnsafe(state.archivedAt) : null,
84 settledOverride: null,
85 settledAt: null,
86 lastVisitedAt: null,
87 deletedAt: null,
88 };
89}
90
91let stableParent: ReturnType<typeof mockThreadShell> | null = null;
92function mockThreads() {
93 if (state.delegatedChild === null) return [mockThreadShell()];
94 stableParent ??= mockThreadShell();
95 const child = {
96 ...mockThreadShell(),
97 id: "child-1",
98 title: "Review the login form",
99 creationSource: "mcp",
100 lineage: {
101 rootThreadId: "thread-1",
102 parentThreadId: "thread-1",
103 relationshipToParent: "subagent",
104 },
105 pendingRuntimeRequest:
106 state.delegatedChild === "approval"
107 ? { id: "request-2", kind: "command", createdAt: SHELL_NOW }
108 : null,
109 };
110 return [stableParent, child];
111}
112
113vi.mock(import("@effect/atom-react"), async (original) => ({
114 ...(await original()),
115 useAtomValue: (() => ({
116 status: state.live ? "live" : "disconnected",
117 snapshot: Option.some({ threads: mockThreads() }),
118 })) as never,
119}));
120vi.mock(import("@tanstack/react-router"), async (original) => ({
121 ...(await original()),
122 useNavigate: (() => state.navigate) as never,
123 useParams: (() => state.active) as never,
124}));
125vi.mock(import("../hooks/useSettings"), async (original) => ({
126 ...(await original()),
127 useClientSettings: ((
128 select: (
129 settings: Pick<ClientSettings, "notificationMode" | "inAppNotificationsEnabled">,
130 ) => unknown,
131 ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,
132 getClientSettings: (() => ({ notificationMode: state.mode })) as never,
133}));
134vi.mock(import("../state/environments"), async (original) => ({
135 ...(await original()),
136 useEnvironmentIds: (() => ["env-1"]) as never,
137}));
138vi.mock(import("../threadNotifications"), async (original) => ({
139 ...(await original()),
140 playNotificationSound: state.sound,
141 setNotificationBadge: vi.fn(),
142}));
143vi.mock(import("./ui/toast"), async (original) => {
144 const actual = await original();
145 return {
146 ...actual,
147 toastManager: { ...actual.toastManager, add: state.add as never, close: state.close },
148 };
149});
150
151import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
152
153let root: Root;
154
155async function render() {
156 await act(() => root.render(<ThreadNotificationCoordinator />));
157}
158
159async function complete() {
160 state.completedAt = "2026-09-13T10:00:00.000Z";
161 await render();
162}
163
164beforeEach(() => {
165 vi.clearAllMocks();
166 Object.assign(state, {
167 mode: "off",
168 inApp: true,
169 active: { environmentId: "env-1", threadId: "other-thread" },
170 focused: true,
171 visible: "visible",
172 live: true,
173 completedAt: null,
174 archivedAt: null,
175 input: false,
176 approval: false,
177 sessionError: false,
178 turnError: false,
179 limited: false,
180 subagent: false,
181 background: [],
182 delegatedChild: null,
183 });
184 stableParent = null;
185 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
186 vi.spyOn(document, "visibilityState", "get").mockImplementation(
187 () => state.visible as DocumentVisibilityState,
188 );
189 vi.spyOn(document, "hasFocus").mockImplementation(() => state.focused);
190 vi.stubGlobal("Notification", Object.assign(state.notification, { permission: "granted" }));
191 root = createRoot(document.createElement("div"));
192});
193
194afterEach(async () => {
195 await act(() => root.unmount());
196 vi.restoreAllMocks();
197 vi.unstubAllGlobals();
198});
199
200describe("thread notifications", () => {
201 it.each([true, false])("keeps subagents silent with focus=%s", async (focused) => {
202 state.subagent = true;
203 state.focused = focused;
204 state.mode = "notifications-and-sound";
205 await render();
206 await complete();
207 state.input = true;
208 await render();
209 expect(state.sound).not.toHaveBeenCalled();
210 expect(state.add).not.toHaveBeenCalled();
211 expect(state.notification).not.toHaveBeenCalled();
212 });
213
214 it("alerts on the parent when its delegated subagent asks for approval", async () => {
215 state.mode = "notifications-and-sound";
216 state.delegatedChild = "running";
217 await render();
218 state.delegatedChild = "approval";
219 await render();
220 await render();
221 expect(state.add).toHaveBeenCalledTimes(1);
222 expect(state.add).toHaveBeenLastCalledWith(
223 expect.objectContaining({ title: "Approval needed", description: "Fix the login form" }),
224 );
225 });
226
227 it("alerts once with system alerts off and opens the completed thread", async () => {
228 await render();
229 await complete();
230 await render();
231 expect(state.add).toHaveBeenCalledTimes(1);
232 const toast = state.add.mock.calls[0]?.[0];
233 expect(toast?.title).toBe("Thread completed");
234 expect(toast?.description).toBe("Fix the login form");
235 toast?.actionProps.onClick();
236 expect(state.close).toHaveBeenCalledWith("toast-1");
237 expect(state.navigate).toHaveBeenCalledWith({
238 to: "/$environmentId/$threadId",
239 params: { environmentId: "env-1", threadId: "thread-1" },
240 });
241 expect(state.notification).not.toHaveBeenCalled();
242 });
243
244 it.each(["active", "blurred", "hidden", "archived", "disabled"])(
245 "does not show a completion toast for %s threads",
246 async (condition) => {
247 await render();
248 if (condition === "active") state.active.threadId = "thread-1";
249 if (condition === "blurred") state.focused = false;
250 if (condition === "hidden") state.visible = "hidden";
251 if (condition === "archived") state.archivedAt = "2026-09-13T09:00:00.000Z";
252 if (condition === "disabled") state.inApp = false;
253 await complete();
254 expect(state.add).not.toHaveBeenCalled();
255 },
256 );
257
258 it.each([
259 ["input", "Input needed"],
260 ["approval", "Approval needed"],
261 ["sessionError", "Thread failed"],
262 ["turnError", "Thread failed"],
263 ["limited", "Usage limit reached"],
264 ] as const)("uses the same %s event for in-app and desktop alerts", async (event, title) => {
265 state.mode = "notifications-and-sound";
266 await render();
267 state[event] = true;
268 await render();
269 await render();
270 expect(state.add).toHaveBeenCalledTimes(1);
271 expect(state.add).toHaveBeenLastCalledWith(expect.objectContaining({ title }));
272 expect(state.sound).toHaveBeenCalledWith("input", expect.any(Function));
273 expect(state.notification).not.toHaveBeenCalled();
274
275 state[event] = false;
276 await render();
277 state.focused = false;
278 state[event] = true;
279 await render();
280 await render();
281 expect(state.add).toHaveBeenCalledTimes(1);
282 expect(state.notification).toHaveBeenCalledTimes(1);
283 expect(state.notification).toHaveBeenCalledWith(title, {
284 body: "Fix the login form",
285 tag: "env-1:thread-1",
286 silent: true,
287 });
288 });
289
290 it("alerts when only a dev server is left running, not while a monitor can wake the agent", async () => {
291 await render();
292 state.background = [{ taskId: "watch", kind: "monitor" }];
293 await complete();
294 expect(state.add).not.toHaveBeenCalled();
295 state.background = [{ taskId: "dev", kind: "command" }];
296 await render();
297 expect(state.add).toHaveBeenCalledTimes(1);
298 expect(state.add).toHaveBeenLastCalledWith(
299 expect.objectContaining({ title: "Thread completed" }),
300 );
301 });
302
303 it("keeps background desktop alerts when in-app notifications are disabled", async () => {
304 state.focused = false;
305 state.inApp = false;
306 state.mode = "notifications";
307 await render();
308 await complete();
309 expect(state.add).not.toHaveBeenCalled();
310 expect(state.notification).toHaveBeenCalledTimes(1);
311 state.inApp = true;
312 await render();
313 expect(state.add).not.toHaveBeenCalled();
314 });
315
316 it("does not replay a completion when opting in from all alerts off", async () => {
317 state.inApp = false;
318 await render();
319 await complete();
320 state.inApp = true;
321 await render();
322 expect(state.add).not.toHaveBeenCalled();
323 });
324
325 it("compares the environment as well as the thread", async () => {
326 state.active = { environmentId: "env-2", threadId: "thread-1" };
327 await render();
328 await complete();
329 expect(state.add).toHaveBeenCalledTimes(1);
330 });
331
332 it("does not replay completed threads on first load or reconnect", async () => {
333 await complete();
334 state.live = false;
335 await render();
336 state.live = true;
337 await render();
338 expect(state.add).not.toHaveBeenCalled();
339 });
340
341 it("keeps sound but replaces the system popup when showing a toast", async () => {
342 state.mode = "notifications-and-sound";
343 await render();
344 await complete();
345 expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
346 expect(state.add).toHaveBeenCalledTimes(1);
347 expect(state.notification).not.toHaveBeenCalled();
348 });
349
350 it("keeps system alerts when the app is in the background", async () => {
351 state.mode = "notifications";
352 state.focused = false;
353 await render();
354 await complete();
355 expect(state.add).not.toHaveBeenCalled();
356 expect(state.notification).toHaveBeenCalledWith("Thread completed", {
357 body: "Fix the login form",
358 tag: "env-1:thread-1",
359 silent: true,
360 });
361 });
362});