Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadNotificationCoordinator.tsx

252 lines9.0 KB

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