Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
67 changes: 67 additions & 0 deletions src/browser/audio-playback.test.ts
Original file line number Diff line number Diff line change
@@ -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<void>) {
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<void>>()
.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<void>>()
.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);
});
});
42 changes: 35 additions & 7 deletions src/browser/audio-playback.ts
Original file line number Diff line number Diff line change
@@ -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<AudioPlayOutcome> {
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<AudioPlayOutcome> {
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<boolean> {
try {
await el.play();
return true;
} catch {
return false;
}
return (await playAudioElement(el)) === "playing";
}

/**
Expand Down
70 changes: 70 additions & 0 deletions src/browser/browser-voice-session-mic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((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");
});
});
21 changes: 13 additions & 8 deletions src/browser/browser-voice-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ import {
} from "./microphone.js";
import {
createHiddenAudioElement,
unlockAudioPlayback as unlockAudioPlaybackElement,
playAudioElement,
type AudioPlaybackState,
} from "./audio-playback.js";

Expand Down Expand Up @@ -593,12 +593,15 @@ export async function connectBrowserVoiceSession(
};
const attemptInboundAudioPlayback = async (): Promise<void> => {
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. */
Expand Down Expand Up @@ -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: () =>
Expand Down
1 change: 1 addition & 0 deletions test/public-exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ const INTERNAL: Record<string, string> = {
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",
Expand Down
Loading