Open History to see the last commit
1import {
2 type PendingSubagentRequest,
3 presentThreadShell,
4} from "@t3tools/client-runtime/state/models";
5import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads";
6import { useAtomValue } from "@effect/atom-react";
7import { useNavigate, useParams } from "@tanstack/react-router";
8import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
9import * as Option from "effect/Option";
10import {
11 CircleAlertIcon,
12 CircleCheckIcon,
13 MessageCircleQuestionIcon,
14 ShieldQuestionIcon,
15} from "lucide-react";
16import { useEffect, useRef } from "react";
17
18import { getClientSettings, useClientSettings } from "../hooks/useSettings";
19import { useEnvironmentIds } from "../state/environments";
20import { environmentShell } from "../state/shell";
21import {
22 hasDesktopNotifications,
23 hasNotificationSound,
24 playNotificationSound,
25 setNotificationBadge,
26 unlockNotificationAudio,
27} from "../threadNotifications";
28import { resolveSidebarThreadStatus } from "./Sidebar.logic";
29import { toastManager } from "./ui/toast";
30
31export function ThreadNotificationCoordinator() {
32 const environmentIds = useEnvironmentIds();
33 const mode = useClientSettings((settings) => settings.notificationMode);
34 const inAppNotificationsEnabled = useClientSettings(
35 (settings) => settings.inAppNotificationsEnabled,
36 );
37 const pending = useRef(
38 new Map<string, { environmentId: EnvironmentId; notification: Notification }>(),
39 );
40 const onNotification = (environmentId: EnvironmentId, notification: Notification) => {
41 pending.current.get(notification.tag)?.notification.close();
42 pending.current.set(notification.tag, { environmentId, notification });
43 setNotificationBadge(pending.current.size);
44 };
45
46 useEffect(() => {
47 const activeIds = new Set(environmentIds);
48 const count = pending.current.size;
49 for (const [tag, entry] of pending.current) {
50 if (activeIds.has(entry.environmentId)) continue;
51 entry.notification.close();
52 pending.current.delete(tag);
53 }
54 if (count !== pending.current.size) setNotificationBadge(pending.current.size);
55 }, [environmentIds]);
56
57 useEffect(() => {
58 const clear = () => {
59 for (const { notification } of pending.current.values()) notification.close();
60 pending.current.clear();
61 setNotificationBadge(0);
62 };
63 clear();
64 if (!hasDesktopNotifications(mode)) return;
65 const unsubscribe = window.desktopBridge?.onNotificationBadgeClear?.(clear);
66 window.addEventListener("focus", clear);
67 return () => {
68 unsubscribe?.();
69 window.removeEventListener("focus", clear);
70 clear();
71 };
72 }, [mode]);
73
74 useEffect(() => {
75 if (!hasNotificationSound(mode)) return;
76 document.addEventListener("pointerdown", unlockNotificationAudio);
77 document.addEventListener("keydown", unlockNotificationAudio);
78 return () => {
79 document.removeEventListener("pointerdown", unlockNotificationAudio);
80 document.removeEventListener("keydown", unlockNotificationAudio);
81 };
82 }, [mode]);
83
84 if (mode === "off" && !inAppNotificationsEnabled) return null;
85
86 return environmentIds.map((environmentId) => (
87 <EnvironmentNotifications
88 key={environmentId}
89 environmentId={environmentId}
90 onNotification={onNotification}
91 />
92 ));
93}
94
95interface NotificationState {
96 readonly raw: OrchestrationV2ThreadShell;
97 readonly subagentRequest: PendingSubagentRequest | null;
98 readonly attention: string | null;
99 readonly completion: number | null;
100}
101
102function EnvironmentNotifications({
103 environmentId,
104 onNotification,
105}: {
106 environmentId: EnvironmentId;
107 onNotification: (environmentId: EnvironmentId, notification: Notification) => void;
108}) {
109 const shell = useAtomValue(environmentShell.stateValueAtom(environmentId));
110 const threads =
111 shell.status === "live" && Option.isSome(shell.snapshot) ? shell.snapshot.value.threads : null;
112 const mode = useClientSettings((settings) => settings.notificationMode);
113 const inAppNotificationsEnabled = useClientSettings(
114 (settings) => settings.inAppNotificationsEnabled,
115 );
116 const navigate = useNavigate();
117 const { environmentId: activeEnvironmentId, threadId: activeThreadId } = useParams({
118 strict: false,
119 });
120 const previous = useRef(new Map<ThreadId, NotificationState>());
121
122 useEffect(() => {
123 if (threads === null) {
124 previous.current.clear();
125 return;
126 }
127 const next = new Map<ThreadId, NotificationState>();
128 const subagentRequests = pendingSubagentRequestsByThread(threads);
129 for (const rawThread of threads) {
130 if (rawThread.lineage.relationshipToParent === "subagent") continue;
131 const prior = previous.current.get(rawThread.id);
132 const subagentRequest = subagentRequests.get(rawThread.id) ?? null;
133 if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) {
134 next.set(rawThread.id, prior);
135 continue;
136 }
137 const thread = presentThreadShell(environmentId, rawThread, subagentRequest);
138 let status = resolveSidebarThreadStatus(thread);
139 if (status === "ready" && thread.latestRun?.status === "failed") status = "failed";
140 const attention =
141 status === "input" || status === "approval" || status === "failed" || status === "limited"
142 ? `${thread.latestRun?.runId ?? ""}:${status}`
143 : null;
144 const completedAt = Date.parse(thread.latestRun?.completedAt ?? "");
145 const completion =
146 status === "ready" &&
147 thread.latestRun?.status === "completed" &&
148 Number.isFinite(completedAt)
149 ? completedAt
150 : (prior?.completion ?? null);
151 next.set(thread.id, { raw: rawThread, subagentRequest, attention, completion });
152 if (!prior || thread.archivedAt !== null) continue;
153 const kind =
154 attention && attention !== prior.attention
155 ? "input"
156 : completion !== null && (prior.completion === null || completion > prior.completion)
157 ? "completion"
158 : null;
159 if (!kind) continue;
160 const title =
161 kind === "completion"
162 ? "Thread completed"
163 : status === "approval"
164 ? "Approval needed"
165 : status === "limited"
166 ? "Usage limit reached"
167 : status === "failed"
168 ? "Thread failed"
169 : "Input needed";
170 if (hasNotificationSound(mode)) {
171 void playNotificationSound(kind, () =>
172 hasNotificationSound(getClientSettings().notificationMode),
173 );
174 }
175 if (
176 inAppNotificationsEnabled &&
177 document.visibilityState === "visible" &&
178 document.hasFocus() &&
179 (activeEnvironmentId !== environmentId || activeThreadId !== thread.id)
180 ) {
181 const toastId = toastManager.add({
182 type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
183 title,
184 description: thread.title,
185 data: {
186 hideCopyButton: true,
187 leadingIcon:
188 kind === "completion" ? (
189 <CircleCheckIcon aria-hidden className="size-4 text-success-foreground" />
190 ) : status === "approval" ? (
191 <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
192 ) : status === "failed" ? (
193 <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
194 ) : (
195 <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
196 ),
197 },
198 actionProps: {
199 children: "Open thread",
200 onClick: () => {
201 toastManager.close(toastId);
202 void navigate({
203 to: "/$environmentId/$threadId",
204 params: { environmentId, threadId: thread.id },
205 });
206 },
207 },
208 });
209 continue;
210 }
211 if (
212 !hasDesktopNotifications(mode) ||
213 (document.visibilityState === "visible" && document.hasFocus()) ||
214 typeof Notification === "undefined" ||
215 Notification.permission !== "granted"
216 )
217 continue;
218 try {
219 const notification = new Notification(title, {
220 body: thread.title,
221 tag: `${environmentId}:${thread.id}`,
222 silent: true,
223 });
224 onNotification(environmentId, notification);
225 notification.addEventListener("click", () => {
226 notification.close();
227 window.focus();
228 void navigate({
229 to: "/$environmentId/$threadId",
230 params: { environmentId, threadId: thread.id },
231 });
232 });
233 } catch {
234 // Some browsers expose Notification but reject desktop presentation.
235 }
236 }
237 previous.current = next;
238 }, [
239 activeEnvironmentId,
240 activeThreadId,
241 environmentId,
242 inAppNotificationsEnabled,
243 mode,
244 navigate,
245 onNotification,
246 threads,
247 ]);
248
249 return null;
250}