Open History to see the last commit
1import {
2 type EnvironmentThreadShell,
3 type PendingSubagentRequest,
4 presentThreadShell,
5} from "@t3tools/client-runtime/state/models";
6import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
7import type { AnyRouter } from "@tanstack/react-router";
8import { threadKey } from "@t3tools/client-runtime/state/entities";
9import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
10import { monitorHoldsWakeCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
11import type { ClientSettings } from "@t3tools/contracts/settings";
12import * as Option from "effect/Option";
13import type { AtomRegistry } from "effect/reactivity";
14import {
15 CircleAlertIcon,
16 CircleCheckIcon,
17 MessageCircleQuestionIcon,
18 ShieldQuestionIcon,
19} from "lucide-react";
20
21import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings";
22import { isWindowsPlatform } from "../lib/utils";
23import { environmentSummaries } from "../state/presentation";
24import { environmentShell } from "../state/shell";
25import { environmentThreadShells } from "../state/threads";
26import {
27 hasDesktopNotifications,
28 hasNotificationSound,
29 playNotificationSound,
30 setNotificationBadge,
31 threadNotificationTag,
32 unlockNotificationAudio,
33} from "../threadNotifications";
34import { resolveBackgroundThreadRequest } from "./backgroundThreadAnnouncement";
35import { resolveSidebarThreadStatus, type SidebarThreadStatus } from "./Sidebar.logic";
36import {
37 createThreadNotificationGate,
38 type ThreadNotificationKind,
39 type ThreadNotificationObservation,
40} from "./ThreadNotificationCoordinator.logic";
41import { toastManager } from "./ui/toast";
42
43interface NotificationState extends ThreadNotificationObservation {
44 readonly raw: OrchestrationV2ThreadShell;
45 readonly subagentRequest: PendingSubagentRequest | null;
46 readonly thread: EnvironmentThreadShell;
47 readonly status: SidebarThreadStatus;
48}
49
50type ToastId = ReturnType<typeof toastManager.add>;
51
52interface WatchedEnvironment {
53 unsubscribe: () => void;
54 previous: Map<ThreadId, NotificationState>;
55 reconnecting: boolean;
56 readonly gate: ReturnType<typeof createThreadNotificationGate<ThreadId>>;
57}
58
59/**
60 * Turns thread status transitions in every connected environment into sounds, in-app toasts,
61 * and desktop notifications, and keeps the dock badge in step with the unread ones.
62 */
63export function startThreadNotifications(
64 registry: AtomRegistry.AtomRegistry,
65 router: AnyRouter,
66): () => void {
67 const pending = new Map<
68 string,
69 { environmentId: EnvironmentId; threadId: ThreadId; notification: Notification }
70 >();
71 const watched = new Map<EnvironmentId, WatchedEnvironment>();
72
73 const trackNotification = (
74 environmentId: EnvironmentId,
75 threadId: ThreadId,
76 notification: Notification,
77 ) => {
78 pending.get(notification.tag)?.notification.close();
79 pending.set(notification.tag, { environmentId, threadId, notification });
80 setNotificationBadge(pending.size);
81 };
82 // Toast ids by thread key, so hiding or opening a thread can close its open toasts.
83 const openToasts = new Map<string, Array<ToastId>>();
84 const forgetToast = (key: string, toastId: ToastId) => {
85 const remaining = (openToasts.get(key) ?? []).filter((id) => id !== toastId);
86 if (remaining.length === 0) openToasts.delete(key);
87 else openToasts.set(key, remaining);
88 };
89 const closeToasts = (shouldClose: (key: string) => boolean) => {
90 for (const [key, toastIds] of openToasts) {
91 if (!shouldClose(key)) continue;
92 for (const toastId of toastIds) toastManager.close(toastId);
93 openToasts.delete(key);
94 }
95 };
96 const activeThread = () =>
97 (router.state.matches.at(-1)?.params ?? {}) as {
98 environmentId?: EnvironmentId;
99 threadId?: ThreadId;
100 };
101 const closeOpenedThreadToasts = () => {
102 const { environmentId, threadId } = activeThread();
103 if (environmentId === undefined || threadId === undefined) return;
104 const opened = threadKey({ environmentId, threadId });
105 closeToasts((key) => key === opened);
106 };
107 // A notification shown before the tag filter turned on must not stay on screen. While hiding,
108 // one whose thread left the live list (archived) cannot be judged, so it closes too.
109 const closeHiddenPending = () => {
110 const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom);
111 const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom)
112 ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey))
113 : null;
114 const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key));
115 closeToasts(shouldClose);
116 const count = pending.size;
117 for (const [tag, entry] of pending) {
118 if (!shouldClose(threadKey(entry))) continue;
119 entry.notification.close();
120 pending.delete(tag);
121 }
122 if (count !== pending.size) setNotificationBadge(pending.size);
123 };
124 const clearPending = () => {
125 for (const { notification } of pending.values()) notification.close();
126 pending.clear();
127 setNotificationBadge(0);
128 };
129
130 const present = (
131 environmentId: EnvironmentId,
132 state: NotificationState,
133 kind: ThreadNotificationKind,
134 ) => {
135 const { thread, status } = state;
136 if (
137 registry
138 .get(environmentThreadShells.hiddenThreadKeysAtom)
139 .has(threadKey({ environmentId, threadId: thread.id }))
140 )
141 return;
142 const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();
143 const active = activeThread();
144 const title =
145 kind === "completion"
146 ? "Thread completed"
147 : status === "approval"
148 ? "Approval needed"
149 : status === "limited"
150 ? "Usage limit reached"
151 : status === "failed"
152 ? "Thread failed"
153 : status === "request"
154 ? "Guest request"
155 : "Input needed";
156 if (hasNotificationSound(mode)) {
157 void playNotificationSound(kind, () =>
158 hasNotificationSound(getClientSettings().notificationMode),
159 );
160 }
161 if (
162 inAppNotificationsEnabled &&
163 document.visibilityState === "visible" &&
164 document.hasFocus() &&
165 (active.environmentId !== environmentId || active.threadId !== thread.id)
166 ) {
167 const toastKey = threadKey({ environmentId, threadId: thread.id });
168 const toastId: ToastId = toastManager.add({
169 onRemove: (): void => forgetToast(toastKey, toastId),
170 type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
171 title,
172 description: thread.title,
173 data: {
174 hideCopyButton: true,
175 leadingIcon:
176 kind === "completion" ? (
177 <CircleCheckIcon aria-hidden className="size-4 text-success-foreground" />
178 ) : status === "approval" ? (
179 <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
180 ) : status === "limited" ? (
181 <CircleAlertIcon aria-hidden className="size-4 text-warning-foreground" />
182 ) : status === "failed" ? (
183 <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
184 ) : (
185 <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
186 ),
187 },
188 actionProps: {
189 children: "Open thread",
190 onClick: () => {
191 toastManager.close(toastId);
192 void router.navigate({
193 to: "/$environmentId/$threadId",
194 params: { environmentId, threadId: thread.id },
195 });
196 },
197 },
198 });
199 openToasts.set(toastKey, [...(openToasts.get(toastKey) ?? []), toastId]);
200 return;
201 }
202 if (
203 !hasDesktopNotifications(mode) ||
204 (document.visibilityState === "visible" && document.hasFocus()) ||
205 typeof Notification === "undefined" ||
206 Notification.permission !== "granted"
207 )
208 return;
209 try {
210 const notification = new Notification(title, {
211 body: thread.title,
212 tag: threadNotificationTag(environmentId, thread.id),
213 silent: true,
214 // Windows drops clicks after a toast moves into Notification Center.
215 requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),
216 });
217 trackNotification(environmentId, thread.id, notification);
218 notification.addEventListener("click", () => {
219 notification.close();
220 window.focus();
221 void window.desktopBridge?.revealWindow().catch(() => undefined);
222 void router.navigate({
223 to: "/$environmentId/$threadId",
224 params: { environmentId, threadId: thread.id },
225 });
226 });
227 } catch {
228 // Some browsers expose Notification but reject desktop presentation.
229 }
230 };
231
232 const observeThreads = (
233 environmentId: EnvironmentId,
234 entry: WatchedEnvironment,
235 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
236 ) => {
237 const previous = entry.previous;
238 const next = new Map<ThreadId, NotificationState>();
239 // A parent here also hears of what its tasks on linked environments ask.
240 const subagentRequests = registry.get(
241 environmentThreadShells.pendingSubagentRequestsAtom(environmentId),
242 );
243 const delegatedUnderParent = registry.get(environmentThreadShells.delegatedUnderParentAtom);
244 const changed: Array<[NotificationState | undefined, NotificationState]> = [];
245 for (const rawThread of threads) {
246 if (
247 isShownUnderParent(
248 { environmentId, threadId: rawThread.id },
249 rawThread.lineage,
250 delegatedUnderParent,
251 )
252 ) {
253 continue;
254 }
255 const prior = previous.get(rawThread.id);
256 const subagentRequest = subagentRequests.get(rawThread.id) ?? null;
257 if (
258 !entry.reconnecting &&
259 prior?.raw === rawThread &&
260 prior.subagentRequest === subagentRequest
261 ) {
262 next.set(rawThread.id, prior);
263 continue;
264 }
265 const thread = presentThreadShell(environmentId, rawThread, subagentRequest);
266 let status = resolveSidebarThreadStatus(thread);
267 if (status === "ready" && thread.latestRun?.status === "failed") status = "failed";
268 const needsAttention =
269 status === "input" ||
270 status === "request" ||
271 status === "approval" ||
272 status === "failed" ||
273 status === "limited";
274 const requestId = needsAttention ? resolveBackgroundThreadRequest(thread).requestId : null;
275 // Queued messages become the latest run while a request stays pending, so a request
276 // with an id is keyed by that id alone and announces once.
277 const attention = !needsAttention
278 ? null
279 : requestId !== null
280 ? `${status}:${requestId}`
281 : `${thread.latestRun?.runId ?? ""}:${status}`;
282 const completed = status === "ready" && thread.latestRun?.status === "completed";
283 const settled = completed && !monitorHoldsWakeCompletion(rawThread);
284 const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? "");
285 const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null;
286 const state = {
287 raw: rawThread,
288 subagentRequest,
289 thread,
290 status,
291 attention,
292 requestId,
293 settled,
294 completedAt: settled ? completedAt : null,
295 backgroundWake: rawThread.latestRunBackgroundWake === true,
296 };
297 next.set(thread.id, state);
298 changed.push([prior, state]);
299 }
300 entry.reconnecting = false;
301 entry.previous = next;
302 entry.gate.retain(new Set(next.keys()));
303 for (const [prior, state] of changed) {
304 entry.gate.observe(state.thread.id, prior, state, {
305 archived: state.thread.archivedAt !== null,
306 quiet: state.raw.latestRunStopRequested === true,
307 });
308 }
309 };
310
311 const watchEnvironment = (environmentId: EnvironmentId): WatchedEnvironment => {
312 const entry: WatchedEnvironment = {
313 previous: new Map(),
314 reconnecting: false,
315 unsubscribe: () => {},
316 gate: createThreadNotificationGate<ThreadId>((threadId, kind) => {
317 const state = entry.previous.get(threadId);
318 if (state) present(environmentId, state, kind);
319 }),
320 };
321 let threads: ReadonlyArray<OrchestrationV2ThreadShell> | null = null;
322 const unsubscribeShell = registry.subscribe(
323 environmentShell.stateValueAtom(environmentId),
324 (shell) => {
325 threads =
326 shell.status === "live" && Option.isSome(shell.snapshot)
327 ? shell.snapshot.value.threads
328 : null;
329 if (threads !== null) {
330 observeThreads(environmentId, entry, threads);
331 return;
332 }
333 entry.reconnecting = true;
334 entry.gate.pause();
335 },
336 { immediate: true },
337 );
338 const reobserve = () => {
339 if (threads !== null) observeThreads(environmentId, entry, threads);
340 };
341 const unsubscribeRequests = registry.subscribe(
342 environmentThreadShells.pendingSubagentRequestsAtom(environmentId),
343 reobserve,
344 );
345 const unsubscribeDelegated = registry.subscribe(
346 environmentThreadShells.delegatedUnderParentAtom,
347 reobserve,
348 );
349 entry.unsubscribe = () => {
350 unsubscribeShell();
351 unsubscribeRequests();
352 unsubscribeDelegated();
353 entry.gate.clear();
354 };
355 return entry;
356 };
357
358 const syncEnvironments = () => {
359 const { notificationMode, inAppNotificationsEnabled } = getClientSettings();
360 const enabled = notificationMode !== "off" || inAppNotificationsEnabled;
361 if (!enabled) closeToasts(() => true);
362 const environmentIds = enabled ? registry.get(environmentSummaries.environmentIdsAtom) : [];
363 const activeIds = new Set(environmentIds);
364 for (const [environmentId, entry] of watched) {
365 if (activeIds.has(environmentId)) continue;
366 entry.unsubscribe();
367 watched.delete(environmentId);
368 }
369 for (const environmentId of environmentIds) {
370 if (!watched.has(environmentId)) watched.set(environmentId, watchEnvironment(environmentId));
371 }
372 };
373
374 const pruneRemovedEnvironments = () => {
375 const activeIds = new Set(registry.get(environmentSummaries.environmentIdsAtom));
376 const count = pending.size;
377 for (const [tag, entry] of pending) {
378 if (activeIds.has(entry.environmentId)) continue;
379 entry.notification.close();
380 pending.delete(tag);
381 }
382 if (count !== pending.size) setNotificationBadge(pending.size);
383 };
384
385 // Listeners that only exist for some notification modes, rebuilt when the mode changes.
386 let appliedMode: ClientSettings["notificationMode"] | null = null;
387 let stopModeListeners = () => {};
388 const applyMode = () => {
389 const nextMode = getClientSettings().notificationMode;
390 if (nextMode === appliedMode) return;
391 appliedMode = nextMode;
392 stopModeListeners();
393 clearPending();
394 const stops: Array<() => void> = [];
395 if (hasDesktopNotifications(nextMode)) {
396 const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear(clearPending);
397 window.addEventListener("focus", clearPending);
398 stops.push(() => {
399 unsubscribeBadgeClear?.();
400 window.removeEventListener("focus", clearPending);
401 clearPending();
402 });
403 }
404 if (hasNotificationSound(nextMode)) {
405 document.addEventListener("pointerdown", unlockNotificationAudio);
406 document.addEventListener("keydown", unlockNotificationAudio);
407 stops.push(() => {
408 document.removeEventListener("pointerdown", unlockNotificationAudio);
409 document.removeEventListener("keydown", unlockNotificationAudio);
410 });
411 }
412 stopModeListeners = () => {
413 for (const stop of stops) stop();
414 };
415 };
416
417 const onSettings = () => {
418 applyMode();
419 syncEnvironments();
420 };
421 const unsubscribeSettings = subscribeClientSettings(onSettings);
422 const unsubscribeEnvironmentIds = registry.subscribe(
423 environmentSummaries.environmentIdsAtom,
424 () => {
425 pruneRemovedEnvironments();
426 syncEnvironments();
427 },
428 );
429 const unsubscribeHidden = [
430 registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending),
431 registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending),
432 registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending),
433 ];
434 const unsubscribeRoute = router.subscribe("onResolved", closeOpenedThreadToasts);
435 onSettings();
436
437 return () => {
438 unsubscribeSettings();
439 unsubscribeEnvironmentIds();
440 for (const unsubscribe of unsubscribeHidden) unsubscribe();
441 unsubscribeRoute();
442 for (const entry of watched.values()) entry.unsubscribe();
443 watched.clear();
444 stopModeListeners();
445 closeToasts(() => true);
446 };
447}