Open History to see the last commit
1import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2import type { AnyRouter } from "@tanstack/react-router";
3import { EnvironmentId } from "@t3tools/contracts";
4import * as DateTime from "effect/DateTime";
5import * as Option from "effect/Option";
6import { Atom, AtomRegistry } from "effect/reactivity";
7import { expect, it, vi } from "vite-plus/test";
8
9import { fakeTimers, stubGlobal } from "../../test/render";
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 session: null as { status: string } | null,
111 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
112};
113let focused = false;
114let visibility = "visible";
115
116const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T07:00:00.000Z");
117
118function toV2ThreadShell(input: typeof thread) {
119 const latestTurn = input.latestTurn;
120 return {
121 id: input.id,
122 projectId: "project",
123 title: input.title,
124 providerInstanceId: "codex",
125 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
126 runtimeMode: "full-access",
127 interactionMode: "default",
128 branch: null,
129 worktreePath: null,
130 activeProviderThreadId: null,
131 lineage: {
132 rootThreadId: input.id,
133 parentThreadId: null,
134 relationshipToParent: null,
135 },
136 forkedFrom: null,
137 createdBy: "user",
138 creationSource: "web",
139 latestRunId: latestTurn.turnId,
140 activeRunId: null,
141 status:
142 latestTurn.state === "completed"
143 ? "completed"
144 : latestTurn.state === "error" || input.session?.status === "error"
145 ? "failed"
146 : "running",
147 pendingRuntimeRequest: input.hasPendingUserInput
148 ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW }
149 : input.hasPendingApprovals
150 ? { id: "request-1", kind: "command", createdAt: SHELL_NOW }
151 : null,
152 latestVisibleMessage: null,
153 latestUserMessageAt: null,
154 hasActionableProposedPlan: false,
155 itemCount: 0,
156 visibleItemCount: 0,
157 createdAt: SHELL_NOW,
158 updatedAt: SHELL_NOW,
159 latestRunRequestedAt: SHELL_NOW,
160 latestRunStartedAt: SHELL_NOW,
161 latestRunCompletedAt: latestTurn.completedAt
162 ? DateTime.makeUnsafe(latestTurn.completedAt)
163 : undefined,
164 archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null,
165 settledOverride: null,
166 settledAt: null,
167 lastVisitedAt: null,
168 deletedAt: null,
169 };
170}
171
172function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof thread>[]) {
173 return {
174 status: "live",
175 snapshot: Option.some({
176 threads: [overrides, ...others].map((override) =>
177 toV2ThreadShell({ ...thread, ...override }),
178 ),
179 }),
180 };
181}
182// The mocked modules read `state` and the focus flags, so every test resets them before
183// starting the service.
184function setup() {
185 vi.clearAllMocks();
186 const stack = new AsyncDisposableStack();
187 registry = AtomRegistry.make();
188 const testRegistry = registry;
189 stack.defer(() => testRegistry.dispose());
190 state.mode = "notifications";
191 state.inApp = false;
192 state.settingsListeners.clear();
193 registry.set(environmentIdsAtom, ["one", "two"]);
194 state.shells.set("one", shell());
195 state.shells.set("two", shell());
196 focused = false;
197 visibility = "visible";
198 TestNotification.permission = "granted";
199 TestNotification.sent = [];
200 stack.use(stubGlobal("Notification", TestNotification));
201 stack.use(vi.spyOn(window, "focus").mockImplementation(() => undefined));
202 stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => focused));
203 stack.use(
204 vi
205 .spyOn(document, "visibilityState", "get")
206 .mockImplementation(() => visibility as DocumentVisibilityState),
207 );
208 const router = {
209 state: { matches: [{ params: {} }] },
210 navigate: state.navigate,
211 } as unknown as AnyRouter;
212 return {
213 start: () => {
214 stack.defer(startThreadNotifications(testRegistry, router));
215 },
216 setEnvironmentIds: (ids: ReadonlyArray<string>) => testRegistry.set(environmentIdsAtom, ids),
217 changeSettings: () => {
218 for (const listener of state.settingsListeners) listener();
219 },
220 [Symbol.asyncDispose]: () => stack.disposeAsync(),
221 };
222}
223
224it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
225 "badges %s and clears when notifications are disabled",
226 async (flag) => {
227 await using app = setup();
228 app.start();
229 state.shells.set("one", shell({ [flag]: true }));
230 expect(state.badge).toHaveBeenLastCalledWith(1);
231 const notification = TestNotification.sent[0]!;
232 notification.dispatchEvent(new Event("click"));
233 expect(state.navigate).toHaveBeenCalledWith({
234 to: "/$environmentId/$threadId",
235 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
236 });
237 state.mode = "sound";
238 app.changeSettings();
239 expect(state.badge).toHaveBeenLastCalledWith(0);
240 expect(notification.close).toHaveBeenCalled();
241 },
242);
243
244it("holds a completion through a continuation gap and notifies once it settles", async () => {
245 await using app = setup();
246 app.start();
247 using _timers = fakeTimers();
248 const finished = (turnId: string, completedAt: string) => ({
249 latestTurn: { turnId, state: "completed", completedAt },
250 });
251 state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z")));
252 state.shells.set(
253 "one",
254 shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }),
255 );
256 state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z")));
257 expect(TestNotification.sent).toEqual([]);
258 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1);
259 expect(TestNotification.sent).toEqual([]);
260 await vi.advanceTimersByTimeAsync(1);
261 expect(TestNotification.sent.map((sent) => sent.title)).toEqual(["Thread completed"]);
262});
263
264it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
265 "notifies for offline completion and %s once across reconnects",
266 async (flag) => {
267 await using app = setup();
268 const asking = { id: "asking", hasPendingApprovals: true };
269 const offline = { id: "offline", [flag]: true };
270 const done = {
271 id: "done",
272 latestTurn: {
273 turnId: "done-turn",
274 state: "completed",
275 completedAt: "2026-09-13T07:00:00.000Z",
276 },
277 };
278 state.shells.set("one", shell({ id: "working" }, { id: "asking" }, { id: "offline" }, done));
279 app.start();
280 using _timers = fakeTimers();
281 state.shells.set("one", shell({ id: "working" }, asking, { id: "offline" }, done));
282 state.shells.set("one", {
283 ...shell({ id: "working" }, asking, { id: "offline" }, done),
284 status: "cached",
285 });
286
287 const completed = {
288 id: "working",
289 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" },
290 };
291 state.shells.set("one", {
292 ...shell(completed, asking, offline, done),
293 status: "synchronizing",
294 });
295 state.shells.set("one", shell(completed, asking, offline, done));
296
297 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
298 "Approval needed",
299 flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
300 ]);
301 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
302 state.shells.set("one", { ...shell(completed, asking, offline, done), status: "cached" });
303 state.shells.set("one", shell(completed, asking, offline, done));
304 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
305 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
306 "Approval needed",
307 flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
308 "Thread completed",
309 ]);
310 },
311);
312
313it.each([false, true])(
314 "rechecks a pending completion after reconnect (continued: %s)",
315 async (continued) => {
316 await using app = setup();
317 app.start();
318 using _timers = fakeTimers();
319 const completed = shell({
320 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" },
321 });
322 state.shells.set("one", completed);
323 state.shells.set("one", { ...completed, status: "cached" });
324 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
325 expect(TestNotification.sent).toEqual([]);
326 state.shells.set("one", continued ? shell() : completed);
327 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
328 expect(TestNotification.sent.map(({ title }) => title)).toEqual(
329 continued ? [] : ["Thread completed"],
330 );
331 },
332);