Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(calls): audio and mic change issues (#4861)
Will Hutchinsonccbbf3cfeeef
diff --git a/apps/web/src/features/channel/Call/CallContext.tsx b/apps/web/src/features/channel/Call/CallContext.tsxindex 937a9067f8..a0253d2a97 100644--- a/apps/web/src/features/channel/Call/CallContext.tsx+++ b/apps/web/src/features/channel/Call/CallContext.tsx@@ -24,6 +24,7 @@ import {type CallSessionDisconnectOptions,createCallSessionController,} from './CallSessionController';+import { createLatestAsyncRequestQueue } from './latest-async-request-queue';import {getKrisp,getLivekit,@@ -94,6 +95,18 @@ type NativeAudioProcessingSupportedConstraints =voiceIsolation?: boolean;};+type AudioDeviceSwitchRequest = {+ room: Room;+ deviceId: string;+};++function audioDeviceSwitchRequestsAreEqual(+ left: AudioDeviceSwitchRequest,+ right: AudioDeviceSwitchRequest+): boolean {+ return left.room === right.room && left.deviceId === right.deviceId;+}+function supportedNativeAudioProcessingConstraints(): NativeAudioProcessingSupportedConstraints | null {return ((navigator.mediaDevices?.getSupportedConstraints?.() as@@ -927,39 +940,94 @@ function createCallState() {}}- async function switchAudioInput(deviceId: string) {- const r = room();- if (!r) return;+ function isCurrentLivekitRoom(targetRoom: Room): boolean {+ return (+ room() === targetRoom &&+ targetRoom.state !== LK_CONNECTION_STATE.Disconnected+ );+ }++ async function applyAudioInputSwitch({+ room: targetRoom,+ deviceId,+ }: AudioDeviceSwitchRequest): Promise<void> {+ if (!isCurrentLivekitRoom(targetRoom)) return;++ const activeDeviceId = targetRoom.getActiveDevice('audioinput');+ if (+ activeDeviceId === deviceId ||+ (!activeDeviceId && store.activeAudioInputDeviceId === deviceId)+ ) {+ return;+ }++ await targetRoom.switchActiveDevice('audioinput', deviceId);+ if (!isCurrentLivekitRoom(targetRoom)) return;++ setStore('activeAudioInputDeviceId', deviceId);++ const microphonePublication =+ targetRoom.localParticipant.getTrackPublication(+ LK_TRACK_SOURCE.Microphone+ );+ const microphoneTrack = microphonePublication?.track as+ | LocalTrack+ | undefined;+ if (+ !store.isAudioMuted &&+ !microphonePublication?.isMuted &&+ isLiveLocalTrack(microphoneTrack)+ ) {+ await ensureNoiseSuppressionOnMicTrack(targetRoom);+ }+ }++ async function applyAudioOutputSwitch({+ room: targetRoom,+ deviceId,+ }: AudioDeviceSwitchRequest): Promise<void> {+ if (!isCurrentLivekitRoom(targetRoom)) return;++ const activeDeviceId = targetRoom.getActiveDevice('audiooutput');+ if (+ activeDeviceId === deviceId ||+ (!activeDeviceId && store.activeAudioOutputDeviceId === deviceId)+ ) {+ return;+ }++ await targetRoom.switchActiveDevice('audiooutput', deviceId);+ if (!isCurrentLivekitRoom(targetRoom)) return;++ setStore('activeAudioOutputDeviceId', deviceId);+ }++ const enqueueAudioInputSwitch = createLatestAsyncRequestQueue(+ applyAudioInputSwitch,+ audioDeviceSwitchRequestsAreEqual+ );+ const enqueueAudioOutputSwitch = createLatestAsyncRequestQueue(+ applyAudioOutputSwitch,+ audioDeviceSwitchRequestsAreEqual+ );++ async function switchAudioInput(deviceId: string): Promise<void> {+ const targetRoom = room();+ if (!targetRoom) return;+try {- await r.switchActiveDevice('audioinput', deviceId);- setStore('activeAudioInputDeviceId', deviceId);-- // If the mic is live, cycle mute/unmute as a nudge for devices where- // switchActiveDevice's internal track restart doesn't take. Note this- // is NOT a republish: setMicrophoneEnabled(true, opts) ignores the- // capture options when the muted publication survives- // (stopMicTrackOnMute is false), so the device change itself always- // comes from switchActiveDevice above.- if (!store.isAudioMuted) {- await r.localParticipant.setMicrophoneEnabled(false);- await r.localParticipant.setMicrophoneEnabled(- true,- currentMicrophoneCaptureOptions(deviceId)- );- // The mic track may have changed — re-apply the selected audio processing.- await ensureNoiseSuppressionOnMicTrack(r);- }+ await enqueueAudioInputSwitch({ room: targetRoom, deviceId });} catch (e) {console.error('failed to switch audio input device', e);}}- async function switchAudioOutput(deviceId: string) {- const r = room();- if (!r) return;+ async function switchAudioOutput(deviceId: string): Promise<void> {+ const targetRoom = room();+ if (!targetRoom) return;+try {- await r.switchActiveDevice('audiooutput', deviceId);- setStore('activeAudioOutputDeviceId', deviceId);+ await enqueueAudioOutputSwitch({ room: targetRoom, deviceId });} catch (e) {console.error('failed to switch audio output device', e);}diff --git a/apps/web/src/features/channel/Call/latest-async-request-queue.ts b/apps/web/src/features/channel/Call/latest-async-request-queue.tsnew file mode 100644index 0000000000..1f53f2c4a2--- /dev/null+++ b/apps/web/src/features/channel/Call/latest-async-request-queue.ts@@ -0,0 +1,85 @@+export type LatestAsyncRequestQueue<Request> = (+ request: Request+) => Promise<void>;++type RequestEntry<Request> = {+ request: Request;+ callers: Caller[];+};++type Caller = {+ resolve: () => void;+ reject: (reason: unknown) => void;+};++/**+ * Creates a single-flight queue that keeps only the latest request received+ * while the executor is active.+ *+ * Callers whose pending request is replaced settle with the replacement. A+ * request equal to the active or pending request reuses that execution.+ */+export function createLatestAsyncRequestQueue<Request>(+ executor: (request: Request) => Promise<void>,+ requestsAreEqual: (left: Request, right: Request) => boolean = Object.is+): LatestAsyncRequestQueue<Request> {+ let active: RequestEntry<Request> | undefined;+ let pending: RequestEntry<Request> | undefined;++ async function execute(entry: RequestEntry<Request>): Promise<void> {+ let failure: unknown;+ let failed = false;++ try {+ await executor(entry.request);+ } catch (error) {+ failed = true;+ failure = error;+ } finally {+ active = undefined;++ if (pending) {+ active = pending;+ pending = undefined;+ void execute(active);+ }+ }++ for (const caller of entry.callers) {+ if (failed) {+ caller.reject(failure);+ } else {+ caller.resolve();+ }+ }+ }++ return function enqueue(request: Request): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ const caller = { resolve, reject };++ if (!active) {+ active = { request, callers: [caller] };+ void execute(active);+ return;+ }++ if (requestsAreEqual(active.request, request)) {+ active.callers.push(caller);+ if (pending) {+ active.callers.push(...pending.callers);+ pending = undefined;+ }+ return;+ }++ if (pending) {+ pending.callers.push(caller);+ pending.request = request;+ return;+ }++ pending = { request, callers: [caller] };+ });+ };+}diff --git a/apps/web/src/features/channel/Call/tests/latest-async-request-queue.test.ts b/apps/web/src/features/channel/Call/tests/latest-async-request-queue.test.tsnew file mode 100644index 0000000000..503415cf85--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/latest-async-request-queue.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it, vi } from 'vitest';+import { createLatestAsyncRequestQueue } from '../latest-async-request-queue';++type Deferred = {+ promise: Promise<void>;+ resolve: () => void;+ reject: (reason: unknown) => void;+};++function createDeferred(): Deferred {+ let resolve: () => void = () => {};+ let reject: (reason: unknown) => void = () => {};+ const promise = new Promise<void>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise;+ reject = rejectPromise;+ });++ return { promise, resolve, reject };+}++async function nextMicrotask(): Promise<void> {+ await Promise.resolve();+}++describe('createLatestAsyncRequestQueue', () => {+ it('executes requests strictly one at a time', async () => {+ const executions = [createDeferred(), createDeferred()];+ let activeExecutions = 0;+ let maximumActiveExecutions = 0;+ const executor = vi.fn(async () => {+ const execution = executions[executor.mock.calls.length - 1];+ activeExecutions += 1;+ maximumActiveExecutions = Math.max(+ maximumActiveExecutions,+ activeExecutions+ );+ await execution.promise;+ activeExecutions -= 1;+ });+ const enqueue = createLatestAsyncRequestQueue(executor);++ const first = enqueue('first');+ const second = enqueue('second');++ expect(executor).toHaveBeenCalledTimes(1);+ executions[0].resolve();+ await first;+ expect(executor).toHaveBeenCalledTimes(2);+ expect(maximumActiveExecutions).toBe(1);++ executions[1].resolve();+ await second;+ expect(maximumActiveExecutions).toBe(1);+ });++ it('retains only the latest request received during an execution', async () => {+ const firstExecution = createDeferred();+ const executor = vi.fn(async (request: string) => {+ if (request === 'first') await firstExecution.promise;+ });+ const enqueue = createLatestAsyncRequestQueue(executor);++ const first = enqueue('first');+ const replaced = enqueue('replaced');+ const latest = enqueue('latest');++ expect(executor).toHaveBeenCalledTimes(1);+ firstExecution.resolve();+ await Promise.all([first, replaced, latest]);++ expect(executor.mock.calls).toEqual([['first'], ['latest']]);+ });++ it('suppresses duplicate active and pending requests', async () => {+ const firstExecution = createDeferred();+ const secondExecution = createDeferred();+ const executor = vi.fn(async (request: string) => {+ if (request === 'first') await firstExecution.promise;+ if (request === 'second') await secondExecution.promise;+ });+ const enqueue = createLatestAsyncRequestQueue(executor);++ const first = enqueue('first');+ const duplicateActive = enqueue('first');+ const second = enqueue('second');+ const duplicatePending = enqueue('second');++ firstExecution.resolve();+ await Promise.all([first, duplicateActive]);+ expect(executor.mock.calls).toEqual([['first'], ['second']]);++ secondExecution.resolve();+ await Promise.all([second, duplicatePending]);+ expect(executor.mock.calls).toEqual([['first'], ['second']]);+ });++ it('settles callers whose requests are replaced by the latest request', async () => {+ const firstExecution = createDeferred();+ const latestExecution = createDeferred();+ const executor = vi.fn(async (request: number) => {+ if (request === 1) await firstExecution.promise;+ if (request === 3) await latestExecution.promise;+ });+ const enqueue = createLatestAsyncRequestQueue(executor);+ let replacedSettled = false;++ const first = enqueue(1);+ const replaced = enqueue(2).finally(() => {+ replacedSettled = true;+ });+ const latest = enqueue(3);++ firstExecution.resolve();+ await first;+ expect(replacedSettled).toBe(false);++ latestExecution.resolve();+ await Promise.all([replaced, latest]);+ expect(replacedSettled).toBe(true);+ });++ it('continues with pending and later requests after executor rejection', async () => {+ const failedExecution = createDeferred();+ const executor = vi.fn(async (request: string) => {+ if (request === 'fails') await failedExecution.promise;+ });+ const enqueue = createLatestAsyncRequestQueue(executor);+ const failure = new Error('device switch failed');++ const failed = enqueue('fails');+ const pending = enqueue('pending');+ failedExecution.reject(failure);++ await expect(failed).rejects.toBe(failure);+ await expect(pending).resolves.toBeUndefined();+ await expect(enqueue('later')).resolves.toBeUndefined();+ expect(executor.mock.calls).toEqual([['fails'], ['pending'], ['later']]);+ });++ it('allows consumers to discard stale requests without blocking the queue', async () => {+ let currentCall = 'new-call';+ const applied: string[] = [];+ const enqueue = createLatestAsyncRequestQueue(async (call: string) => {+ if (call !== currentCall) return;+ applied.push(call);+ });++ await enqueue('old-call');+ await enqueue(currentCall);+ currentCall = 'newer-call';+ await enqueue(currentCall);+ await nextMicrotask();++ expect(applied).toEqual(['new-call', 'newer-call']);+ });+});