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

ThreadNotificationCoordinator.badge.browser.test.tsx

240 lines7.9 KB

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 { expect, it, vi } from "vite-plus/test";
7​
8import { render, stubGlobal, type Screen } from "../../test/render";
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 }
78​
79const thread = {
80 id: "thread",
81 title: "Test thread",
82 archivedAt: null as string | null,
83 latestRunSilent: false,
84 hasPendingApprovals: false,
85 hasPendingUserInput: false,
86 session: null as { status: string } | null,
87 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
88};
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 latestRunSilent: input.latestRunSilent,
117 activeRunId: null,
118 status:
119 latestTurn.state === "completed"
120 ? "completed"
121 : latestTurn.state === "error" || input.session?.status === "error"
122 ? "failed"
123 : "running",
124 pendingRuntimeRequest: input.hasPendingUserInput
125 ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW }
126 : input.hasPendingApprovals
127 ? { id: "request-1", kind: "command", createdAt: SHELL_NOW }
128 : null,
129 latestVisibleMessage: null,
130 latestUserMessageAt: null,
131 hasActionableProposedPlan: false,
132 itemCount: 0,
133 visibleItemCount: 0,
134 createdAt: SHELL_NOW,
135 updatedAt: SHELL_NOW,
136 latestRunRequestedAt: SHELL_NOW,
137 latestRunStartedAt: SHELL_NOW,
138 latestRunCompletedAt: latestTurn.completedAt
139 ? DateTime.makeUnsafe(latestTurn.completedAt)
140 : undefined,
141 archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null,
142 settledOverride: null,
143 settledAt: null,
144 lastVisitedAt: null,
145 deletedAt: null,
146 };
148​
149function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof thread>[]) {
150 return {
151 status: "live",
152 snapshot: Option.some({
153 threads: [overrides, ...others].map((override) =>
154 toV2ThreadShell({ ...thread, ...override }),
155 ),
156 }),
157 };
159// The mocked modules read `state`, the registry and the focus flags, so every test starts by
160// resetting them. The first render is left to the test because some tests change state first.
161function setup() {
162 vi.clearAllMocks();
163 const stack = new AsyncDisposableStack();
164 registry = AtomRegistry.make();
165 const testRegistry = registry;
166 stack.defer(() => testRegistry.dispose());
167 state.mode = "notifications";
168 state.inApp = false;
169 state.environmentIds = ["one", "two"];
170 state.shells.set("one", shell());
171 state.shells.set("two", shell());
172 focused = false;
173 visibility = "visible";
174 TestNotification.permission = "granted";
175 TestNotification.sent = [];
176 stack.use(stubGlobal("Notification", TestNotification));
177 stack.use(vi.spyOn(window, "focus").mockImplementation(() => undefined));
178 stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => focused));
179 stack.use(
180 vi
181 .spyOn(document, "visibilityState", "get")
182 .mockImplementation(() => visibility as DocumentVisibilityState),
183 );
184 const ui = () => (
185 <RegistryContext.Provider value={testRegistry}>
186 <ThreadNotificationCoordinator />
187 </RegistryContext.Provider>
188 );
189 let screen: Screen | undefined;
190 return {
191 ui,
192 async render() {
193 if (screen) await screen.rerender(ui());
194 else screen = stack.use(await render(ui()));
195 },
196 unmount: () => screen!.unmount(),
197 [Symbol.asyncDispose]: () => stack.disposeAsync(),
198 };
200​
201it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
202 "badges %s and clears when notifications are disabled",
203 async (flag) => {
204 await using app = setup();
205 await app.render();
206 state.shells.set("one", shell({ [flag]: true }));
207 await app.render();
208 expect(state.badge).toHaveBeenLastCalledWith(1);
209 const notification = TestNotification.sent[0]!;
210 notification.dispatchEvent(new Event("click"));
211 expect(state.navigate).toHaveBeenCalledWith({
212 to: "/$environmentId/$threadId",
213 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
214 });
215 state.mode = "sound";
216 await app.render();
217 expect(state.badge).toHaveBeenLastCalledWith(0);
218 expect(notification.close).toHaveBeenCalled();
219 },
220);
221​
222it.each([
223 ["pre-expiry compaction", true, "completed", []],
224 ["manual compaction", false, "completed", ["Thread completed"]],
225 ["failed pre-expiry compaction", true, "error", ["Thread failed"]],
226] as const)("notifies for %s only when attention is needed", async (_, silent, status, titles) => {
227 await using app = setup();
228 state.environmentIds = ["one"];
229 state.shells.set("one", shell({ latestRunSilent: silent }));
230 await using screen = await render(app.ui());
231 state.shells.set(
232 "one",
233 shell({
234 latestRunSilent: silent,
235 latestTurn: { turnId: "turn", state: status, completedAt: "2026-09-13T07:01:00.000Z" },
236 }),
237 );
238 await screen.rerender(app.ui());
239 expect(TestNotification.sent.map((notification) => notification.title)).toEqual(titles);
240});