@devries-cameron20 / t3code-1 / commits / a852de0b7b
Fork 0

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

fix(web): play completion sounds without delay (#29146)

Completion alerts waited two seconds after the client received a completed thread state. Audio was also fetched and decoded only when an alert needed to play, adding a first-play delay. Notify immediately when the thread shell reports completion, and preload both sounds when a user gesture unlocks audio. Keep completion deduplication and suppression for existing, archived, and stopped runs. This intentionally removes the continuation grace for completion alerts. A completed run can now notify before an automatic continuation starts. The sidebar's two-second placement grace and server settlement behavior remain in place. Validation: `vp run check:changed` passes after merging current main, including 40 affected tests, formatting, lint, unused-code checks, affected typechecks, and React compiler checks. Tests cover immediate completion, duplicate suppression across reconnects, preloaded audio reuse, and retrying failed loads on alerts without retrying on every gesture. Audible timing has not been verified in a live client. Model: GPT 6.1 Sol. Harness: Codex through T3 Code.

Yash Singh committed Nov 2, 2026 at 02:05 UTC a852de0b7b8bc241e036e9a3b5c0c080418b114a
7 files changed +100 -191
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts
+12 -26
@@ -1,4 +1,3 @@
1 -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
1 import type { AnyRouter } from "@tanstack/react-router";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import * as DateTime from "effect/DateTime";
@@ -6,7 +5,7 @@ import * as Option from "effect/Option";
5 import { Atom, AtomRegistry } from "effect/reactivity";
6 import { expect, it, vi } from "vite-plus/test";
7
9 -import { fakeTimers, stubGlobal } from "../../test/render";
8 +import { stubGlobal } from "../../test/render";
9
10 const state = vi.hoisted(() => ({
11 mode: "notifications",
@@ -241,24 +240,18 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
240 },
241 );
242
244 -it("holds a completion through a continuation gap and notifies once it settles", async () => {
243 +it("presents completion notifications and sound as soon as the shell completes", async () => {
244 await using app = setup();
245 + state.mode = "notifications-and-sound";
246 app.start();
247 - using _timers = fakeTimers();
248 - const finished = (turnId: string, completedAt: string) => ({
249 - latestTurn: { turnId, state: "completed", completedAt },
250 - });
251 - state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z")));
247 state.shells.set(
248 "one",
254 - shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }),
249 + shell({
250 + latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:00:01.000Z" },
251 + }),
252 );
256 - state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z")));
257 - expect(TestNotification.sent).toEqual([]);
258 - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1);
259 - expect(TestNotification.sent).toEqual([]);
260 - await vi.advanceTimersByTimeAsync(1);
253 expect(TestNotification.sent.map((sent) => sent.title)).toEqual(["Thread completed"]);
254 + expect(state.sound).toHaveBeenCalledWith("completion", expect.any(Function));
255 });
256
257 it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
@@ -277,7 +270,6 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
270 };
271 state.shells.set("one", shell({ id: "working" }, { id: "asking" }, { id: "offline" }, done));
272 app.start();
280 - using _timers = fakeTimers();
273 state.shells.set("one", shell({ id: "working" }, asking, { id: "offline" }, done));
274 state.shells.set("one", {
275 ...shell({ id: "working" }, asking, { id: "offline" }, done),
@@ -296,37 +288,31 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
288
289 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
290 "Approval needed",
291 + "Thread completed",
292 flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
293 ]);
301 - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
294 state.shells.set("one", { ...shell(completed, asking, offline, done), status: "cached" });
295 state.shells.set("one", shell(completed, asking, offline, done));
304 - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
296 expect(TestNotification.sent.map(({ title }) => title)).toEqual([
297 "Approval needed",
307 - flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
298 "Thread completed",
299 + flag === "hasPendingApprovals" ? "Approval needed" : "Input needed",
300 ]);
301 },
302 );
303
304 it.each([false, true])(
314 - "rechecks a pending completion after reconnect (continued: %s)",
305 + "does not replay a notified completion after reconnect (continued: %s)",
306 async (continued) => {
307 await using app = setup();
308 app.start();
318 - using _timers = fakeTimers();
309 const completed = shell({
310 latestTurn: { turnId: "turn", state: "completed", completedAt: "2026-09-13T07:05:00.000Z" },
311 });
312 state.shells.set("one", completed);
313 state.shells.set("one", { ...completed, status: "cached" });
324 - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
325 - expect(TestNotification.sent).toEqual([]);
314 + expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]);
315 state.shells.set("one", continued ? shell() : completed);
327 - await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS);
328 - expect(TestNotification.sent.map(({ title }) => title)).toEqual(
329 - continued ? [] : ["Thread completed"],
330 - );
316 + expect(TestNotification.sent.map(({ title }) => title)).toEqual(["Thread completed"]);
317 },
318 );
apps/web/src/components/ThreadNotificationCoordinator.logic.test.ts
+37 -117
@@ -1,5 +1,4 @@
1 -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
1 +import { describe, expect, it, vi } from "vite-plus/test";
2
3 import {
4 createThreadNotificationGate,
@@ -30,164 +29,85 @@ function harness() {
29 }
30
31 describe("createThreadNotificationGate", () => {
33 - beforeEach(() => {
34 - vi.useFakeTimers();
35 - });
36 - afterEach(() => {
37 - vi.useRealTimers();
38 - });
39 -
40 - it("drops a completion when the thread resumes within the grace", () => {
41 - const { notify, observe } = harness();
42 - observe(working);
43 - observe(completed(1));
44 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1);
45 - observe(working);
46 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
47 - expect(notify).not.toHaveBeenCalled();
48 - });
49 -
50 - it("notifies a real completion once after the grace", () => {
32 + it("notifies a completion immediately and only once", () => {
33 const { notify, observe } = harness();
34 observe(working);
35 observe(completed(1));
54 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS - 1);
55 - expect(notify).not.toHaveBeenCalled();
56 - vi.advanceTimersByTime(1);
36 expect(notify.mock.calls).toEqual([["thread", "completion"]]);
37 observe({ ...completed(1) });
59 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
60 - expect(notify).toHaveBeenCalledTimes(1);
61 - });
62 -
63 - it("notifies attention at once and replaces a pending completion", () => {
64 - const { notify, observe } = harness();
38 observe(working);
39 observe(completed(1));
67 - vi.advanceTimersByTime(500);
68 - observe({ attention: "run-1:approval", settled: false, completedAt: null });
69 - expect(notify.mock.calls).toEqual([["thread", "input"]]);
70 - vi.advanceTimersByTime(60_000);
71 - // The request resolves and the same run reads as completed again.
72 - observe(completed(1));
73 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
74 - expect(notify.mock.calls).toEqual([["thread", "input"]]);
40 + expect(notify).toHaveBeenCalledTimes(1);
41 });
42
77 - it("notifies one completion across continuation gaps", () => {
43 + it("notifies each newer completion immediately", () => {
44 const { notify, observe } = harness();
45 observe(working);
46 observe(completed(1));
81 - vi.advanceTimersByTime(300);
47 observe(working);
83 - vi.advanceTimersByTime(5_000);
48 observe(completed(2));
85 - vi.advanceTimersByTime(300);
86 - observe(working);
87 - vi.advanceTimersByTime(5_000);
88 - observe(completed(3));
89 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
90 - expect(notify.mock.calls).toEqual([["thread", "completion"]]);
49 + expect(notify.mock.calls).toEqual([
50 + ["thread", "completion"],
51 + ["thread", "completion"],
52 + ]);
53 + observe(completed(1));
54 + expect(notify).toHaveBeenCalledTimes(2);
55 });
56
93 - it("keeps a completion interrupted by attention after a working gap from firing", () => {
57 + it("notifies attention once and still notifies the subsequent completion", () => {
58 const { notify, observe } = harness();
59 observe(working);
96 - observe(completed(1));
97 - vi.advanceTimersByTime(500);
60 + const attention = { attention: "run-1:approval", settled: false, completedAt: null };
61 + observe(attention);
62 + expect(notify.mock.calls).toEqual([["thread", "input"]]);
63 + observe({ ...attention });
64 + expect(notify).toHaveBeenCalledTimes(1);
65 observe(working);
99 - observe({ attention: "run-1:approval", settled: false, completedAt: null });
100 - vi.advanceTimersByTime(60_000);
66 observe(completed(1));
102 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
103 - expect(notify.mock.calls).toEqual([["thread", "input"]]);
67 + expect(notify.mock.calls).toEqual([
68 + ["thread", "input"],
69 + ["thread", "completion"],
70 + ]);
71 });
72
106 - it("adds nothing when attention follows a completion that already fired", () => {
73 + it("does not replay a completion after attention resolves", () => {
74 const { notify, observe } = harness();
75 observe(working);
76 observe(completed(1));
110 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
77 observe({ attention: "run-1:limited", settled: false, completedAt: null });
78 observe(completed(1));
113 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
79 expect(notify.mock.calls).toEqual([
80 ["thread", "completion"],
81 ["thread", "input"],
82 ]);
83 });
84
120 - it("still notifies a newer completion after attention", () => {
85 + it("never notifies existing, archived or stopped completions, including when unarchived", () => {
86 const { notify, observe } = harness();
122 - observe(working);
87 observe(completed(1));
124 - vi.advanceTimersByTime(500);
125 - observe({ attention: "run-2:approval", settled: false, completedAt: null });
88 observe(working);
89 + observe(completed(2), { ...visible, quiet: true });
90 observe(completed(2));
128 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
129 - expect(notify.mock.calls).toEqual([
130 - ["thread", "input"],
131 - ["thread", "completion"],
132 - ]);
133 - });
134 -
135 - it("ignores unrelated updates while a completion waits", () => {
136 - const { notify, observe } = harness();
91 observe(working);
138 - observe(completed(1));
139 - vi.advanceTimersByTime(1_500);
140 - observe({ ...completed(1) });
141 - vi.advanceTimersByTime(500);
142 - expect(notify).toHaveBeenCalledTimes(1);
143 - });
144 -
145 - it("notifies a run that settles again after a brief runtime blip", () => {
146 - const { notify, observe } = harness();
147 - observe(working);
148 - observe(completed(1));
149 - vi.advanceTimersByTime(500);
92 + observe(completed(3), { ...visible, archived: true });
93 + observe(completed(3));
94 + expect(notify).not.toHaveBeenCalled();
95 observe(working);
151 - observe(completed(1));
152 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS);
96 + observe(completed(4));
97 expect(notify.mock.calls).toEqual([["thread", "completion"]]);
98 });
99
156 - it("restarts the grace when a newer completion replaces a pending one", () => {
157 - const { notify, observe } = harness();
158 - observe(working);
159 - observe(completed(1));
160 - vi.advanceTimersByTime(1_500);
161 - observe(completed(2));
162 - vi.advanceTimersByTime(1_500);
163 - expect(notify).not.toHaveBeenCalled();
164 - vi.advanceTimersByTime(500);
165 - expect(notify).toHaveBeenCalledTimes(1);
166 - });
167 -
168 - it("drops a pending completion on archive, stop request, removal or clear", () => {
169 - for (const end of [
170 - (h: ReturnType<typeof harness>) => h.observe(completed(1), { ...visible, archived: true }),
171 - (h: ReturnType<typeof harness>) =>
172 - h.observe({ ...completed(1) }, { ...visible, quiet: true }),
173 - (h: ReturnType<typeof harness>) => h.gate.retain(new Set()),
174 - (h: ReturnType<typeof harness>) => h.gate.clear(),
100 + it("forgets handled completions when a thread is removed or the gate is cleared", () => {
101 + for (const reset of [
102 + (gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.retain(new Set()),
103 + (gate: ReturnType<typeof createThreadNotificationGate<string>>) => gate.clear(),
104 ]) {
176 - const h = harness();
177 - h.observe(working);
178 - h.observe(completed(1));
179 - end(h);
180 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
181 - expect(h.notify).not.toHaveBeenCalled();
105 + const { gate, notify, observe } = harness();
106 + observe(completed(1));
107 + reset(gate);
108 + gate.observe("thread", undefined, working, visible);
109 + gate.observe("thread", working, completed(1), visible);
110 + expect(notify.mock.calls).toEqual([["thread", "completion"]]);
111 }
112 });
184 -
185 - it("never notifies a stopped run or the first observation", () => {
186 - const { notify, observe } = harness();
187 - observe(completed(1));
188 - observe(working);
189 - observe(completed(2), { ...visible, quiet: true });
190 - vi.advanceTimersByTime(WORKING_EXIT_GRACE_MS * 2);
191 - expect(notify).not.toHaveBeenCalled();
192 - });
113 });
apps/web/src/components/ThreadNotificationCoordinator.logic.ts
+2 -36
@@ -1,5 +1,3 @@
1 -import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2 -
1 export type ThreadNotificationKind = "input" | "completion";
2
3 export interface ThreadNotificationObservation {
@@ -11,23 +9,11 @@ export interface ThreadNotificationObservation {
9 readonly completedAt: number | null;
10 }
11
14 -/**
15 - * Attention notifies at once. Completion waits out the Working shelf's exit grace,
16 - * because an orchestrator run can end moments before its continuation starts. Any
17 - * observation that is not settled during the wait cancels it.
18 - */
12 export function createThreadNotificationGate<Key>(
13 notify: (key: Key, kind: ThreadNotificationKind) => void,
14 ) {
22 - const pending = new Map<Key, { at: number; timer: ReturnType<typeof setTimeout> }>();
15 // The newest completion already notified, or deliberately skipped.
16 const handled = new Map<Key, number>();
25 - // The newest completion seen settled, kept while the thread works or waits.
26 - const lastSettled = new Map<Key, number>();
27 - const cancel = (key: Key) => {
28 - clearTimeout(pending.get(key)?.timer);
29 - pending.delete(key);
30 - };
17 const skip = (key: Key, at: number | null) => {
18 if (at !== null && at > (handled.get(key) ?? -Infinity)) handled.set(key, at);
19 };
@@ -38,44 +24,24 @@ export function createThreadNotificationGate<Key>(
24 next: ThreadNotificationObservation,
25 options: { readonly archived: boolean; readonly quiet: boolean },
26 ): void {
41 - if (next.settled && next.completedAt !== null) lastSettled.set(key, next.completedAt);
42 - if (!next.settled || options.archived || options.quiet) cancel(key);
27 // The first sighting, archived threads, and stopped or silent runs never notify completion.
28 if (!prior || options.archived || options.quiet) skip(key, next.completedAt);
29 if (!prior || options.archived) return;
30 if (next.attention && next.attention !== prior.attention) {
47 - // Attention replaces the completion before it, so that run must not notify later.
48 - skip(key, lastSettled.get(key) ?? null);
49 - cancel(key);
31 notify(key, "input");
32 return;
33 }
34 const at = next.completedAt;
35 if (!next.settled || at === null || at <= (handled.get(key) ?? -Infinity)) return;
55 - if (pending.get(key)?.at === at) return;
56 - cancel(key);
57 - pending.set(key, {
58 - at,
59 - timer: setTimeout(() => {
60 - pending.delete(key);
61 - handled.set(key, at);
62 - notify(key, "completion");
63 - }, WORKING_EXIT_GRACE_MS),
64 - });
36 + handled.set(key, at);
37 + notify(key, "completion");
38 },
39 /** Forgets threads that left the snapshot. */
40 retain(keys: ReadonlySet<Key>): void {
68 - for (const key of pending.keys()) if (!keys.has(key)) cancel(key);
41 for (const key of handled.keys()) if (!keys.has(key)) handled.delete(key);
70 - for (const key of lastSettled.keys()) if (!keys.has(key)) lastSettled.delete(key);
71 - },
72 - cancelPending(): void {
73 - for (const key of pending.keys()) cancel(key);
42 },
43 clear(): void {
76 - for (const key of pending.keys()) cancel(key);
44 handled.clear();
78 - lastSettled.clear();
45 },
46 };
47 }
apps/web/src/components/ThreadNotificationCoordinator.tsx
-2
@@ -111,7 +111,6 @@ export function startThreadNotifications(
111 setNotificationBadge(0);
112 };
113
114 - // Completions fire from a timer, so read settings, focus and route when presenting.
114 const present = (
115 environmentId: EnvironmentId,
116 state: NotificationState,
@@ -308,7 +307,6 @@ export function startThreadNotifications(
307 observeThreads(environmentId, entry, threads);
308 return;
309 }
311 - entry.gate.cancelPending();
310 entry.reconnecting = true;
311 },
312 { immediate: true },
apps/web/src/threadNotifications.test.ts
+25
@@ -49,6 +49,31 @@ afterEach(() => {
49 });
50
51 describe("playNotificationSound", () => {
52 + it("preloads both sounds on unlock and reuses them for playback", async () => {
53 + const { unlockNotificationAudio, playNotificationSound } = await loadUnlocked();
54 + expect(fetch).toHaveBeenCalledTimes(2);
55 + unlockNotificationAudio();
56 + await playNotificationSound("completion", () => true);
57 + await playNotificationSound("input", () => true);
58 + expect(fetch).toHaveBeenCalledTimes(2);
59 + expect(audio.started).toBe(2);
60 + });
61 +
62 + it("retries failed preloads on an alert rather than every gesture", async () => {
63 + vi.mocked(fetch).mockRejectedValue(new Error("offline"));
64 + const { unlockNotificationAudio, playNotificationSound } = await loadUnlocked();
65 + await playNotificationSound("completion", () => true);
66 + expect(fetch).toHaveBeenCalledTimes(2);
67 +
68 + unlockNotificationAudio();
69 + expect(fetch).toHaveBeenCalledTimes(2);
70 +
71 + vi.mocked(fetch).mockResolvedValue(new Response(new ArrayBuffer(0)));
72 + await playNotificationSound("completion", () => true);
73 + expect(fetch).toHaveBeenCalledTimes(3);
74 + expect(audio.started).toBe(1);
75 + });
76 +
77 it("plays one sound for threads that complete together", async () => {
78 const { playNotificationSound } = await loadUnlocked();
79
apps/web/src/threadNotifications.ts
+23 -9
@@ -85,10 +85,31 @@ const buffers = new Map<string, Promise<AudioBuffer>>();
85 /** When each sound's current playback ends, on the audio context's clock. */
86 const playingUntil = new Map<string, number>();
87
88 +function loadNotificationBuffer(context: AudioContext, url: string): Promise<AudioBuffer> {
89 + let buffer = buffers.get(url);
90 + if (!buffer) {
91 + buffer = fetch(url)
92 + .then((response) => response.arrayBuffer())
93 + .then((data) => context.decodeAudioData(data))
94 + .catch((error: unknown) => {
95 + buffers.delete(url);
96 + throw error;
97 + });
98 + buffers.set(url, buffer);
99 + }
100 + return buffer;
101 +}
102 +
103 /** Called from a gesture so browsers allow later background playback. */
104 export function unlockNotificationAudio() {
105 + const firstUnlock = audioContext === undefined;
106 audioContext ??= new AudioContext();
107 void audioContext.resume().catch(() => undefined);
108 + if (!firstUnlock) return;
109 + // Fetch and decode during interaction so the first alert is ready when the thread finishes.
110 + for (const url of [completionUrl, inputUrl]) {
111 + void loadNotificationBuffer(audioContext, url).catch(() => undefined);
112 + }
113 }
114
115 export async function playNotificationSound(
@@ -99,14 +120,7 @@ export async function playNotificationSound(
120 const context = audioContext;
121 const url = kind === "completion" ? completionUrl : inputUrl;
122 try {
102 - let buffer = buffers.get(url);
103 - if (!buffer) {
104 - buffer = fetch(url)
105 - .then((response) => response.arrayBuffer())
106 - .then((data) => context.decodeAudioData(data));
107 - buffers.set(url, buffer);
108 - }
109 - const decoded = await buffer;
123 + const decoded = await loadNotificationBuffer(context, url);
124 if (!shouldPlay() || context.state !== "running") return;
125 // Coalesce same-sound bursts after decode to avoid clipping; input and completion alerts keep separate slots.
126 if (context.currentTime < (playingUntil.get(url) ?? 0)) return;
@@ -116,6 +130,6 @@ export async function playNotificationSound(
130 source.start();
131 playingUntil.set(url, context.currentTime + decoded.duration);
132 } catch {
119 - buffers.delete(url);
133 + // A failed load is retried on the next alert.
134 }
135 }
packages/client-runtime/src/state/threadInbox.ts
+1 -1
@@ -112,7 +112,7 @@ type ThreadKeyInput = Pick<EnvironmentThreadShell, "environmentId" | "id">;
112 * run can end moments before its continuation starts, so clients wait this long
113 * before treating the thread as done.
114 */
115 -export const WORKING_EXIT_GRACE_MS = 2_000;
115 +const WORKING_EXIT_GRACE_MS = 2_000;
116
117 /**
118 * Keep one at module scope so placement survives routes that unmount the list. Call