The best way to control Claude Code, Codex and more from any computer or phone

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