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

main
ts 136 lines 5.07 KB
Raw
1 import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 import type { ClientSettings } from "@t3tools/contracts/settings";
3 import { msg } from "gt-react";
4
5 import completionUrl from "./assets/notification-completion.mp3";
6 import inputUrl from "./assets/notification-input.mp3";
7
8 type NotificationMode = ClientSettings["notificationMode"];
9 export const NOTIFICATION_MODE_LABELS = {
10 off: msg("Off", { $context: "notification setting, no notifications or sound" }),
11 notifications: msg("Notifications only"),
12 sound: msg("Sound only"),
13 "notifications-and-sound": msg("Notifications with sound"),
14 } satisfies Record<NotificationMode, string>;
15
16 export function hasNotificationSound(mode: NotificationMode) {
17 return mode === "sound" || mode === "notifications-and-sound";
18 }
19
20 export function hasDesktopNotifications(mode: NotificationMode) {
21 return mode === "notifications" || mode === "notifications-and-sound";
22 }
23
24 const TAG_HASH_OFFSET_BASIS = 0xcbf29ce484222325n;
25 const TAG_HASH_PRIME = 0x100000001b3n;
26 const TAG_HASH_MASK = 0xffffffffffffffffn;
27
28 /** Windows drops toast notifications with the 73-character environment/thread tag. */
29 export function threadNotificationTag(environmentId: EnvironmentId, threadId: ThreadId): string {
30 const key = `${environmentId}:${threadId}`;
31 let hash = TAG_HASH_OFFSET_BASIS;
32 for (let index = 0; index < key.length; index += 1) {
33 hash ^= BigInt(key.charCodeAt(index));
34 hash = (hash * TAG_HASH_PRIME) & TAG_HASH_MASK;
35 }
36 return hash.toString(16).padStart(16, "0");
37 }
38
39 let originalFavicon: HTMLLinkElement | undefined;
40 let badgeFavicon: HTMLLinkElement | undefined;
41
42 export function setNotificationBadge(count: number) {
43 const bridge = window.desktopBridge;
44 let image: string | null = null;
45 if (count > 0 && (!bridge || bridge.getClientPlatform() === "win32")) {
46 const canvas = document.createElement("canvas");
47 canvas.width = canvas.height = 64;
48 const context = canvas.getContext("2d");
49 if (context) {
50 context.fillStyle = "#e5484d";
51 context.beginPath();
52 context.arc(32, 32, 28, 0, Math.PI * 2);
53 context.fill();
54 context.fillStyle = "white";
55 context.font = `600 ${count > 9 ? 30 : 40}px "Segoe UI", sans-serif`;
56 context.textAlign = "center";
57 context.textBaseline = "middle";
58 context.fillText(count > 9 ? "9+" : String(count), 32, 34);
59 image = canvas.toDataURL("image/png");
60 }
61 }
62 if (!bridge) {
63 if (image) {
64 if (!badgeFavicon) {
65 originalFavicon = document.querySelector<HTMLLinkElement>('link[rel="icon"]') ?? undefined;
66 badgeFavicon = document.createElement("link");
67 badgeFavicon.rel = "icon";
68 badgeFavicon.type = "image/png";
69 badgeFavicon.sizes.value = "64x64";
70 originalFavicon?.remove();
71 document.head.append(badgeFavicon);
72 }
73 badgeFavicon.href = image;
74 } else if (badgeFavicon) {
75 badgeFavicon.remove();
76 badgeFavicon = undefined;
77 if (originalFavicon) document.head.append(originalFavicon);
78 originalFavicon = undefined;
79 }
80 }
81 void bridge?.setNotificationBadge({ count, image }).catch(() => undefined);
82 }
83
84 let audioContext: AudioContext | undefined;
85 const buffers = new Map<string, Promise<AudioBuffer>>();
86 /** When each sound's current playback ends, on the audio context's clock. */
87 const playingUntil = new Map<string, number>();
88
89 function loadNotificationBuffer(context: AudioContext, url: string): Promise<AudioBuffer> {
90 let buffer = buffers.get(url);
91 if (!buffer) {
92 buffer = fetch(url)
93 .then((response) => response.arrayBuffer())
94 .then((data) => context.decodeAudioData(data))
95 .catch((error: unknown) => {
96 buffers.delete(url);
97 throw error;
98 });
99 buffers.set(url, buffer);
100 }
101 return buffer;
102 }
103
104 /** Called from a gesture so browsers allow later background playback. */
105 export function unlockNotificationAudio() {
106 const firstUnlock = audioContext === undefined;
107 audioContext ??= new AudioContext();
108 void audioContext.resume().catch(() => undefined);
109 if (!firstUnlock) return;
110 // Fetch and decode during interaction so the first alert is ready when the thread finishes.
111 for (const url of [completionUrl, inputUrl]) {
112 void loadNotificationBuffer(audioContext, url).catch(() => undefined);
113 }
114 }
115
116 export async function playNotificationSound(
117 kind: "completion" | "input",
118 shouldPlay: () => boolean,
119 ) {
120 if (!audioContext || audioContext.state !== "running") return;
121 const context = audioContext;
122 const url = kind === "completion" ? completionUrl : inputUrl;
123 try {
124 const decoded = await loadNotificationBuffer(context, url);
125 if (!shouldPlay() || context.state !== "running") return;
126 // Coalesce same-sound bursts after decode to avoid clipping; input and completion alerts keep separate slots.
127 if (context.currentTime < (playingUntil.get(url) ?? 0)) return;
128 const source = context.createBufferSource();
129 source.buffer = decoded;
130 source.connect(context.destination);
131 source.start();
132 playingUntil.set(url, context.currentTime + decoded.duration);
133 } catch {
134 // A failed load is retried on the next alert.
135 }
136 }