Open History to see the last commit
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 }
77}
78
79const thread = {
80 id: "thread",
81 title: "Test thread",
82 archivedAt: null as string | null,
83 hasPendingApprovals: false,
84 hasPendingUserInput: false,
85 session: null as { status: string } | null,
86 latestTurn: { turnId: "turn", state: "running", completedAt: null as string | null },
87};
88let focused = false;
89let visibility = "visible";
90
91const SHELL_NOW = DateTime.makeUnsafe("2026-09-13T07:00:00.000Z");
92
93function toV2ThreadShell(input: typeof thread) {
94 const latestTurn = input.latestTurn;
95 return {
96 id: input.id,
97 projectId: "project",
98 title: input.title,
99 providerInstanceId: "codex",
100 modelSelection: { instanceId: "codex", model: "gpt-5.4" },
101 runtimeMode: "full-access",
102 interactionMode: "default",
103 branch: null,
104 worktreePath: null,
105 activeProviderThreadId: null,
106 lineage: {
107 rootThreadId: input.id,
108 parentThreadId: null,
109 relationshipToParent: null,
110 },
111 forkedFrom: null,
112 createdBy: "user",
113 creationSource: "web",
114 latestRunId: latestTurn.turnId,
115 activeRunId: null,
116 status:
117 latestTurn.state === "completed"
118 ? "completed"
119 : latestTurn.state === "error" || input.session?.status === "error"
120 ? "failed"
121 : "running",
122 pendingRuntimeRequest: input.hasPendingUserInput
123 ? { id: "request-1", kind: "user_input", createdAt: SHELL_NOW }
124 : input.hasPendingApprovals
125 ? { id: "request-1", kind: "command", createdAt: SHELL_NOW }
126 : null,
127 latestVisibleMessage: null,
128 latestUserMessageAt: null,
129 hasActionableProposedPlan: false,
130 itemCount: 0,
131 visibleItemCount: 0,
132 createdAt: SHELL_NOW,
133 updatedAt: SHELL_NOW,
134 latestRunRequestedAt: SHELL_NOW,
135 latestRunStartedAt: SHELL_NOW,
136 latestRunCompletedAt: latestTurn.completedAt
137 ? DateTime.makeUnsafe(latestTurn.completedAt)
138 : undefined,
139 archivedAt: input.archivedAt ? DateTime.makeUnsafe(input.archivedAt) : null,
140 settledOverride: null,
141 settledAt: null,
142 lastVisitedAt: null,
143 deletedAt: null,
144 };
145}
146
147function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof thread>[]) {
148 return {
149 status: "live",
150 snapshot: Option.some({
151 threads: [overrides, ...others].map((override) =>
152 toV2ThreadShell({ ...thread, ...override }),
153 ),
154 }),
155 };
156}
157// The mocked modules read `state`, the registry and the focus flags, so every test starts by
158// resetting them. The first render is left to the test because some tests change state first.
159function setup() {
160 vi.clearAllMocks();
161 const stack = new AsyncDisposableStack();
162 registry = AtomRegistry.make();
163 const testRegistry = registry;
164 stack.defer(() => testRegistry.dispose());
165 state.mode = "notifications";
166 state.inApp = false;
167 state.environmentIds = ["one", "two"];
168 state.shells.set("one", shell());
169 state.shells.set("two", shell());
170 focused = false;
171 visibility = "visible";
172 TestNotification.permission = "granted";
173 TestNotification.sent = [];
174 stack.use(stubGlobal("Notification", TestNotification));
175 stack.use(vi.spyOn(window, "focus").mockImplementation(() => undefined));
176 stack.use(vi.spyOn(document, "hasFocus").mockImplementation(() => focused));
177 stack.use(
178 vi
179 .spyOn(document, "visibilityState", "get")
180 .mockImplementation(() => visibility as DocumentVisibilityState),
181 );
182 const ui = () => (
183 <RegistryContext.Provider value={testRegistry}>
184 <ThreadNotificationCoordinator />
185 </RegistryContext.Provider>
186 );
187 let screen: Screen | undefined;
188 return {
189 async render() {
190 if (screen) await screen.rerender(ui());
191 else screen = stack.use(await render(ui()));
192 },
193 unmount: () => screen!.unmount(),
194 [Symbol.asyncDispose]: () => stack.disposeAsync(),
195 };
196}
197
198it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
199 "badges %s and clears when notifications are disabled",
200 async (flag) => {
201 await using app = setup();
202 await app.render();
203 state.shells.set("one", shell({ [flag]: true }));
204 await app.render();
205 expect(state.badge).toHaveBeenLastCalledWith(1);
206 const notification = TestNotification.sent[0]!;
207 notification.dispatchEvent(new Event("click"));
208 expect(state.navigate).toHaveBeenCalledWith({
209 to: "/$environmentId/$threadId",
210 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
211 });
212 state.mode = "sound";
213 await app.render();
214 expect(state.badge).toHaveBeenLastCalledWith(0);
215 expect(notification.close).toHaveBeenCalled();
216 },
217);