diff --git a/CHANGELOG.md b/CHANGELOG.md index 395ffc1..eba7a5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Fixed + +- The "Enable sound" notice no longer appears when the page's own code changes the audio source right after the agent's audio starts. + ## [0.25.0] - 2026-11-09 ### Added diff --git a/src/browser/audio-playback.test.ts b/src/browser/audio-playback.test.ts new file mode 100644 index 0000000..e63921a --- /dev/null +++ b/src/browser/audio-playback.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from "vitest"; + +import { playAudioElement, unlockAudioPlayback } from "./audio-playback.js"; + +const abort = () => + new DOMException("interrupted by a new load request", "AbortError"); +const notAllowed = () => new DOMException("blocked", "NotAllowedError"); + +function elWith(play: () => Promise) { + const fn = vi.fn(play); + return { el: { play: fn } as unknown as HTMLAudioElement, play: fn }; +} + +describe("playAudioElement", () => { + it("is playing when play() resolves", async () => { + const { el, play } = elWith(async () => undefined); + expect(await playAudioElement(el)).toBe("playing"); + expect(play).toHaveBeenCalledTimes(1); + }); + + it("retries once after an AbortError and is playing when the retry resolves", async () => { + const play = vi + .fn<() => Promise>() + .mockRejectedValueOnce(abort()) + .mockResolvedValueOnce(undefined); + const el = { play } as unknown as HTMLAudioElement; + expect(await playAudioElement(el)).toBe("playing"); + expect(play).toHaveBeenCalledTimes(2); + expect(await unlockAudioPlayback(el)).toBe(true); + }); + + it("is blocked when the retry after an AbortError is NotAllowedError", async () => { + const play = vi + .fn<() => Promise>() + .mockRejectedValueOnce(abort()) + .mockRejectedValueOnce(notAllowed()); + const el = { play } as unknown as HTMLAudioElement; + expect(await playAudioElement(el)).toBe("blocked"); + expect(play).toHaveBeenCalledTimes(2); + }); + + it("is blocked at once on NotAllowedError, without a retry", async () => { + const { el, play } = elWith(async () => { + throw notAllowed(); + }); + expect(await playAudioElement(el)).toBe("blocked"); + expect(play).toHaveBeenCalledTimes(1); + expect(await unlockAudioPlayback(el)).toBe(false); + }); + + it("treats any other error as blocked without a retry", async () => { + const { el, play } = elWith(async () => { + throw new Error("boom"); + }); + expect(await playAudioElement(el)).toBe("blocked"); + expect(play).toHaveBeenCalledTimes(1); + }); + + it("stops after one retry when play() is aborted twice", async () => { + const { el, play } = elWith(async () => { + throw abort(); + }); + expect(await playAudioElement(el)).toBe("aborted"); + expect(play).toHaveBeenCalledTimes(2); + expect(await unlockAudioPlayback(el)).toBe(false); + }); +}); diff --git a/src/browser/audio-playback.ts b/src/browser/audio-playback.ts index cd76a9b..08d5f54 100644 --- a/src/browser/audio-playback.ts +++ b/src/browser/audio-playback.ts @@ -1,18 +1,46 @@ export type AudioPlaybackState = "idle" | "playing" | "blocked"; +export type AudioPlayOutcome = "playing" | "blocked" | "aborted"; + +/** One play() attempt. Only a rejection named AbortError is "aborted". */ +async function playOnce(el: HTMLAudioElement): Promise { + try { + await el.play(); + return "playing"; + } catch (err) { + const name = (err as { name?: unknown } | null)?.name; + return name === "AbortError" ? "aborted" : "blocked"; + } +} + +/** + * Start playback and report the outcome. An AbortError means a new load + * interrupted play() (the page replaced `srcObject`), not that the browser + * blocked autoplay, so it is retried once on the new source. At most one retry. + */ +export async function playAudioElement( + el: HTMLAudioElement, +): Promise { + const first = await playOnce(el); + if (first !== "aborted") return first; + await Promise.resolve(); + const second = await playOnce(el); + return second === "playing" + ? "playing" + : second === "aborted" + ? "aborted" + : "blocked"; +} + /** * Attempt to start playback on an audio element (e.g. after user gesture or ontrack). - * Returns false on failure without throwing. + * Returns false on failure without throwing. A play() that stays interrupted + * after the single retry is not a browser block, but still returns false. */ export async function unlockAudioPlayback( el: HTMLAudioElement, ): Promise { - try { - await el.play(); - return true; - } catch { - return false; - } + return (await playAudioElement(el)) === "playing"; } /** diff --git a/src/browser/browser-voice-session-mic.test.ts b/src/browser/browser-voice-session-mic.test.ts index c4052d4..4837bce 100644 --- a/src/browser/browser-voice-session-mic.test.ts +++ b/src/browser/browser-voice-session-mic.test.ts @@ -505,4 +505,74 @@ describe("connectBrowserVoiceSession microphone APIs", () => { expect(session.getAudioPlaybackState()).toBe("blocked"); expect(onAudioPlayback).toHaveBeenCalledWith("blocked"); }); + + it("does not report blocked when the host's onAgentAudioTrack replaces srcObject and aborts play()", async () => { + MockWebSocket.instances = []; + MockPeerConnection.instances = []; + + const remoteTrack = { + kind: "audio", + readyState: "live", + } as MediaStreamTrack; + const remoteStream = { + id: "remote", + getAudioTracks: () => [remoteTrack], + } as MediaStream; + const hostStream = { id: "host" } as MediaStream; + + const onAudioPlayback = vi.fn(); + const audioElement = { + srcObject: null as MediaStream | null, + play: vi.fn(function (this: { srcObject: MediaStream | null }) { + const before = this.srcObject; + return new Promise((resolve, reject) => { + queueMicrotask(() => { + if (this.srcObject !== before) { + reject( + new DOMException( + "interrupted by a new load request", + "AbortError", + ), + ); + } else resolve(); + }); + }); + }), + } as unknown as HTMLAudioElement; + + const session = await connectBrowserVoiceSession({ + credentials, + requestMic: true, + readiness: "data", + runtime: createDeniedMicRuntime(), + audioElement, + onAudioPlayback, + onAgentAudioTrack: () => { + audioElement.srcObject = hostStream; + }, + }); + + const ws = MockWebSocket.instances[0]!; + ws.onmessage?.({ + data: JSON.stringify({ + type: "offer", + peerId: VOICE_AGENT_SERVER_PEER_ID, + sdp: { type: "offer", sdp: "v=0\na=ice-ufrag:abc\n" }, + }), + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + const pc = MockPeerConnection.instances[0]!; + pc.ontrack?.({ + track: remoteTrack, + streams: [remoteStream], + } as RTCTrackEvent); + + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(audioElement.srcObject).toBe(hostStream); + expect(audioElement.play).toHaveBeenCalledTimes(2); + expect(onAudioPlayback).not.toHaveBeenCalledWith("blocked"); + expect(session.getAudioPlaybackState()).toBe("playing"); + }); }); diff --git a/src/browser/browser-voice-session.ts b/src/browser/browser-voice-session.ts index 373f72e..81fafe5 100644 --- a/src/browser/browser-voice-session.ts +++ b/src/browser/browser-voice-session.ts @@ -86,7 +86,7 @@ import { } from "./microphone.js"; import { createHiddenAudioElement, - unlockAudioPlayback as unlockAudioPlaybackElement, + playAudioElement, type AudioPlaybackState, } from "./audio-playback.js"; @@ -593,12 +593,15 @@ export async function connectBrowserVoiceSession( }; const attemptInboundAudioPlayback = async (): Promise => { if (!playbackAudioElement) return; - const ok = await unlockAudioPlaybackElement(playbackAudioElement); - if (ok) { + const outcome = await playAudioElement(playbackAudioElement); + if (outcome === "playing") { setAudioPlaybackState("playing"); - } else { + } else if (outcome === "blocked") { debug?.warn("webrtc", "audio_playback_blocked"); setAudioPlaybackState("blocked"); + } else { + // Interrupted twice by new loads: the browser did not block anything. + debug?.warn("webrtc", "audio_playback_interrupted"); } }; /** ICE candidates queued by negotiation generation until that PC is ready. */ @@ -2765,14 +2768,16 @@ export async function connectBrowserVoiceSession( getAudioPlaybackState: () => audioPlaybackState, unlockAudioPlayback: async () => { if (!playbackAudioElement) return false; - const ok = await unlockAudioPlaybackElement(playbackAudioElement); - if (ok) { + const outcome = await playAudioElement(playbackAudioElement); + if (outcome === "playing") { setAudioPlaybackState("playing"); - } else { + } else if (outcome === "blocked") { debug?.warn("webrtc", "audio_playback_blocked"); setAudioPlaybackState("blocked"); + } else { + debug?.warn("webrtc", "audio_playback_interrupted"); } - return ok; + return outcome === "playing"; }, getConnectionState: () => connectionState, getConnectionStatus: () => diff --git a/test/public-exports.test.ts b/test/public-exports.test.ts index 61e205f..576cb5d 100644 --- a/test/public-exports.test.ts +++ b/test/public-exports.test.ts @@ -177,6 +177,7 @@ const INTERNAL: Record = { DEBUG_CONSOLE_MAX_EVENTS: "debug-console.ts ring size; exported for tests only", postEndUserIdentify: "used by browser-voice-session.ts", + playAudioElement: "used by browser-voice-session.ts", assertEndUserOptions: "used by startSession and browser-voice-session.ts", parseLegacyAgentError: "used by browser-voice-session.ts", emitDiagnosticSafely: "used by browser-voice-session.ts",