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