Open History to see the last commit
1import type { AnyRouter } from "@tanstack/react-router";
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 { fakeTimers, stubGlobal } from "../../test/render";
9import { RELEASED_COMPLETION_GRACE_MS } from "./ThreadNotificationCoordinator.logic";
10
11const state = vi.hoisted(() => ({
12 mode: "notifications",
13 inApp: false,
14 toast: vi.fn(),
15 shells: null as unknown as { set: (id: string, value: unknown) => void },
16 navigate: vi.fn(),
17 sound: vi.fn(),
18 badge: vi.fn(),
19 settingsListeners: new Set<() => void>(),
20}));
21vi.mock(import("./ui/toast"), async (original) => {
22 const actual = await original();
23 return { ...actual, toastManager: { ...actual.toastManager, add: state.toast as never } };
24});
25vi.mock(import("../state/shell"), async (original) => {
26 const actual = await original();
27 return {
28 ...actual,
29 environmentShell: {
30 ...actual.environmentShell,
31 stateValueAtom: ((id: string) => shellAtom(id)) as never,
32 },
33 };
34});
35vi.mock(import("../state/presentation"), async (original) => {
36 const actual = await original();
37 return {
38 ...actual,
39 environmentSummaries: {
40 ...actual.environmentSummaries,
41 // Read lazily: the factory runs before this module's own bindings exist.
42 get environmentIdsAtom() {
43 return environmentIdsAtom as never;
44 },
45 },
46 };
47});
48vi.mock(import("../state/threads"), async (original) => {
49 const actual = await original();
50 return {
51 ...actual,
52 environmentThreadShells: {
53 ...actual.environmentThreadShells,
54 pendingSubagentRequestsAtom: (() => noRequestsAtom) as never,
55 get delegatedUnderParentAtom() {
56 return noDelegatedAtom as never;
57 },
58 },
59 };
60});
61vi.mock(import("../hooks/useSettings"), async (original) => ({
62 ...(await original()),
63 subscribeClientSettings: ((listener: () => void) => {
64 state.settingsListeners.add(listener);
65 return () => state.settingsListeners.delete(listener);
66 }) as never,
67 getClientSettings: (() => ({
68 notificationMode: state.mode,
69 inAppNotificationsEnabled: state.inApp,
70 })) as never,
71}));
72vi.mock(import("../threadNotifications"), async (original) => ({
73 ...(await original()),
74 playNotificationSound: state.sound,
75 unlockNotificationAudio: vi.fn(),
76 setNotificationBadge: state.badge,
77}));
78
79import { startThreadNotifications } from "./ThreadNotificationCoordinator";
80
81let registry: AtomRegistry.AtomRegistry;
82const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));
83const environmentIdsAtom = Atom.make<ReadonlyArray<string>>([]);
84const noRequestsAtom = Atom.make(new Map());
85const noDelegatedAtom = Atom.make<ReadonlySet<string>>(new Set<string>());
86state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };
87
88class TestNotification extends EventTarget {
89 static permission = "granted";
90 static sent: TestNotification[] = [];
91 close = vi.fn();
92 get tag() {
93 return this.options.tag ?? "";
94 }
95 constructor(
96 readonly title: string,
97 readonly options: NotificationOptions,
98 ) {
99 super();
100 TestNotification.sent.push(this);
101 }
102}
103
104const thread = {
105 id: "thread",
106 title: "Test thread",
107 archivedAt: null as string | null,
108 hasPendingApprovals: false,
109 hasPendingUserInput: false,
110 pendingRequestId: "request-1",
111 session: null as { status: string } | null,
112 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
113};
114let focused = false;
115let visibility = "visible";
116
117const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T07:00:00.000Z");
118
119function toV2ThreadShell(input: typeof thread) {
120 const latestTurn = input.latestTurn;
121 return {
122 id: input.id,
123 projectId: "project",
124 title: input.title,
125 providerInstanceId: "codex",
126 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
127 runtimeMode: "full-access",
128 interactionMode: "default",
129 branch: null,
130 worktreePath: null,
131 activeProviderThreadId: null,
132 lineage: {
133 rootThreadId: input.id,
134 parentThreadId: null,
135 relationshipToParent: null,
136 },
137 forkedFrom: null,
138 createdBy: "user",
139 creationSource: "web",
140 latestRunId: latestTurn.turnId,
141 activeRunId: null,
142 status:
143 latestTurn.state === "completed"
144 ? "completed"
145 : latestTurn.state === "error" || input.session?.status === "error"
146 ? "failed"
147 : "running",
148 pendingRuntimeRequest: input.hasPendingUserInput
149 ? { id: input.pendingRequestId, kind: "user_input", createdAt: SHELL_NOW }
150 : input.hasPendingApprovals
151 ? { id: input.pendingRequestId, kind: "command", createdAt: SHELL_NOW }
152 : null,
153 latestVisibleMessage: null,
154 latestUserMessageAt: null,
155 hasActionableProposedPlan: false,
156 itemCount: 0,
157 visibleItemCount: 0,
158 createdAt: SHELL_NOW,
159 updatedAt: SHELL_NOW,
160 latestRunRequestedAt: SHELL_NOW,
161 latestRunStartedAt: SHELL_NOW,
162 latestRunCompletedAt: latestTurn.completedAt
163 ? DateTime.makeUnsafe(latestTurn.completedAt)
164 : undefined,
165 archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null,
166 settledOverride: null,
167 settledAt: null,
168 lastVisitedAt: null,
169 deletedAt: null,
170 };
171}
172
173function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof thread>[]) {
174 return {
175 status: "live",
176 snapshot: Option.some({
177 threads: [overrides, ...others].map((override) =>
178 toV2ThreadShell({ ...thread, ...override }),
179 ),
180 }),
181 };
182}
183// The mocked modules read `state` and the focus flags, so every test resets them before
184// starting the service.
185function setup() {
186 vi.clearAllMocks();
187 const stack = new AsyncDisposableStack();
188 registry = AtomRegistry.make();
189 const testRegistry = registry;
190 stack.defer(() => testRegistry.dispose());
191 state.mode = "notifications";
192 state.inApp = false;
193 state.settingsListeners.clear();
194 registry.set(environmentIdsAtom, ["one", "two"]);
195 state.shells.set("one", shell());
196 state.shells.set("two", shell());
197 focused = false;
198 visibility = "visible";
199 TestNotification.permission = "granted";
200 TestNotification.sent = [];
201 stack.use(stubGlobal("Notification", TestNotification));
202 stack.use(vi.spyOn(window, "focus").mockImplementation(() => undefined));
203 stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => focused));
204 stack.use(
205 vi
206 .spyOn(document, "visibilityState", "get")
207 .mockImplementation(() => visibility as DocumentVisibilityState),
208 );
209 const router = {
210 state: { matches: [{ params: {} }] },
211 navigate: state.navigate,
212 } as unknown as AnyRouter;
213 return {
214 start: () => {
215 stack.defer(startThreadNotifications(testRegistry, router));
216 },
217 setEnvironmentIds: (ids: ReadonlyArray<string>) => testRegistry.set(environmentIdsAtom, ids),
218 changeSettings: () => {
219 for (const listener of state.settingsListeners) listener();
220 },
221 [Symbol.asyncDispose]: () => stack.disposeAsync(),
222 };
223}
224
225it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
226 "badges %s and clears when notifications are disabled",
227 async (flag) => {
228 await using app = setup();
229 app.start();
230 state.shells.set("one", shell({ [flag]: true }));
231 expect(state.badge).toHaveBeenLastCalledWith(1);
232 const notification = TestNotification.sent[0]!;
233 notification.dispatchEvent(new Event("click"));
234 expect(state.navigate).toHaveBeenCalledWith({
235 to: "/$environmentId/$threadId",
236 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
237 });
238 state.mode = "sound";
239 app.changeSettings();
240 expect(state.badge).toHaveBeenLastCalledWith(0);
241 expect(notification.close).toHaveBeenCalled();
242 },
243);
244
245it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
246 "notifies again when a new %s request replaces the pending one in the same run",
247 async (flag) => {
248 await using app = setup();
249 app.start();
250 state.shells.set("one", shell({ [flag]: true, pendingRequestId: "request-1" }));
251 state.shells.set("one", shell({ [flag]: true, pendingRequestId: "request-2" }));
252 const title = flag === "hasPendingApprovals" ? "Approval needed" : "Input needed";
253 expect(TestNotification.sent.map(({ title }) => title)).toEqual([title, title]);
254 },
255);
256
257it("presents completion notifications and sound as soon as the shell completes", async () => {
258 await using app = setup();
259 state.mode = "notifications-and-sound";
260 app.start();
261 state.shells.set(
262 "one",
263 shell({
264 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:00:01.000Z" },
265 }),
266 );
267 expect(TestNotification.sent.map((sent) => sent.title)).toEqual(["Thread completed"]);
268 expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
269});
270
271it.each([false, true])(
272 "presents one completion when a monitor ends with a final wake (disconnected: %s)",
273 async (disconnect) => {
274 await using app = setup();
275 using _timers = fakeTimers();
276 state.mode = "notifications-and-sound";
277 app.start();
278 const watching = (
279 turnId: string,
280 turnState: string,
281 completedAt: string | null,
282 latestRunBackgroundWake: boolean,
283 pendingBackgroundTasks: ReadonlyArray<{ taskId: string; kind: "monitor" }>,
284 ) => ({
285 status: "live",
286 snapshot: Option.some({
287 threads: [
288 {
289 ...toV2ThreadShell({
290 ...thread,
291 latestTurn: { turnId, state: turnState, completedAt },
292 }),
293 latestRunBackgroundWake,
294 pendingBackgroundTasks,
295 },
296 ],
297 }),
298 });
299 const monitor = [{ taskId: "watch", kind: "monitor" as const }];
300 const titles = () => TestNotification.sent.map(({ title }) => title);
301 state.shells.set(
302 "one",
303 watching("turn", "completed", "2026-09-13T07:00:01.000Z", false, monitor),
304 );
305 expect(titles()).toEqual(["Thread completed"]);
306
307 state.shells.set("one", watching("wake", "running", null, true, monitor));
308 state.shells.set(
309 "one",
310 watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, monitor),
311 );
312 expect(titles()).toEqual(["Thread completed"]);
313
314 // The adapter drains the roster before the final wake starts.
315 state.shells.set("one", watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []));
316 expect(titles()).toEqual(["Thread completed"]);
317 if (disconnect) {
318 state.shells.set("one", {
319 ...watching("wake", "completed", "2026-09-13T07:00:09.000Z", true, []),
320 status: "cached",
321 });
322 vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
323 expect(titles()).toEqual(["Thread completed"]);
324 }
325
326 state.shells.set("one", watching("final", "running", null, false, []));
327 vi.advanceTimersByTime(RELEASED_COMPLETION_GRACE_MS);
328 state.shells.set("one", watching("final", "completed", "2026-09-13T07:00:11.000Z", false, []));
329 expect(titles()).toEqual(["Thread completed", "Thread completed"]);
330 expect(state.sound).toHaveBeenCalledTimes(2);
331 },
332);
333
334it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
335 "notifies for offline completion and %s once across reconnects",
336 async (flag) => {
337 await using app = setup();
338 const asking = { id: "asking", hasPendingApprovals: true };
339 const offline = { id: "offline", [flag]: true };
340 const done = {
341 id: "done",
342 latestTurn: {
343 turnId: "done-turn",
344 state: "completed",
345 completedAt: "2026-09-13T07:00:00.000Z",
346 },
347 };
348 state.shells.set("one", shell({ id: "working" }, { id: "asking" }, { id: "offline" }, done));
349 app.start();
350 state.shells.set("one", shell({ id: "working" }, asking, { id: "offline" }, done));
351 state.shells.set("one", {
352 ...shell({ id: "working" }, asking, { id: "offline" }, done),
353 status: "cached",
354 });
355
356 const completed = {
357 id: "working",
358 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" },
359 };
360 state.shells.set("one", {
361 ...shell(completed, asking, offline, done),
362 status: "synchronizing",
363 });
364 state.shells.set("one", shell(completed, asking, offline, done));
365
366 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
367 "Approval needed",
368 "Thread completed",
369 flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
370 ]);
371 state.shells.set("one", { ...shell(completed, asking, offline, done), status: "cached" });
372 state.shells.set("one", shell(completed, asking, offline, done));
373 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
374 "Approval needed",
375 "Thread completed",
376 flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
377 ]);
378 },
379);
380
381it.each([false, true])(
382 "does not replay a notified completion after reconnect (continued: %s)",
383 async (continued) => {
384 await using app = setup();
385 app.start();
386 const completed = shell({
387 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" },
388 });
389 state.shells.set("one", completed);
390 state.shells.set("one", { ...completed, status: "cached" });
391 expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]);
392 state.shells.set("one", continued ? shell() : completed);
393 expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]);
394 },
395);