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

ThreadNotificationCoordinator.tsx

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