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

ThreadNotificationCoordinator.tsx

428 lines15.7 KB

1import {
2 type EnvironmentThreadShell,
3 type PendingSubagentRequest,
4 presentThreadShell,
5} from "@t3tools/client-runtime/state/models";
6import { isShownUnderParent } from "@t3tools/client-runtime/state/threads";
7import type { AnyRouter } from "@tanstack/react-router";
8import { threadKey } from "@t3tools/client-runtime/state/entities";
9import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
10import { monitorHoldsWakeCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
11import type { ClientSettings } from "@t3tools/contracts/settings";
12import * as Option from "effect/Option";
13import type { AtomRegistry } from "effect/reactivity";
14import {
15 CircleAlertIcon,
16 CircleCheckIcon,
17 MessageCircleQuestionIcon,
18 ShieldQuestionIcon,
19} from "lucide-react";
20​
21import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings";
22import { isWindowsPlatform } from "../lib/utils";
23import { environmentSummaries } from "../state/presentation";
24import { environmentShell } from "../state/shell";
25import { environmentThreadShells } from "../state/threads";
26import {
27 hasDesktopNotifications,
28 hasNotificationSound,
29 playNotificationSound,
30 setNotificationBadge,
31 threadNotificationTag,
32 unlockNotificationAudio,
33} from "../threadNotifications";
34import { resolveBackgroundThreadRequest } from "./backgroundThreadAnnouncement";
35import { resolveSidebarThreadStatus, type SidebarThreadStatus } from "./Sidebar.logic";
36import {
37 createThreadNotificationGate,
38 type ThreadNotificationKind,
39 type ThreadNotificationObservation,
40} from "./ThreadNotificationCoordinator.logic";
41import { toastManager } from "./ui/toast";
42​
43interface NotificationState extends ThreadNotificationObservation {
44 readonly raw: OrchestrationV2ThreadShell;
45 readonly subagentRequest: PendingSubagentRequest | null;
46 readonly thread: EnvironmentThreadShell;
47 readonly status: SidebarThreadStatus;
49​
50type ToastId = ReturnType<typeof toastManager.add>;
51​
52interface WatchedEnvironment {
53 unsubscribe: () => void;
54 previous: Map<ThreadId, NotificationState>;
55 reconnecting: boolean;
56 readonly gate: ReturnType<typeof createThreadNotificationGate<ThreadId>>;
58​
59/**
60 * Turns thread status transitions in every connected environment into sounds, in-app toasts,
61 * and desktop notifications, and keeps the dock badge in step with the unread ones.
62 */
63export function startThreadNotifications(
64 registry: AtomRegistry.AtomRegistry,
65 router: AnyRouter,
66): () => void {
67 const pending = new Map<
68 string,
69 { environmentId: EnvironmentId; threadId: ThreadId; notification: Notification }
70 >();
71 const watched = new Map<EnvironmentId, WatchedEnvironment>();
72​
73 const trackNotification = (
74 environmentId: EnvironmentId,
75 threadId: ThreadId,
76 notification: Notification,
77 ) => {
78 pending.get(notification.tag)?.notification.close();
79 pending.set(notification.tag, { environmentId, threadId, notification });
80 setNotificationBadge(pending.size);
81 };
82 // Toast ids by thread key, so hiding a thread can close its open toasts.
83 const openToasts = new Map<string, Array<ToastId>>();
84 const forgetToast = (key: string, toastId: ToastId) => {
85 const remaining = (openToasts.get(key) ?? []).filter((id) => id !== toastId);
86 if (remaining.length === 0) openToasts.delete(key);
87 else openToasts.set(key, remaining);
88 };
89 // A notification shown before the tag filter turned on must not stay on screen. While hiding,
90 // one whose thread left the live list (archived) cannot be judged, so it closes too.
91 const closeHiddenPending = () => {
92 const hidden = registry.get(environmentThreadShells.hiddenThreadKeysAtom);
93 const live = registry.get(environmentThreadShells.anyEnvironmentHidingAtom)
94 ? new Set(registry.get(environmentThreadShells.threadRefsAtom).map(threadKey))
95 : null;
96 const shouldClose = (key: string) => hidden.has(key) || (live !== null && !live.has(key));
97 for (const [key, toastIds] of openToasts) {
98 if (!shouldClose(key)) continue;
99 for (const toastId of toastIds) toastManager.close(toastId);
100 openToasts.delete(key);
101 }
102 const count = pending.size;
103 for (const [tag, entry] of pending) {
104 if (!shouldClose(threadKey(entry))) continue;
105 entry.notification.close();
106 pending.delete(tag);
107 }
108 if (count !== pending.size) setNotificationBadge(pending.size);
109 };
110 const clearPending = () => {
111 for (const { notification } of pending.values()) notification.close();
112 pending.clear();
113 setNotificationBadge(0);
114 };
115​
116 const present = (
117 environmentId: EnvironmentId,
118 state: NotificationState,
119 kind: ThreadNotificationKind,
120 ) => {
121 const { thread, status } = state;
122 if (
123 registry
124 .get(environmentThreadShells.hiddenThreadKeysAtom)
125 .has(threadKey({ environmentId, threadId: thread.id }))
126 )
127 return;
128 const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();
129 const active = (router.state.matches.at(-1)?.params ?? {}) as {
130 environmentId?: string;
131 threadId?: string;
132 };
133 const title =
134 kind === "completion"
135 ? "Thread completed"
136 : status === "approval"
137 ? "Approval needed"
138 : status === "limited"
139 ? "Usage limit reached"
140 : status === "failed"
141 ? "Thread failed"
142 : status === "request"
143 ? "Guest request"
144 : "Input needed";
145 if (hasNotificationSound(mode)) {
146 void playNotificationSound(kind, () =>
147 hasNotificationSound(getClientSettings().notificationMode),
148 );
149 }
150 if (
151 inAppNotificationsEnabled &&
152 document.visibilityState === "visible" &&
153 document.hasFocus() &&
154 (active.environmentId !== environmentId || active.threadId !== thread.id)
155 ) {
156 const toastKey = threadKey({ environmentId, threadId: thread.id });
157 const toastId: ToastId = toastManager.add({
158 onRemove: (): void => forgetToast(toastKey, toastId),
159 type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
160 title,
161 description: thread.title,
162 data: {
163 hideCopyButton: true,
164 leadingIcon:
165 kind === "completion" ? (
166 <CircleCheckIcon aria-hidden className="size-4 text-success-foreground" />
167 ) : status === "approval" ? (
168 <ShieldQuestionIcon aria-hidden className="size-4 text-warning-foreground" />
169 ) : status === "limited" ? (
170 <CircleAlertIcon aria-hidden className="size-4 text-warning-foreground" />
171 ) : status === "failed" ? (
172 <CircleAlertIcon aria-hidden className="size-4 text-destructive-foreground" />
173 ) : (
174 <MessageCircleQuestionIcon aria-hidden className="size-4 text-info-foreground" />
175 ),
176 },
177 actionProps: {
178 children: "Open thread",
179 onClick: () => {
180 toastManager.close(toastId);
181 void router.navigate({
182 to: "/$environmentId/$threadId",
183 params: { environmentId, threadId: thread.id },
184 });
185 },
186 },
187 });
188 openToasts.set(toastKey, [...(openToasts.get(toastKey) ?? []), toastId]);
189 return;
190 }
191 if (
192 !hasDesktopNotifications(mode) ||
193 (document.visibilityState === "visible" && document.hasFocus()) ||
194 typeof Notification === "undefined" ||
195 Notification.permission !== "granted"
196 )
197 return;
198 try {
199 const notification = new Notification(title, {
200 body: thread.title,
201 tag: threadNotificationTag(environmentId, thread.id),
202 silent: true,
203 // Windows drops clicks after a toast moves into Notification Center.
204 requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),
205 });
206 trackNotification(environmentId, thread.id, notification);
207 notification.addEventListener("click", () => {
208 notification.close();
209 window.focus();
210 void window.desktopBridge?.revealWindow().catch(() => undefined);
211 void router.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​
221 const observeThreads = (
222 environmentId: EnvironmentId,
223 entry: WatchedEnvironment,
224 threads: ReadonlyArray<OrchestrationV2ThreadShell>,
225 ) => {
226 const previous = entry.previous;
227 const next = new Map<ThreadId, NotificationState>();
228 // A parent here also hears of what its tasks on linked environments ask.
229 const subagentRequests = registry.get(
230 environmentThreadShells.pendingSubagentRequestsAtom(environmentId),
231 );
232 const delegatedUnderParent = registry.get(environmentThreadShells.delegatedUnderParentAtom);
233 const changed: Array<[NotificationState | undefined, NotificationState]> = [];
234 for (const rawThread of threads) {
235 if (
236 isShownUnderParent(
237 { environmentId, threadId: rawThread.id },
238 rawThread.lineage,
239 delegatedUnderParent,
240 )
241 ) {
242 continue;
243 }
244 const prior = previous.get(rawThread.id);
245 const subagentRequest = subagentRequests.get(rawThread.id) ?? null;
246 if (
247 !entry.reconnecting &&
248 prior?.raw === rawThread &&
249 prior.subagentRequest === subagentRequest
250 ) {
251 next.set(rawThread.id, prior);
252 continue;
253 }
254 const thread = presentThreadShell(environmentId, rawThread, subagentRequest);
255 let status = resolveSidebarThreadStatus(thread);
256 if (status === "ready" && thread.latestRun?.status === "failed") status = "failed";
257 const needsAttention =
258 status === "input" ||
259 status === "request" ||
260 status === "approval" ||
261 status === "failed" ||
262 status === "limited";
263 const requestId = needsAttention ? resolveBackgroundThreadRequest(thread).requestId : null;
264 const attention = needsAttention
265 ? `${thread.latestRun?.runId ?? ""}:${status}:${requestId ?? ""}`
266 : null;
267 const completed = status === "ready" && thread.latestRun?.status === "completed";
268 const settled = completed && !monitorHoldsWakeCompletion(rawThread);
269 const parsedCompletedAt = Date.parse(thread.latestRun?.completedAt ?? "");
270 const completedAt = Number.isFinite(parsedCompletedAt) ? parsedCompletedAt : null;
271 const state = {
272 raw: rawThread,
273 subagentRequest,
274 thread,
275 status,
276 attention,
277 requestId,
278 settled,
279 completedAt: settled ? completedAt : null,
280 backgroundWake: rawThread.latestRunBackgroundWake === true,
281 };
282 next.set(thread.id, state);
283 changed.push([prior, state]);
284 }
285 entry.reconnecting = false;
286 entry.previous = next;
287 entry.gate.retain(new Set(next.keys()));
288 for (const [prior, state] of changed) {
289 entry.gate.observe(state.thread.id, prior, state, {
290 archived: state.thread.archivedAt !== null,
291 quiet: state.raw.latestRunStopRequested === true,
292 });
293 }
294 };
295​
296 const watchEnvironment = (environmentId: EnvironmentId): WatchedEnvironment => {
297 const entry: WatchedEnvironment = {
298 previous: new Map(),
299 reconnecting: false,
300 unsubscribe: () => {},
301 gate: createThreadNotificationGate<ThreadId>((threadId, kind) => {
302 const state = entry.previous.get(threadId);
303 if (state) present(environmentId, state, kind);
304 }),
305 };
306 let threads: ReadonlyArray<OrchestrationV2ThreadShell> | null = null;
307 const unsubscribeShell = registry.subscribe(
308 environmentShell.stateValueAtom(environmentId),
309 (shell) => {
310 threads =
311 shell.status === "live" && Option.isSome(shell.snapshot)
312 ? shell.snapshot.value.threads
313 : null;
314 if (threads !== null) {
315 observeThreads(environmentId, entry, threads);
316 return;
317 }
318 entry.reconnecting = true;
319 entry.gate.pause();
320 },
321 { immediate: true },
322 );
323 const reobserve = () => {
324 if (threads !== null) observeThreads(environmentId, entry, threads);
325 };
326 const unsubscribeRequests = registry.subscribe(
327 environmentThreadShells.pendingSubagentRequestsAtom(environmentId),
328 reobserve,
329 );
330 const unsubscribeDelegated = registry.subscribe(
331 environmentThreadShells.delegatedUnderParentAtom,
332 reobserve,
333 );
334 entry.unsubscribe = () => {
335 unsubscribeShell();
336 unsubscribeRequests();
337 unsubscribeDelegated();
338 entry.gate.clear();
339 };
340 return entry;
341 };
342​
343 const syncEnvironments = () => {
344 const { notificationMode, inAppNotificationsEnabled } = getClientSettings();
345 const enabled = notificationMode !== "off" || inAppNotificationsEnabled;
346 const environmentIds = enabled ? registry.get(environmentSummaries.environmentIdsAtom) : [];
347 const activeIds = new Set(environmentIds);
348 for (const [environmentId, entry] of watched) {
349 if (activeIds.has(environmentId)) continue;
350 entry.unsubscribe();
351 watched.delete(environmentId);
352 }
353 for (const environmentId of environmentIds) {
354 if (!watched.has(environmentId)) watched.set(environmentId, watchEnvironment(environmentId));
355 }
356 };
357​
358 const pruneRemovedEnvironments = () => {
359 const activeIds = new Set(registry.get(environmentSummaries.environmentIdsAtom));
360 const count = pending.size;
361 for (const [tag, entry] of pending) {
362 if (activeIds.has(entry.environmentId)) continue;
363 entry.notification.close();
364 pending.delete(tag);
365 }
366 if (count !== pending.size) setNotificationBadge(pending.size);
367 };
368​
369 // Listeners that only exist for some notification modes, rebuilt when the mode changes.
370 let appliedMode: ClientSettings["notificationMode"] | null = null;
371 let stopModeListeners = () => {};
372 const applyMode = () => {
373 const nextMode = getClientSettings().notificationMode;
374 if (nextMode === appliedMode) return;
375 appliedMode = nextMode;
376 stopModeListeners();
377 clearPending();
378 const stops: Array<() => void> = [];
379 if (hasDesktopNotifications(nextMode)) {
380 const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear(clearPending);
381 window.addEventListener("focus", clearPending);
382 stops.push(() => {
383 unsubscribeBadgeClear?.();
384 window.removeEventListener("focus", clearPending);
385 clearPending();
386 });
387 }
388 if (hasNotificationSound(nextMode)) {
389 document.addEventListener("pointerdown", unlockNotificationAudio);
390 document.addEventListener("keydown", unlockNotificationAudio);
391 stops.push(() => {
392 document.removeEventListener("pointerdown", unlockNotificationAudio);
393 document.removeEventListener("keydown", unlockNotificationAudio);
394 });
395 }
396 stopModeListeners = () => {
397 for (const stop of stops) stop();
398 };
399 };
400​
401 const onSettings = () => {
402 applyMode();
403 syncEnvironments();
404 };
405 const unsubscribeSettings = subscribeClientSettings(onSettings);
406 const unsubscribeEnvironmentIds = registry.subscribe(
407 environmentSummaries.environmentIdsAtom,
408 () => {
409 pruneRemovedEnvironments();
410 syncEnvironments();
411 },
412 );
413 const unsubscribeHidden = [
414 registry.subscribe(environmentThreadShells.hiddenThreadKeysAtom, closeHiddenPending),
415 registry.subscribe(environmentThreadShells.anyEnvironmentHidingAtom, closeHiddenPending),
416 registry.subscribe(environmentThreadShells.threadRefsAtom, closeHiddenPending),
417 ];
418 onSettings();
419​
420 return () => {
421 unsubscribeSettings();
422 unsubscribeEnvironmentIds();
423 for (const unsubscribe of unsubscribeHidden) unsubscribe();
424 for (const entry of watched.values()) entry.unsubscribe();
425 watched.clear();
426 stopModeListeners();
427 };