Skip to content

Commit c0ea965

Browse files
committed
fix(web): preload notification audio once per context
1 parent a02dcd4 commit c0ea965

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎apps/web/src/threadNotifications.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,21 @@ describe("playNotificationSound", () => {
5959
expect(audio.started).toBe(2);
6060
});
6161

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+
6277
it("plays one sound for threads that complete together", async () => {
6378
const { playNotificationSound } = await loadUnlocked();
6479

‎apps/web/src/threadNotifications.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,10 @@ function loadNotificationBuffer(context: AudioContext, url: string): Promise<Aud
102102

103103
/** Called from a gesture so browsers allow later background playback. */
104104
export function unlockNotificationAudio() {
105+
const firstUnlock = audioContext === undefined;
105106
audioContext ??= new AudioContext();
106107
void audioContext.resume().catch(() => undefined);
108+
if (!firstUnlock) return;
107109
// Fetch and decode during interaction so the first alert is ready when the thread finishes.
108110
for (const url of [completionUrl, inputUrl]) {
109111
void loadNotificationBuffer(audioContext, url).catch(() => undefined);
@@ -128,6 +130,6 @@ export async function playNotificationSound(
128130
source.start();
129131
playingUntil.set(url, context.currentTime + decoded.duration);
130132
} catch {
131-
// A failed preload is retried on the next gesture or alert.
133+
// A failed load is retried on the next alert.
132134
}
133135
}

0 commit comments

Comments
 (0)