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