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

ThreadNotificationCoordinator.tsx

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