Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(calls): trace browser media permissions and setup (#8375)

Eric Hayes360c86530bde
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 281721d04c..a44a48fa86 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -113,6 +113,9 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
- Route explicit call exits using the server's `callEnded` result: ended calls
open their record; ongoing channel and scheduled calls return to the channel
and Calendar. Preserve the session ID before disconnecting.
+- Diagnose browser call media with `call.media.*` spans and the `meeting.setup.id`
+ on `meeting.join`; keep provider messages, device labels/IDs, and call-link
+ tokens out of telemetry. See [call diagnostics](../../docs/agent-guide/calls.md#browser-call-diagnostics).
- Keep desktop Gmail and Outlook inbox consent in the system browser with a
`macro:///inbox-link-callback` return; webview origins are not desktop callbacks.
- Touch email replies and forwards use the full-screen composer with the shared new-email header actions; preserve thread state underneath and flush local edits before closing.
diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsx
index 7a0b0f211b..7bcdb180ed 100644
--- a/apps/web/src/features/channel/Call/CallContext.tsx
+++ b/apps/web/src/features/channel/Call/CallContext.tsx
@@ -9,6 +9,7 @@ import { fireAndForget } from '@core/util/fireAndForget';
import { holdAutomaticReload } from '@core/util/reloadForNewerBuild';
import type { KrispNoiseFilter } from '@livekit/krisp-noise-filter';
import type { BackgroundProcessorWrapper } from '@livekit/track-processors';
+import type { Span } from '@macro-inc/observability';
import {
fetchActiveCall,
invalidateActiveCallQueries,
@@ -40,6 +41,7 @@ import {
stopPrejoinTracks,
} from './CallSessionController';
import { type CallLifecycleState, createCallLifecycle } from './call-lifecycle';
+import { traceCallMedia } from './call-media-telemetry';
import { publishCallResolution } from './call-resolution';
import { createLatestAsyncRequestQueue } from './latest-async-request-queue';
import {
@@ -1195,11 +1197,21 @@ function createCallState() {
targetRoom: Room,
source: keyof CallPrejoinTracks,
prejoinTrack: MediaStreamTrack | undefined,
- enableDevice: () => Promise<unknown>
+ enableDevice: () => Promise<unknown>,
+ mediaSpan?: Span
) {
+ const callId = store.activeCallId;
if (prejoinTrack?.readyState === 'live') {
try {
- await publishPrejoinTrack(targetRoom, source, prejoinTrack);
+ await traceCallMedia(
+ 'publish_prejoin',
+ {
+ 'call.id': callId ?? undefined,
+ 'call.media.device': source,
+ },
+ () => publishPrejoinTrack(targetRoom, source, prejoinTrack),
+ mediaSpan
+ );
return;
} catch (e) {
console.error(`failed to publish prejoin ${source} track`, e);
@@ -1208,13 +1220,22 @@ function createCallState() {
}
}
prejoinTrack?.stop();
- await enableDevice();
+ await traceCallMedia(
+ 'enable',
+ {
+ 'call.id': callId ?? undefined,
+ 'call.media.device': source,
+ },
+ enableDevice,
+ mediaSpan
+ );
}
async function finishLocalMediaSetup(
targetRoom: Room,
setupVersion: number,
- prejoinTracks?: CallPrejoinTracks
+ prejoinTracks?: CallPrejoinTracks,
+ mediaSpan?: Span
) {
// Each step claims its track; anything left unclaimed is stopped.
const unclaimed = { ...prejoinTracks };
@@ -1224,7 +1245,7 @@ function createCallState() {
return track;
};
try {
- await setUpLocalMedia(targetRoom, setupVersion, claim);
+ await setUpLocalMedia(targetRoom, setupVersion, claim, mediaSpan);
} finally {
stopPrejoinTracks(unclaimed);
}
@@ -1233,7 +1254,8 @@ function createCallState() {
async function setUpLocalMedia(
targetRoom: Room,
setupVersion: number,
- claim: (source: keyof CallPrejoinTracks) => MediaStreamTrack | undefined
+ claim: (source: keyof CallPrejoinTracks) => MediaStreamTrack | undefined,
+ mediaSpan?: Span
) {
if (!isCurrentMediaSetup(targetRoom, setupVersion)) return;
@@ -1250,7 +1272,8 @@ function createCallState() {
targetRoom.localParticipant.setMicrophoneEnabled(
true,
currentMicrophoneCaptureOptions(store.activeAudioInputDeviceId)
- )
+ ),
+ mediaSpan
);
}
} catch (e) {
@@ -1276,8 +1299,12 @@ function createCallState() {
if (!store.isVideoMuted) {
try {
- await enablePrejoinOrDevice(targetRoom, 'camera', claim('camera'), () =>
- enableInitialCamera(targetRoom)
+ await enablePrejoinOrDevice(
+ targetRoom,
+ 'camera',
+ claim('camera'),
+ () => enableInitialCamera(targetRoom),
+ mediaSpan
);
if (!isCurrentMediaSetup(targetRoom, setupVersion)) return;
if (store.isVideoMuted) {
@@ -1422,16 +1449,33 @@ function createCallState() {
const newMuted = !store.isAudioMuted;
try {
if (newMuted) {
- await r.localParticipant.setMicrophoneEnabled(false);
+ await traceCallMedia(
+ 'toggle',
+ {
+ 'call.id': store.activeCallId ?? undefined,
+ 'call.media.device': 'microphone',
+ 'call.media.enabled': false,
+ },
+ () => r.localParticipant.setMicrophoneEnabled(false)
+ );
} else {
// Re-enable the mic. When the muted publication survived
// (stopMicTrackOnMute is false) this only unmutes and the capture
// options are ignored; they matter when the track was stopped and
// must be recreated (e.g. after a device unplug).
const deviceId = store.activeAudioInputDeviceId;
- await r.localParticipant.setMicrophoneEnabled(
- true,
- currentMicrophoneCaptureOptions(deviceId)
+ await traceCallMedia(
+ 'toggle',
+ {
+ 'call.id': store.activeCallId ?? undefined,
+ 'call.media.device': 'microphone',
+ 'call.media.enabled': true,
+ },
+ () =>
+ r.localParticipant.setMicrophoneEnabled(
+ true,
+ currentMicrophoneCaptureOptions(deviceId)
+ )
);
// The mic track may have changed — re-apply the selected audio processing.
await ensureNoiseSuppressionOnMicTrack(r);
@@ -1455,14 +1499,31 @@ function createCallState() {
const newMuted = !store.isVideoMuted;
try {
if (newMuted) {
- await r.localParticipant.setCameraEnabled(false);
+ await traceCallMedia(
+ 'toggle',
+ {
+ 'call.id': store.activeCallId ?? undefined,
+ 'call.media.device': 'camera',
+ 'call.media.enabled': false,
+ },
+ () => r.localParticipant.setCameraEnabled(false)
+ );
// Track is gone — drop our processor ref so the next enable starts clean.
setBlurProcessor(null);
} else {
const deviceId = store.activeVideoInputDeviceId;
- await r.localParticipant.setCameraEnabled(
- true,
- deviceId ? { deviceId: { exact: deviceId } } : undefined
+ await traceCallMedia(
+ 'toggle',
+ {
+ 'call.id': store.activeCallId ?? undefined,
+ 'call.media.device': 'camera',
+ 'call.media.enabled': true,
+ },
+ () =>
+ r.localParticipant.setCameraEnabled(
+ true,
+ deviceId ? { deviceId: { exact: deviceId } } : undefined
+ )
);
// Read the actual device the browser chose so the dropdown is accurate
const camPub = r.localParticipant.getTrackPublication(
diff --git a/apps/web/src/features/channel/Call/LivekitJsCallController.ts b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
index 5c72f7a765..8398cd3e1a 100644
--- a/apps/web/src/features/channel/Call/LivekitJsCallController.ts
+++ b/apps/web/src/features/channel/Call/LivekitJsCallController.ts
@@ -1,4 +1,5 @@
-import { Telemetry } from '@macro-inc/observability';
+import { fireAndForget } from '@core/util/fireAndForget';
+import { type Span, Telemetry } from '@macro-inc/observability';
import type { CallTokenResponse } from '@service-call/client';
import {
type AudioCaptureOptions,
@@ -16,6 +17,7 @@ import {
stopPrejoinTracks,
} from './CallSessionController';
import { startReceiverStatsSampling } from './call-audio-receiver-stats';
+import { traceCallMedia } from './call-media-telemetry';
type LivekitJsCallControllerState = {
activeChannelId: string | null;
@@ -34,7 +36,8 @@ type LivekitJsCallControllerOptions = {
finishLocalMediaSetup: (
room: Room,
setupVersion: number,
- prejoinTracks?: CallPrejoinTracks
+ prejoinTracks?: CallPrejoinTracks,
+ mediaSpan?: Span
) => Promise<void>;
destroyProcessors: () => void;
resetState: () => void;
@@ -81,11 +84,15 @@ export function createLivekitJsCallController(
room.on(RoomEvent.ConnectionStateChanged, (state: ConnectionState) => {
if (!isCurrentRoom(room)) return;
- console.debug('[call] connection state changed', {
- state,
- room: call.channelId,
- call: call.callId,
- });
+ Telemetry.recordSample(
+ 'call.connection.state',
+ {
+ 'call.connection.state': state,
+ 'channel.id': call.channelId ?? undefined,
+ 'call.id': call.callId,
+ },
+ Date.now()
+ );
// A terminal disconnect clears the UI state, but the current Room can
// still report a late recovery. Restore its identity with the connection
// state so audio and channel UI agree about which call is connected.
@@ -122,11 +129,17 @@ export function createLivekitJsCallController(
room.on(RoomEvent.Disconnected, (reason?: unknown) => {
if (!isCurrentRoom(room)) return;
- console.warn('[call] room disconnected', {
- reason,
- room: call.channelId,
- call: call.callId,
- });
+ Telemetry.recordSample(
+ 'call.connection.disconnected',
+ {
+ // LiveKit's disconnect reason is a numeric enum, never a raw error.
+ 'call.connection.reason':
+ typeof reason === 'number' ? reason : undefined,
+ 'channel.id': call.channelId ?? undefined,
+ 'call.id': call.callId,
+ },
+ Date.now()
+ );
options.resetState();
});
}
@@ -148,9 +161,17 @@ export function createLivekitJsCallController(
preferences?: CallSessionConnectMetadata
) {
let prejoinTracks = preferences?.localTracks;
+ const span = Telemetry.span('call.connect');
+ span.setAttr('call.id', tokenResponse.callId);
try {
- prejoinTracks = await connectRoom(tokenResponse, preferences);
+ prejoinTracks = await span.run(() =>
+ connectRoom(tokenResponse, span, preferences)
+ );
+ } catch (error) {
+ span.error('Call connection failed');
+ throw error;
} finally {
+ span.end();
stopPrejoinTracks(prejoinTracks);
}
}
@@ -158,6 +179,7 @@ export function createLivekitJsCallController(
/** Returns the prejoin tracks it did not hand to media setup. */
async function connectRoom(
tokenResponse: CallTokenResponse,
+ connectSpan: Span,
preferences?: CallSessionConnectMetadata
): Promise<CallPrejoinTracks | undefined> {
const prejoinTracks = preferences?.localTracks;
@@ -256,14 +278,48 @@ export function createLivekitJsCallController(
// run failed-join cleanup, which calls DELETE /call/:channel and kicks the
// user out. Run the non-critical setup in the background instead.
const setupVersion = options.nextMediaSetupVersion();
- void options
- .finishLocalMediaSetup(targetRoom, setupVersion, prejoinTracks)
- .catch((e) => {
- console.error('failed to finish local call media setup', e);
- });
+ fireAndForget(
+ finishMediaSetup(
+ targetRoom,
+ setupVersion,
+ tokenResponse.callId,
+ connectSpan,
+ prejoinTracks
+ ),
+ 'call-media'
+ );
return undefined;
}
+ async function finishMediaSetup(
+ targetRoom: Room,
+ setupVersion: number,
+ callId: string,
+ connectSpan: Span,
+ prejoinTracks?: CallPrejoinTracks
+ ) {
+ try {
+ await traceCallMedia(
+ 'setup',
+ {
+ 'call.id': callId,
+ 'call.media.microphone_track': Boolean(prejoinTracks?.microphone),
+ 'call.media.camera_track': Boolean(prejoinTracks?.camera),
+ },
+ (mediaSpan) =>
+ options.finishLocalMediaSetup(
+ targetRoom,
+ setupVersion,
+ prejoinTracks,
+ mediaSpan
+ ),
+ connectSpan
+ );
+ } catch {
+ // The media span records a sanitized failure; joining still succeeds.
+ }
+ }
+
async function disconnect() {
connectGeneration += 1;
const room = options.room();
diff --git a/apps/web/src/features/channel/Call/call-media-telemetry.ts b/apps/web/src/features/channel/Call/call-media-telemetry.ts
new file mode 100644
index 0000000000..86478f86be
--- /dev/null
+++ b/apps/web/src/features/channel/Call/call-media-telemetry.ts
@@ -0,0 +1,60 @@
+import {
+ type Attributes,
+ type Span,
+ Telemetry,
+} from '@macro-inc/observability';
+
+/** Provider messages can contain device labels, URLs, or credentials. */
+export function callMediaErrorType(error: unknown): string {
+ const name =
+ error instanceof Error || error instanceof DOMException
+ ? error.name
+ : undefined;
+ const known = [
+ 'NotAllowedError',
+ 'SecurityError',
+ 'NotFoundError',
+ 'DevicesNotFoundError',
+ 'NotReadableError',
+ 'TrackStartError',
+ 'AbortError',
+ 'OverconstrainedError',
+ 'ConstraintNotSatisfiedError',
+ 'NotSupportedError',
+ 'TypeError',
+ ];
+ return name && known.includes(name) ? name : 'UnknownError';
+}
+
+export function recordCallMediaFailure(span: Span, error: unknown) {
+ const type = callMediaErrorType(error);
+ span.setAttr('error.type', type);
+ span.setAttr('call.media.outcome', 'failed');
+ span.error(`Call media operation failed: ${type}`);
+ span.event('call.media.failed', { 'error.type': type });
+}
+
+/** Keep background publication and later device actions on the active trace. */
+export async function traceCallMedia<T>(
+ phase: string,
+ attributes: Attributes,
+ operation: (span: Span) => Promise<T>,
+ parent?: Span
+): Promise<T> {
+ const run = async (span: Span) => {
+ for (const [key, value] of Object.entries(attributes)) {
+ if (value !== undefined) span.setAttr(key, value);
+ }
+ try {
+ const result = await operation(span);
+ span.setAttr('call.media.outcome', 'succeeded');
+ return result;
+ } catch (error) {
+ recordCallMediaFailure(span, error);
+ throw error;
+ }
+ };
+ return parent
+ ? parent.span(`call.media.${phase}`, run)
+ : Telemetry.span(`call.media.${phase}`, run);
+}
diff --git a/apps/web/src/features/channel/Call/tests/call-media-telemetry.test.ts b/apps/web/src/features/channel/Call/tests/call-media-telemetry.test.ts
new file mode 100644
index 0000000000..7ebcae11d1
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/call-media-telemetry.test.ts
@@ -0,0 +1,88 @@
+import type { Span } from '@macro-inc/observability';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { traceCallMedia } from '../call-media-telemetry';
+
+const span = vi.hoisted(() => ({
+ setAttr: vi.fn(),
+ error: vi.fn(),
+ event: vi.fn(),
+ end: vi.fn(),
+}));
+
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: {
+ span: async (
+ _name: string,
+ operation: (span: Partial<Span>) => Promise<unknown>
+ ) => {
+ try {
+ return await operation(span);
+ } finally {
+ span.end();
+ }
+ },
+ },
+}));
+
+describe('call media telemetry', () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ it.each([
+ 'NotAllowedError',
+ 'NotFoundError',
+ 'NotReadableError',
+ 'OverconstrainedError',
+ 'SecurityError',
+ ])(
+ 'retains %s without exporting device details or changing the failure',
+ async (name) => {
+ const error = new DOMException('secret device label and token', name);
+ await expect(
+ traceCallMedia(
+ 'enable',
+ {
+ 'call.id': 'call-1',
+ 'call.media.device': 'microphone',
+ },
+ async () => {
+ throw error;
+ }
+ )
+ ).rejects.toBe(error);
+ expect(span.setAttr).toHaveBeenCalledWith('call.id', 'call-1');
+ expect(span.setAttr).toHaveBeenCalledWith('error.type', name);
+ expect(span.error).toHaveBeenCalledWith(
+ `Call media operation failed: ${name}`
+ );
+ expect(JSON.stringify(span.error.mock.calls)).not.toContain('secret');
+ expect(span.end).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('redacts unknown provider error names as well as messages', async () => {
+ const error = new Error('token in message');
+ error.name = 'token in name';
+ await expect(
+ traceCallMedia('publish_prejoin', {}, async () => {
+ throw error;
+ })
+ ).rejects.toBe(error);
+ expect(span.error).toHaveBeenCalledExactlyOnceWith(
+ 'Call media operation failed: UnknownError'
+ );
+ expect(span.setAttr).toHaveBeenCalledWith('error.type', 'UnknownError');
+ });
+
+ it('records a successful operation and preserves its result', async () => {
+ const result = { published: true };
+ await expect(
+ traceCallMedia('publish_prejoin', {}, async () => result)
+ ).resolves.toBe(result);
+ expect(span.setAttr).toHaveBeenCalledWith(
+ 'call.media.outcome',
+ 'succeeded'
+ );
+ expect(span.error).not.toHaveBeenCalled();
+ expect(span.end).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/web/src/features/channel/Call/tests/livekit-js-call-controller.test.ts b/apps/web/src/features/channel/Call/tests/livekit-js-call-controller.test.ts
index f48940c6ea..c973e38cec 100644
--- a/apps/web/src/features/channel/Call/tests/livekit-js-call-controller.test.ts
+++ b/apps/web/src/features/channel/Call/tests/livekit-js-call-controller.test.ts
@@ -1,6 +1,7 @@
+import { Telemetry } from '@macro-inc/observability';
import type { CallTokenResponse } from '@service-call/client';
import type { Room, RoomOptions } from 'livekit-client';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const roomOptions = vi.fn();
const connectRoom = vi.fn<() => Promise<void>>();
@@ -76,6 +77,8 @@ function setup(state?: { connectionState: string; room?: Room }) {
}
describe('livekit call controller prejoin tracks', () => {
+ afterEach(() => vi.restoreAllMocks());
+
beforeEach(() => {
connectRoom.mockReset();
connectRoom.mockResolvedValue(undefined);
@@ -107,12 +110,33 @@ describe('livekit call controller prejoin tracks', () => {
expect(finishLocalMediaSetup).toHaveBeenCalledWith(
expect.anything(),
1,
- localTracks
+ localTracks,
+ expect.objectContaining({ span: expect.any(Function) })
);
expect(localTracks.microphone.stop).not.toHaveBeenCalled();
expect(localTracks.camera.stop).not.toHaveBeenCalled();
});
+ it('explicitly parents background media after the asynchronous room connection', async () => {
+ const connectionSpan = Telemetry.span('test');
+ const phases = vi.spyOn(connectionSpan, 'span');
+ vi.spyOn(Telemetry, 'span').mockReturnValue(connectionSpan);
+ const { controller, finishLocalMediaSetup } = setup();
+
+ await controller.connect(token);
+
+ expect(phases).toHaveBeenCalledWith(
+ 'call.media.setup',
+ expect.any(Function)
+ );
+ expect(finishLocalMediaSetup).toHaveBeenCalledWith(
+ expect.anything(),
+ 1,
+ undefined,
+ expect.objectContaining({ span: expect.any(Function) })
+ );
+ });
+
it('stops prejoin tracks when the room fails to connect', async () => {
connectRoom.mockRejectedValue(new Error('offline'));
const { controller, finishLocalMediaSetup } = setup();
diff --git a/apps/web/src/features/meetings/context/meeting-session.ts b/apps/web/src/features/meetings/context/meeting-session.ts
index 998481314b..8cf8bb8598 100644
--- a/apps/web/src/features/meetings/context/meeting-session.ts
+++ b/apps/web/src/features/meetings/context/meeting-session.ts
@@ -18,6 +18,24 @@ export type MeetingLocalTracks = {
camera?: MediaStreamTrack;
};
+export type MeetingMediaDiagnostics = {
+ setupId: string;
+ microphone:
+ | 'not_requested'
+ | 'pending'
+ | 'granted'
+ | 'blocked'
+ | 'failed'
+ | 'cancelled';
+ camera:
+ | 'not_requested'
+ | 'pending'
+ | 'granted'
+ | 'blocked'
+ | 'failed'
+ | 'cancelled';
+};
+
export type MeetingMediaPreferences = {
microphoneEnabled: boolean;
cameraEnabled: boolean;
diff --git a/apps/web/src/features/meetings/primitives/meeting-media-telemetry.test.ts b/apps/web/src/features/meetings/primitives/meeting-media-telemetry.test.ts
new file mode 100644
index 0000000000..7c61c400a3
--- /dev/null
+++ b/apps/web/src/features/meetings/primitives/meeting-media-telemetry.test.ts
@@ -0,0 +1,119 @@
+import { Telemetry } from '@macro-inc/observability';
+import { createRoot } from 'solid-js';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fakeMediaAccess } from '../tests/fake-media';
+import { createMeetingMedia } from './meeting-media';
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('waiting-room media telemetry', () => {
+ it('distinguishes blocked microphone access from an allowed camera left off', async () => {
+ const microphoneSpan = Telemetry.span('microphone');
+ const cameraSpan = Telemetry.span('camera');
+ const attributes = vi.spyOn(microphoneSpan, 'setAttr');
+ const errors = vi.spyOn(microphoneSpan, 'error');
+ const ended = vi.spyOn(microphoneSpan, 'end');
+ const cameraAttributes = vi.spyOn(cameraSpan, 'setAttr');
+ const cameraEnded = vi.spyOn(cameraSpan, 'end');
+ vi.spyOn(Telemetry, 'span')
+ .mockReturnValueOnce(microphoneSpan)
+ .mockReturnValueOnce(cameraSpan);
+ const { request } = fakeMediaAccess();
+ request.mockRejectedValueOnce(
+ new DOMException('private device info', 'NotAllowedError')
+ );
+ const { media, dispose } = createRoot((dispose) => ({
+ media: createMeetingMedia({ request }),
+ dispose,
+ }));
+ try {
+ await media.prepare();
+ expect(media.diagnostics()).toEqual({
+ setupId: expect.any(String),
+ microphone: 'blocked',
+ camera: 'granted',
+ });
+ expect(attributes).toHaveBeenCalledWith(
+ 'meeting.setup.id',
+ media.diagnostics().setupId
+ );
+ expect(attributes).toHaveBeenCalledWith('error.type', 'NotAllowedError');
+ expect(errors).toHaveBeenCalledExactlyOnceWith(
+ 'Call media operation failed: NotAllowedError'
+ );
+ expect(cameraAttributes).toHaveBeenCalledWith(
+ 'call.media.retained',
+ false
+ );
+ expect(ended).toHaveBeenCalledOnce();
+ expect(cameraEnded).toHaveBeenCalledOnce();
+ expect(media.microphoneEnabled()).toBe(false);
+ expect(media.cameraEnabled()).toBe(false);
+ expect(JSON.stringify(attributes.mock.calls)).not.toContain(
+ 'private device info'
+ );
+ } finally {
+ dispose();
+ }
+ });
+
+ it('ends pending spans on navigation and ignores late denials', async () => {
+ const span = Telemetry.span('capture');
+ const attributes = vi.spyOn(span, 'setAttr');
+ const errors = vi.spyOn(span, 'error');
+ const ended = vi.spyOn(span, 'end');
+ vi.spyOn(Telemetry, 'span').mockReturnValue(span);
+ let reject!: (reason: unknown) => void;
+ let started!: () => void;
+ const requested = new Promise<void>((resolve) => {
+ started = resolve;
+ });
+ const request = vi.fn(
+ () =>
+ new Promise<MediaStream>((_resolve, fail) => {
+ reject = fail;
+ started();
+ })
+ );
+ const { media, dispose } = createRoot((dispose) => ({
+ media: createMeetingMedia({ request }),
+ dispose,
+ }));
+ const preparing = media.prepare();
+ await requested;
+ dispose();
+ expect(ended).toHaveBeenCalledOnce();
+ expect(attributes).toHaveBeenCalledWith('call.media.outcome', 'cancelled');
+ reject(new DOMException('Late denial', 'NotAllowedError'));
+ await preparing;
+ expect(media.diagnostics().microphone).toBe('cancelled');
+ expect(errors).not.toHaveBeenCalled();
+ expect(request).toHaveBeenCalledOnce();
+ });
+
+ it('records granted access after retrying a denied device', async () => {
+ const { request } = fakeMediaAccess();
+ request.mockRejectedValueOnce(
+ new DOMException('Denied', 'NotAllowedError')
+ );
+ const { media, dispose } = createRoot((dispose) => ({
+ media: createMeetingMedia({ request }),
+ dispose,
+ }));
+ try {
+ await media.prepare();
+ const setupId = media.diagnostics().setupId;
+ expect(media.diagnostics().microphone).toBe('blocked');
+ // Retry via prepare to await the same serialized capture path as controls.
+ await media.prepare();
+ expect(media.diagnostics()).toEqual({
+ setupId,
+ microphone: 'granted',
+ camera: 'granted',
+ });
+ expect(media.microphoneEnabled()).toBe(false);
+ } finally {
+ dispose();
+ }
+ });
+});
diff --git a/apps/web/src/features/meetings/primitives/meeting-media.ts b/apps/web/src/features/meetings/primitives/meeting-media.ts
index 58215db3ff..d2bb863d79 100644
--- a/apps/web/src/features/meetings/primitives/meeting-media.ts
+++ b/apps/web/src/features/meetings/primitives/meeting-media.ts
@@ -1,7 +1,15 @@
+import {
+ recordCallMediaFailure,
+ traceCallMedia,
+} from '@channel/Call/call-media-telemetry';
import type { BackgroundEffect } from '@core/media/background-effect';
import { fireAndForget } from '@core/util/fireAndForget';
+import { type Span, Telemetry } from '@macro-inc/observability';
import { createSignal, onCleanup } from 'solid-js';
-import type { MeetingLocalTracks } from '../context/meeting-session';
+import type {
+ MeetingLocalTracks,
+ MeetingMediaDiagnostics,
+} from '../context/meeting-session';
export type MeetingMediaAccess = {
request: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
@@ -65,6 +73,12 @@ export function createMeetingMedia(
) {
type Device = 'microphone' | 'camera';
const devices: Device[] = ['microphone', 'camera'];
+ const diagnostics: MeetingMediaDiagnostics = {
+ setupId: crypto.randomUUID(),
+ microphone: 'not_requested',
+ camera: 'not_requested',
+ };
+ const captures: Partial<Record<Device, Span>> = {};
const [microphoneEnabled, setMicrophone] = createSignal(true);
const [cameraEnabled, setCamera] = createSignal(false);
const [video, setVideo] = createSignal<MediaStream>();
@@ -108,6 +122,13 @@ export function createMeetingMedia(
const setDevicePending = (device: Device, value: boolean) =>
setPending((current) => ({ ...current, [device]: value }));
const stop = (device: Device) => {
+ const capture = captures[device];
+ if (capture) {
+ capture.setAttr('call.media.outcome', 'cancelled');
+ capture.end();
+ delete captures[device];
+ diagnostics[device] = 'cancelled';
+ }
generations[device]++;
streams[device]?.getTracks().forEach((track) => track.stop());
delete streams[device];
@@ -124,7 +145,14 @@ export function createMeetingMedia(
if (!access?.enumerate || disposed) return;
const generation = ++enumerationGeneration;
try {
- const devices = await access.enumerate();
+ const enumerate = access.enumerate;
+ const devices = await traceCallMedia(
+ 'enumerate',
+ {
+ 'meeting.setup.id': diagnostics.setupId,
+ },
+ enumerate
+ );
if (disposed || generation !== enumerationGeneration) return;
setAvailableDevices(devices);
setDeviceError(undefined);
@@ -157,7 +185,16 @@ export function createMeetingMedia(
try {
if (!access?.processBackground)
throw new Error('Background effects are unavailable.');
- const processed = await access.processBackground(track, effect);
+ const processBackground = access.processBackground;
+ const processed = await traceCallMedia(
+ 'background',
+ {
+ 'meeting.setup.id': diagnostics.setupId,
+ 'call.media.device': 'camera',
+ 'call.media.background': effect.type,
+ },
+ () => processBackground(track, effect)
+ );
if (disposed || generation !== previewGeneration) {
processed.dispose();
return;
@@ -233,6 +270,7 @@ export function createMeetingMedia(
} catch (error) {
if (!isCurrent() || errorName(error) !== 'OverconstrainedError')
throw error;
+ captures[device]?.event('call.media.constraints_retry');
const deviceId = selectedDevices().camera;
return access.request({
audio: false,
@@ -256,8 +294,23 @@ export function createMeetingMedia(
const isCurrent = () => !disposed && generations[device] === generation;
setDevicePending(device, true);
setErrors((current) => ({ ...current, [device]: undefined }));
+ const span = Telemetry.span('call.media.capture');
+ span.setAttr('meeting.setup.id', diagnostics.setupId);
+ span.setAttr('call.media.device', device);
+ span.setAttr('call.media.enabled', enabled(device));
+ span.setAttr(
+ 'call.media.trigger',
+ requireEnabled ? 'device_control' : 'prepare'
+ );
+ captures[device] = span;
+ diagnostics[device] = 'pending';
try {
- const stream = await capture(device, isCurrent);
+ const stream = await span.run(() => capture(device, isCurrent));
+ if (isCurrent()) {
+ diagnostics[device] = 'granted';
+ span.setAttr('call.media.outcome', 'granted');
+ span.setAttr('call.media.retained', enabled(device));
+ }
if (!isCurrent() || !enabled(device)) {
stream.getTracks().forEach((track) => track.stop());
return;
@@ -266,14 +319,19 @@ export function createMeetingMedia(
fireAndForget(refreshDevices(), 'meeting-media');
} catch (error) {
if (!isCurrent()) return;
- console.warn(`[meeting] ${device} request failed`, error);
+ recordCallMediaFailure(span, error);
const message = mediaErrorMessage(device, error);
+ diagnostics[device] = message.permission ? 'blocked' : 'failed';
// Permission is requested for both devices up front, but a hardware
// problem only matters for a device the user actually turned on.
if (!enabled(device) && !message.permission) return;
setEnabled(device, false);
setErrors((current) => ({ ...current, [device]: message.text }));
} finally {
+ if (captures[device] === span) {
+ span.end();
+ delete captures[device];
+ }
if (isCurrent()) setDevicePending(device, false);
}
}
@@ -297,6 +355,7 @@ export function createMeetingMedia(
release();
});
return {
+ diagnostics: (): MeetingMediaDiagnostics => ({ ...diagnostics }),
microphoneEnabled,
cameraEnabled,
video,
diff --git a/apps/web/src/features/meetings/primitives/meeting-session.test.ts b/apps/web/src/features/meetings/primitives/meeting-session.test.ts
index 3387d0c022..56979bea7d 100644
--- a/apps/web/src/features/meetings/primitives/meeting-session.test.ts
+++ b/apps/web/src/features/meetings/primitives/meeting-session.test.ts
@@ -84,8 +84,25 @@ describe('meeting session ownership', () => {
const end = vi.spyOn(trace, 'end');
const { session, dispose } = setup({ prepare: async () => {} });
- await session.join(undefined, preferences);
+ await session.join(undefined, preferences, {
+ setupId: 'setup-1',
+ microphone: 'blocked',
+ camera: 'granted',
+ });
+ expect(attributes).toHaveBeenCalledWith('meeting.setup.id', 'setup-1');
+ expect(attributes).toHaveBeenCalledWith(
+ 'meeting.join.microphone_access',
+ 'blocked'
+ );
+ expect(attributes).toHaveBeenCalledWith(
+ 'meeting.join.camera_access',
+ 'granted'
+ );
+ expect(attributes).toHaveBeenCalledWith(
+ 'meeting.join.microphone_track',
+ false
+ );
expect(phases.mock.calls.map(([name]) => name)).toEqual([
'meeting.join.previous_session',
'meeting.join.create',
diff --git a/apps/web/src/features/meetings/primitives/meeting-session.ts b/apps/web/src/features/meetings/primitives/meeting-session.ts
index e4870124d3..5e66475482 100644
--- a/apps/web/src/features/meetings/primitives/meeting-session.ts
+++ b/apps/web/src/features/meetings/primitives/meeting-session.ts
@@ -4,6 +4,7 @@ import { createSignal, onCleanup } from 'solid-js';
import type {
MeetingCredentials,
MeetingLocalTracks,
+ MeetingMediaDiagnostics,
MeetingMediaPreferences,
MeetingSessionCapabilities,
} from '../context/meeting-session';
@@ -39,15 +40,21 @@ export function createMeetingSession(capabilities: MeetingSessionCapabilities) {
/** Handed-off tracks go to `connect` or are stopped; they never leak. */
async function join(
displayName: string | undefined,
- { localTracks, ...preferences }: MeetingMediaPreferences
+ { localTracks, ...preferences }: MeetingMediaPreferences,
+ mediaDiagnostics?: MeetingMediaDiagnostics
) {
let unclaimed = localTracks;
try {
- await attemptJoin(displayName, preferences, () => {
- const claimed = unclaimed;
- unclaimed = undefined;
- return claimed;
- });
+ await attemptJoin(
+ displayName,
+ preferences,
+ () => {
+ const claimed = unclaimed;
+ unclaimed = undefined;
+ return claimed;
+ },
+ mediaDiagnostics
+ );
} finally {
unclaimed?.microphone?.stop();
unclaimed?.camera?.stop();
@@ -57,7 +64,8 @@ export function createMeetingSession(capabilities: MeetingSessionCapabilities) {
async function attemptJoin(
displayName: string | undefined,
preferences: Omit<MeetingMediaPreferences, 'localTracks'>,
- claimLocalTracks: () => MeetingLocalTracks | undefined
+ claimLocalTracks: () => MeetingLocalTracks | undefined,
+ mediaDiagnostics?: MeetingMediaDiagnostics
) {
if (joining() || disposed) return;
if (issuedSession && capabilities.isInCall()) {
@@ -90,6 +98,14 @@ export function createMeetingSession(capabilities: MeetingSessionCapabilities) {
joinTrace.setAttr('meeting.join.guest', displayName !== undefined);
joinTrace.setAttr('meeting.join.microphone', preferences.microphoneEnabled);
joinTrace.setAttr('meeting.join.camera', preferences.cameraEnabled);
+ if (mediaDiagnostics) {
+ joinTrace.setAttr('meeting.setup.id', mediaDiagnostics.setupId);
+ joinTrace.setAttr(
+ 'meeting.join.microphone_access',
+ mediaDiagnostics.microphone
+ );
+ joinTrace.setAttr('meeting.join.camera_access', mediaDiagnostics.camera);
+ }
joinTrace.setAttr('meeting.join.outcome', 'cancelled');
try {
await joinTrace.span('meeting.join.previous_session', async () => {
@@ -126,6 +142,14 @@ export function createMeetingSession(capabilities: MeetingSessionCapabilities) {
setCredentials(issued.credentials);
joinTrace.setAttr('call.id', issued.credentials.callId);
const localTracks = claimLocalTracks();
+ joinTrace.setAttr(
+ 'meeting.join.microphone_track',
+ Boolean(localTracks?.microphone)
+ );
+ joinTrace.setAttr(
+ 'meeting.join.camera_track',
+ Boolean(localTracks?.camera)
+ );
const credentials = issued.credentials;
await joinTrace.span('meeting.join.connect', () =>
capabilities.connect(
diff --git a/apps/web/src/features/meetings/views/meeting-page.tsx b/apps/web/src/features/meetings/views/meeting-page.tsx
index 7290465ad6..0bf6cef773 100644
--- a/apps/web/src/features/meetings/views/meeting-page.tsx
+++ b/apps/web/src/features/meetings/views/meeting-page.tsx
@@ -121,15 +121,19 @@ export function MeetingPage(props: {
return;
// The call publishes the preview tracks rather than re-opening the
// devices, so the waiting room is the only place permission is asked.
- return session.join(props.authenticated() ? undefined : name(), {
- microphoneEnabled: media.microphoneEnabled(),
- cameraEnabled: media.cameraEnabled(),
- microphoneDeviceId: media.selectedDevices().microphone,
- cameraDeviceId: media.selectedDevices().camera,
- speakerDeviceId: media.selectedDevices().speaker,
- backgroundEffect: media.backgroundEffect(),
- localTracks: media.handoff(),
- });
+ return session.join(
+ props.authenticated() ? undefined : name(),
+ {
+ microphoneEnabled: media.microphoneEnabled(),
+ cameraEnabled: media.cameraEnabled(),
+ microphoneDeviceId: media.selectedDevices().microphone,
+ cameraDeviceId: media.selectedDevices().camera,
+ speakerDeviceId: media.selectedDevices().speaker,
+ backgroundEffect: media.backgroundEffect(),
+ localTracks: media.handoff(),
+ },
+ media.diagnostics()
+ );
};
async function leave() {
if (leaving()) return;
diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.md
index 7b9a3fc3b6..8177094b8f 100644
--- a/docs/agent-guide/calls.md
+++ b/docs/agent-guide/calls.md
@@ -163,6 +163,44 @@ and image-upload menu as the join screen; the caret pins this panel for keyboard
and touch access. Click outside or press Escape to close the settings.
The controls also work by keyboard and touch.
+### Browser call diagnostics
+
+Browser OpenTelemetry requires `enable-browser-otel` (or
+`VITE_ENABLE_BROWSER_OTEL=true`) and a configured exporter. PostHog deliberately
+drops events on private call-link routes; it is not a substitute for these traces.
+Existing `call_action`, audio-processing, and receiver-health analytics describe
+other parts of the call, not waiting-room permission outcomes.
+
+Find `meeting.join` by `call.id`, then use its `meeting.setup.id` to find that
+page's earlier `call.media.capture` spans, including guest attempts. The setup ID
+is random and scoped to the page owner; it is not derived from the share token.
+Each capture records the device, whether it was enabled, the trigger, outcome,
+and whether the captured stream was retained. Camera permission can succeed
+while its toggle remains off. A pending request cancelled by navigation ends
+with `cancelled`; a camera constraint fallback emits `call.media.constraints_retry`.
+Join records final `meeting.join.microphone_access` / `camera_access`, enabled
+flags, and whether each live preview track was handed to the call.
+
+Failures include an allowlisted `error.type`: `NotAllowedError` or `SecurityError`
+indicates blocked access (browser, OS, or policy), not proof the user explicitly
+clicked Deny. `NotFoundError`, `NotReadableError`, and `OverconstrainedError`
+help distinguish missing devices, capture failures, and unsupported constraints.
+Unknown provider errors are redacted. Raw error messages, device labels/IDs,
+guest names, and bearer URLs/tokens are not attributes.
+
+`call.connect` and background `call.media.setup` are children of the join flow.
+`call.media.publish_prejoin`, `enable`, and `toggle` expose publishing/capture
+failures after admission; `enumerate` and `background` cover waiting-room
+device lists and effects. A completed join/setup does not imply every device
+worked: inspect its media children. Later toggles and connection-state samples
+are searchable by `call.id`. `call.connection.disconnected` records the SDK's
+numeric reason when available. These spans cover the browser LiveKit path,
+not the native CallKit media implementation.
+
+Verify allowing and blocking each device, joining with both off, granting
+access on retry, and leaving while a prompt is pending. Confirm setup and join
+share the setup ID and that media failures remain visible when join succeeds.
+
### Sharing a call
With quick calls enabled, channel calls use the same **Copy Meeting Url** button
diff --git a/docs/agent-guide/observability.md b/docs/agent-guide/observability.md
index ec164c7de8..db7d53d304 100644
--- a/docs/agent-guide/observability.md
+++ b/docs/agent-guide/observability.md
@@ -107,7 +107,12 @@ covers an accepted button press through connection or failure:
The root records `meeting.join.kind` (`create` or `join`), guest status,
microphone/camera preferences, `call.id` once credentials arrive, and
`meeting.join.outcome` (`connected`, `failed`, `cancelled`, or `already_in_call`).
-It does not measure setup-page loading or completion of background media setup.
+Its duration excludes setup-page loading and completion of background media
+setup. The `call.media.setup` child continues after the join root ends; inspect
+its per-device children for capture and publishing failures. Earlier waiting-room
+captures correlate through `meeting.setup.id`, and the join records final device
+access states. See [browser call diagnostics](calls.md#browser-call-diagnostics)
+for fields, failure interpretation, and verification.
Never add share tokens or RTC credentials to trace attributes or errors.
The HTTP requests can have separate trace IDs across asynchronous mutation