Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadNotificationCoordinator.test.tsx

254 lines8.0 KB

1import type { ClientSettings } from "@t3tools/contracts/settings";
2import * as Option from "effect/Option";
3import { act } from "react";
4import { create, type ReactTestRenderer } from "react-test-renderer";
5import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6​
7const state = vi.hoisted(() => ({
8 mode: "off" as ClientSettings["notificationMode"],
9 inApp: true,
10 active: { environmentId: "env-1", threadId: "other-thread" },
11 focused: true,
12 visible: "visible",
13 live: true,
14 completedAt: null as string | null,
15 archivedAt: null as string | null,
16 input: false,
17 approval: false,
18 sessionError: false,
19 turnError: false,
20 add: vi.fn(
21 (_toast: { title: string; description: string; actionProps: { onClick: () => void } }) =>
22 "toast-1",
23 ),
24 close: vi.fn(),
25 navigate: vi.fn(),
26 sound: vi.fn(),
27 notification: vi.fn(function (_title: string, options: NotificationOptions) {
28 return Object.assign(new EventTarget(), { tag: options.tag, close: vi.fn() });
29 }),
30}));
31​
32vi.mock("@effect/atom-react", () => ({
33 useAtomValue: () => ({
34 status: state.live ? "live" : "disconnected",
35 snapshot: Option.some({
36 threads: [
37 {
38 id: "thread-1",
39 title: "Fix the login form",
40 archivedAt: state.archivedAt,
41 hasPendingUserInput: state.input,
42 hasPendingApprovals: state.approval,
43 session: state.sessionError ? { status: "error" } : null,
44 latestTurn: {
45 turnId: "turn-1",
46 state: state.turnError ? "error" : state.completedAt ? "completed" : "running",
47 completedAt: state.completedAt,
48 },
49 },
50 ],
51 }),
52 }),
53}));
54vi.mock("@tanstack/react-router", () => ({
55 useNavigate: () => state.navigate,
56 useParams: () => state.active,
57}));
58vi.mock("../hooks/useSettings", () => ({
59 useClientSettings: (
60 select: (
61 settings: Pick<ClientSettings, "notificationMode" | "inAppNotificationsEnabled">,
62 ) => unknown,
63 ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp }),
64 getClientSettings: () => ({ notificationMode: state.mode }),
65}));
66vi.mock("../state/environments", () => ({
67 useEnvironments: () => ({ environments: [{ environmentId: "env-1" }] }),
68}));
69vi.mock("../state/shell", () => ({
70 environmentShell: { stateValueAtom: vi.fn() },
71}));
72vi.mock("../threadNotifications", async (importOriginal) => ({
73 ...(await importOriginal<typeof import("../threadNotifications")>()),
74 playNotificationSound: state.sound,
75 setNotificationBadge: vi.fn(),
76}));
77vi.mock("./ui/toast", () => ({
78 toastManager: { add: state.add, close: state.close },
79}));
80​
81import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
82​
83let renderer: ReactTestRenderer | undefined;
84​
85async function render() {
86 await act(() => {
87 if (renderer) renderer.update(<ThreadNotificationCoordinator />);
88 else renderer = create(<ThreadNotificationCoordinator />);
89 });
91​
92async function complete() {
93 state.completedAt = "2026-09-13T10:00:00.000Z";
94 await render();
96​
97beforeEach(() => {
98 vi.clearAllMocks();
99 Object.assign(state, {
100 mode: "off",
101 inApp: true,
102 active: { environmentId: "env-1", threadId: "other-thread" },
103 focused: true,
104 visible: "visible",
105 live: true,
106 completedAt: null,
107 archivedAt: null,
108 input: false,
109 approval: false,
110 sessionError: false,
111 turnError: false,
112 });
113 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
114 vi.stubGlobal("window", new EventTarget());
115 vi.stubGlobal("document", {
116 get visibilityState() {
117 return state.visible;
118 },
119 hasFocus: () => state.focused,
120 addEventListener: vi.fn(),
121 removeEventListener: vi.fn(),
122 });
123 vi.stubGlobal("Notification", Object.assign(state.notification, { permission: "granted" }));
124});
125​
126afterEach(async () => {
127 await act(() => renderer?.unmount());
128 renderer = undefined;
129 vi.unstubAllGlobals();
130});
131​
132describe("thread notifications", () => {
133 it("alerts once with system alerts off and opens the completed thread", async () => {
134 await render();
135 await complete();
136 await render();
137 expect(state.add).toHaveBeenCalledTimes(1);
138 const toast = state.add.mock.calls[0]?.[0];
139 expect(toast?.title).toBe("Thread completed");
140 expect(toast?.description).toBe("Fix the login form");
141 toast?.actionProps.onClick();
142 expect(state.close).toHaveBeenCalledWith("toast-1");
143 expect(state.navigate).toHaveBeenCalledWith({
144 to: "/$environmentId/$threadId",
145 params: { environmentId: "env-1", threadId: "thread-1" },
146 });
147 expect(state.notification).not.toHaveBeenCalled();
148 });
149​
150 it.each(["active", "blurred", "hidden", "archived", "disabled"])(
151 "does not show a completion toast for %s threads",
152 async (condition) => {
153 await render();
154 if (condition === "active") state.active.threadId = "thread-1";
155 if (condition === "blurred") state.focused = false;
156 if (condition === "hidden") state.visible = "hidden";
157 if (condition === "archived") state.archivedAt = "2026-09-13T09:00:00.000Z";
158 if (condition === "disabled") state.inApp = false;
159 await complete();
160 expect(state.add).not.toHaveBeenCalled();
161 },
162 );
163​
164 it.each([
165 ["input", "Input needed"],
166 ["approval", "Approval needed"],
167 ["sessionError", "Thread failed"],
168 ["turnError", "Thread failed"],
169 ] as const)("uses the same %s event for in-app and desktop alerts", async (event, title) => {
170 state.mode = "notifications-and-sound";
171 await render();
172 state[event] = true;
173 await render();
174 await render();
175 expect(state.add).toHaveBeenCalledTimes(1);
176 expect(state.add).toHaveBeenLastCalledWith(expect.objectContaining({ title }));
177 expect(state.sound).toHaveBeenCalledWith("input", expect.any(Function));
178 expect(state.notification).not.toHaveBeenCalled();
179​
180 state[event] = false;
181 await render();
182 state.focused = false;
183 state[event] = true;
184 await render();
185 await render();
186 expect(state.add).toHaveBeenCalledTimes(1);
187 expect(state.notification).toHaveBeenCalledTimes(1);
188 expect(state.notification).toHaveBeenCalledWith(title, {
189 body: "Fix the login form",
190 tag: "env-1:thread-1",
191 silent: true,
192 });
193 });
194​
195 it("keeps background desktop alerts when in-app notifications are disabled", async () => {
196 state.focused = false;
197 state.inApp = false;
198 state.mode = "notifications";
199 await render();
200 await complete();
201 expect(state.add).not.toHaveBeenCalled();
202 expect(state.notification).toHaveBeenCalledTimes(1);
203 state.inApp = true;
204 await render();
205 expect(state.add).not.toHaveBeenCalled();
206 });
207​
208 it("does not replay a completion when opting in from all alerts off", async () => {
209 state.inApp = false;
210 await render();
211 await complete();
212 state.inApp = true;
213 await render();
214 expect(state.add).not.toHaveBeenCalled();
215 });
216​
217 it("compares the environment as well as the thread", async () => {
218 state.active = { environmentId: "env-2", threadId: "thread-1" };
219 await render();
220 await complete();
221 expect(state.add).toHaveBeenCalledTimes(1);
222 });
223​
224 it("does not replay completed threads on first load or reconnect", async () => {
225 await complete();
226 state.live = false;
227 await render();
228 state.live = true;
229 await render();
230 expect(state.add).not.toHaveBeenCalled();
231 });
232​
233 it("keeps sound but replaces the system popup when showing a toast", async () => {
234 state.mode = "notifications-and-sound";
235 await render();
236 await complete();
237 expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
238 expect(state.add).toHaveBeenCalledTimes(1);
239 expect(state.notification).not.toHaveBeenCalled();
240 });
241​
242 it("keeps system alerts when the app is in the background", async () => {
243 state.mode = "notifications";
244 state.focused = false;
245 await render();
246 await complete();
247 expect(state.add).not.toHaveBeenCalled();
248 expect(state.notification).toHaveBeenCalledWith("Thread completed", {
249 body: "Fix the login form",
250 tag: "env-1:thread-1",
251 silent: true,
252 });
253 });
254});