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 aria-hidden className="size-4 text-success-foreground" />
168 ) : status === "approval" ? (
169 <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
170 ) : status === "failed" ? (
171 <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
172 ) : (
173 <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
174 ),
175 },
176 actionProps: {
177 children: "Open thread",
178 onClick: () => {
179 toastManager.close(toastId);
180 void navigate({
181 to: "/$environmentId/$threadId",
182 params: { environmentId, threadId: thread.id },
183 });
184 },
185 },
186 });
187 continue;
188 }
189 if (
190 !hasDesktopNotifications(mode) ||
191 (document.visibilityState === "visible" && document.hasFocus()) ||
192 typeof Notification === "undefined" ||
193 Notification.permission !== "granted"
194 )
195 continue;
196 try {
197 const notification = new Notification(title, {
198 body: thread.title,
199 tag: `${environmentId}:${thread.id}`,
200 silent: true,
201 });
202 onNotification(environmentId, notification);
203 notification.addEventListener("click", () => {
204 notification.close();
205 window.focus();
206 void navigate({
207 to: "/$environmentId/$threadId",
208 params: { environmentId, threadId: thread.id },
209 });
210 });
211 } catch {
212 // Some browsers expose Notification but reject desktop presentation.
213 }
214 }
215 previous.current = next;
216 }, [
217 activeEnvironmentId,
218 activeThreadId,
219 environmentId,
220 inAppNotificationsEnabled,
221 mode,
222 navigate,
223 onNotification,
224 shell,
225 ]);
226
227 return null;
228}