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): cancel answered calls across tabs (#5541)
Peter Chinman2f9e2a883828
diff --git a/apps/web/src/features/block-call/sidebar/incoming-calls.ts b/apps/web/src/features/block-call/sidebar/incoming-calls.tsindex 3b1090d212..5c639fdd64 100644--- a/apps/web/src/features/block-call/sidebar/incoming-calls.ts+++ b/apps/web/src/features/block-call/sidebar/incoming-calls.ts@@ -4,14 +4,24 @@ import {stopCallRinger,} from '@channel/Call/CallStartedNotifier';import { createCallEventsEffect } from '@channel/Call/call-events';+import {+ createCallResolutionsEffect,+ getCallRecordResolution,+ publishCallResolution,+} from '@channel/Call/call-resolution';import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';+import { isTabFocused } from '@core/signal/tabFocus';+import { fetchCallRecord } from '@queries/call/call';import {type Accessor,createEffect,createMemo,createSignal,+ on,onCleanup,+ untrack,} from 'solid-js';export type IncomingCall = {@@ -41,6 +51,7 @@ declare global {// renders incoming calls can be hidden while a call is still ringing.const [incomingCalls, setIncomingCalls] = createSignal<IncomingCall[]>([]);const incomingCallTimeouts = new Map<string, number>();+const INCOMING_CALL_RECONCILE_INTERVAL_MS = 4_000;function clearIncomingCallTimeouts() {for (const timeoutId of incomingCallTimeouts.values()) {@@ -85,6 +96,23 @@ function addIncomingCall(call: IncomingCall) {});}+async function reconcileIncomingCall(call: IncomingCall, userId: string) {+ try {+ // The stale time matches the reconcile interval so overlapping triggers+ // (interval + focus + online) collapse into one request per cycle.+ const record = await fetchCallRecord(+ call.callId,+ INCOMING_CALL_RECONCILE_INTERVAL_MS+ );+ const resolution = getCallRecordResolution(record, userId);+ if (resolution) publishCallResolution(resolution);+ } catch (error) {+ // The websocket and cross-tab transports remain the primary paths. A+ // transient reconciliation failure should not disturb the active ring.+ console.warn('incoming call reconciliation failed', error);+ }+}+export function useVisibleIncomingCalls(): Accessor<IncomingCall[]> {const channelsCtx = useChannelsContext();const callCtx = useCallContextOptional();@@ -121,11 +149,22 @@ export function useIncomingCallWidgetVisible() {* Mount once near the app root, alongside `<CallStartedNotifier />` — *not** inside the sidebar. The store is module-level and per-call auto-dismiss* timers bound its growth, so tracking must not be tied to whether the widget- * that renders it happens to be visible.+ * that renders it happens to be visible. Instant dismissal on answer/end+ * arrives via call resolutions, which `<CallStartedNotifier />` publishes+ * from the websocket events — without it mounted, dismissal degrades to the+ * reconciliation poll below.*/export function IncomingCallEvents() {const callCtx = useCallContextOptional();const channelsCtx = useChannelsContext();+ const userId = useUserId();++ createCallResolutionsEffect((resolution) => {+ if (resolution.type === 'answered' && resolution.answeredBy !== userId()) {+ return;+ }+ dismissIncomingCall(resolution.callId);+ });createEffect(() => {if (!DEV_MODE_ENV) return;@@ -170,11 +209,60 @@ export function IncomingCallEvents() {if (activeCallId) dismissIncomingCall(activeCallId);});- createCallEventsEffect({- onCallEnded: ({ callId }) => dismissIncomingCall(callId),+ // Dev-only debug calls (`window.macroDebugIncomingCall`) have no server+ // record to reconcile against.+ const reconcilableCalls = createMemo(() =>+ incomingCalls().filter(+ (call) => !(DEV_MODE_ENV && call.callId.startsWith('debug-'))+ )+ );+ const shouldReconcile = createMemo(+ () => reconcilableCalls().length > 0 && !!userId()+ );- onCallAnswered: ({ callId }) => dismissIncomingCall(callId),+ const reconcile = () => {+ const currentUserId = userId();+ if (!currentUserId) return;+ if (typeof navigator !== 'undefined' && !navigator.onLine) return;+ for (const call of reconcilableCalls()) {+ void reconcileIncomingCall(call, currentUserId);+ }+ };+ // Websocket events are intentionally one-shot and are not replayed after a+ // background tab reconnects. While calls are ringing, periodically compare+ // them with the authoritative call record. Overlapping triggers are deduped+ // by the query cache inside `reconcileIncomingCall`; the boolean memo gate+ // keeps the interval from restarting every time the call set changes.+ createEffect(() => {+ if (!shouldReconcile()) return;++ untrack(reconcile);+ const intervalId = window.setInterval(+ reconcile,+ INCOMING_CALL_RECONCILE_INTERVAL_MS+ );+ window.addEventListener('online', reconcile);++ onCleanup(() => {+ window.clearInterval(intervalId);+ window.removeEventListener('online', reconcile);+ });+ });++ // The interval is throttled while the tab is hidden; re-check as soon as+ // the tab regains focus.+ createEffect(+ on(+ isTabFocused,+ (focused) => {+ if (focused && shouldReconcile()) reconcile();+ },+ { defer: true }+ )+ );++ createCallEventsEffect({onCallStarted: ({ channelId, callId, createdBy, isFromSelf }) => {if (callCtx?.activeCallId() === callId) return;if (isFromSelf) return;diff --git a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx b/apps/web/src/features/channel/Call/CallStartedNotifier.tsxindex 053ed94cb0..8e789c9e6e 100644--- a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx+++ b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx@@ -1,4 +1,5 @@import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';import { usePlatformNotificationState } from '@notifications';import { DefaultUserNameResolver } from '@notifications/notification-resolvers';import {@@ -8,6 +9,10 @@ import {} from '@queries/call/call';import { useCallContext } from './CallContext';import { createCallEventsEffect } from './call-events';+import {+ createCallResolutionsEffect,+ publishCallResolution,+} from './call-resolution';import { joinChannelCall } from './join-channel-call';const RING_VOLUME = 0.11;@@ -188,6 +193,11 @@ function startRingingLoop(* `call_ended` both stop the ring; `call_answered` additionally closes the* incoming-call notification since the user is already in the call.*+ * This component is the sole bridge from those one-shot websocket events to+ * published call resolutions (`call-resolution.ts`) — resolution consumers+ * like `IncomingCallEvents` rely on it being mounted for instant dismissal,+ * falling back to their reconciliation poll otherwise.+ ** Mount once near the app root, inside `<CallProvider>` and* `<ChannelsContextProvider>`. The backend already excludes the caller from* the broadcast (`call_service::send_call_event` filters on@@ -198,17 +208,37 @@ export function CallStartedNotifier() {const callCtx = useCallContext();const channelsCtx = useChannelsContext();const notif = usePlatformNotificationState();+ const userId = useUserId();++ createCallResolutionsEffect((resolution) => {+ if (resolution.type === 'answered') {+ if (resolution.answeredBy !== userId()) return;+ stopCallRinger(resolution.callId);+ closeCallNotification(resolution.callId);+ return;+ }++ stopCallRinger(resolution.callId);+ setActiveCallEndedCache({+ channelId: resolution.channelId,+ callId: resolution.callId,+ });+ void invalidateActiveCallQueries();+ });createCallEventsEffect({onCallEnded: ({ channelId, callId }) => {- stopCallRinger(callId);- setActiveCallEndedCache({ channelId, callId });- void invalidateActiveCallQueries();+ publishCallResolution({ type: 'ended', channelId, callId });},- onCallAnswered: ({ callId }) => {- stopCallRinger(callId);- closeCallNotification(callId);+ onCallAnswered: ({ callId, answeredBy }) => {+ const answeringUserId = answeredBy ?? userId();+ if (!answeringUserId) return;+ publishCallResolution({+ type: 'answered',+ callId,+ answeredBy: answeringUserId,+ });},onCallStarted: ({ channelId, callId, createdBy, isFromSelf }) => {diff --git a/apps/web/src/features/channel/Call/call-resolution.ts b/apps/web/src/features/channel/Call/call-resolution.tsnew file mode 100644index 0000000000..c187fc1d4e--- /dev/null+++ b/apps/web/src/features/channel/Call/call-resolution.ts@@ -0,0 +1,194 @@+import type { CallRecord } from '@service-call/client';+import { onCleanup } from 'solid-js';+import { match, P } from 'ts-pattern';++/**+ * Cross-tab fan-out of terminal incoming-call states ("answered"/"ended"), so+ * a ring resolved in one tab stops in every tab even when a background tab+ * missed the one-shot websocket event.+ *+ * Resolutions publish over a BroadcastChannel, with a localStorage `storage`+ * event as fallback for embedded browsers where BroadcastChannel is missing+ * or unreliable. The channel is a hand-rolled module-level singleton rather+ * than `@solid-primitives/broadcast-channel`: the primitive constructs+ * `BroadcastChannel` unguarded (it would throw in exactly the environments+ * the fallback exists for) and ties the channel's lifetime to a reactive+ * owner, while publishes here happen from async owner-less contexts and the+ * subscription registry must outlive any subscribing component.+ */++const CALL_RESOLUTION_CHANNEL = 'macro-call-resolution';+const CALL_RESOLUTION_STORAGE_KEY = 'macro.call-resolution';++export type CallResolution =+ | {+ type: 'answered';+ callId: string;+ answeredBy: string;+ }+ | {+ type: 'ended';+ callId: string;+ channelId: string;+ };++type CallResolutionHandler = (resolution: CallResolution) => void;++const handlers = new Set<CallResolutionHandler>();+const handledResolutionKeys = new Set<string>();+const MAX_HANDLED_RESOLUTIONS = 100;+let broadcastChannel: BroadcastChannel | null | undefined;+let isStorageListenerAttached = false;++function getResolutionKey(resolution: CallResolution) {+ return resolution.type === 'answered'+ ? `${resolution.type}:${resolution.callId}:${resolution.answeredBy}`+ : `${resolution.type}:${resolution.callId}`;+}++function parseCallResolution(value: unknown): CallResolution | null {+ return match(value)+ .with(+ { type: 'answered', callId: P.string, answeredBy: P.string },+ ({ type, callId, answeredBy }) => ({ type, callId, answeredBy })+ )+ .with(+ { type: 'ended', callId: P.string, channelId: P.string },+ ({ type, callId, channelId }) => ({ type, callId, channelId })+ )+ .otherwise(() => null);+}++function emitCallResolution(value: unknown) {+ const resolution = parseCallResolution(value);+ if (!resolution) return;++ const key = getResolutionKey(resolution);+ if (handledResolutionKeys.has(key)) return;+ handledResolutionKeys.add(key);+ if (handledResolutionKeys.size > MAX_HANDLED_RESOLUTIONS) {+ const oldestKey = handledResolutionKeys.values().next().value;+ if (oldestKey) handledResolutionKeys.delete(oldestKey);+ }++ for (const handler of handlers) {+ try {+ handler(resolution);+ } catch (error) {+ console.error('Failed to handle call resolution', error);+ }+ }+}++function getBroadcastChannel() {+ if (broadcastChannel !== undefined) return broadcastChannel;+ if (typeof BroadcastChannel === 'undefined') {+ broadcastChannel = null;+ return broadcastChannel;+ }++ try {+ broadcastChannel = new BroadcastChannel(CALL_RESOLUTION_CHANNEL);+ broadcastChannel.addEventListener('message', (event) =>+ emitCallResolution(event.data)+ );+ } catch {+ broadcastChannel = null;+ }++ return broadcastChannel;+}++function handleStorage(event: StorageEvent) {+ if (event.key !== CALL_RESOLUTION_STORAGE_KEY || !event.newValue) return;++ try {+ emitCallResolution(JSON.parse(event.newValue));+ } catch {+ // Ignore malformed or stale values from older clients.+ }+}++function attachStorageListener() {+ if (isStorageListenerAttached || typeof window === 'undefined') return;+ window.addEventListener('storage', handleStorage);+ isStorageListenerAttached = true;+}++/**+ * Publishes a terminal incoming-call state to this tab and sibling tabs.+ * BroadcastChannel is the primary transport; localStorage is a fallback for+ * embedded browsers where BroadcastChannel delivery is unreliable.+ */+export function publishCallResolution(resolution: CallResolution) {+ emitCallResolution(resolution);++ try {+ getBroadcastChannel()?.postMessage(resolution);+ } catch {+ // The storage event below remains available as a cross-tab fallback.+ }++ try {+ localStorage.setItem(+ CALL_RESOLUTION_STORAGE_KEY,+ JSON.stringify(resolution)+ );+ } catch {+ // Storage can be disabled in private or embedded browser contexts —+ // there, even reading the `localStorage` global throws (a `typeof` check+ // would not catch that, since the global resolves but its getter throws).+ }+}++/** Subscribes to call resolutions originating locally or in another tab. */+export function subscribeToCallResolutions(handler: CallResolutionHandler) {+ handlers.add(handler);+ getBroadcastChannel();+ attachStorageListener();++ return () => {+ handlers.delete(handler);+ };+}++/**+ * Subscribes to call resolutions for the lifetime of the owning component.+ * Must be called during component setup, mirroring `createCallEventsEffect`.+ */+export function createCallResolutionsEffect(handler: CallResolutionHandler) {+ onCleanup(subscribeToCallResolutions(handler));+}++/**+ * Converts authoritative call-record state into a terminal ring resolution.+ * A historic participant row still counts as answered even if the user has+ * since left while the call remains active.+ */+export function getCallRecordResolution(+ record: Pick<+ CallRecord,+ 'callId' | 'channelId' | 'isActive' | 'participants'+ >,+ userId: string+): CallResolution | null {+ if (!record.isActive) {+ return {+ type: 'ended',+ callId: record.callId,+ channelId: record.channelId,+ };+ }++ if (+ record.participants.some((participant) => participant.userId === userId)+ ) {+ return {+ type: 'answered',+ callId: record.callId,+ answeredBy: userId,+ };+ }++ return null;+}diff --git a/apps/web/src/features/channel/Call/tests/call-resolution.test.ts b/apps/web/src/features/channel/Call/tests/call-resolution.test.tsnew file mode 100644index 0000000000..61e1356ed6--- /dev/null+++ b/apps/web/src/features/channel/Call/tests/call-resolution.test.ts@@ -0,0 +1,195 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++class MockBroadcastChannel {+ static instance: MockBroadcastChannel | undefined;++ readonly postMessage = vi.fn();+ private messageHandler: ((event: { data: unknown }) => void) | undefined;++ constructor(readonly name: string) {+ MockBroadcastChannel.instance = this;+ }++ addEventListener(_type: string, handler: (event: { data: unknown }) => void) {+ this.messageHandler = handler;+ }++ emit(data: unknown) {+ this.messageHandler?.({ data });+ }+}++describe('call resolution signaling', () => {+ beforeEach(() => {+ localStorage.clear();+ MockBroadcastChannel.instance = undefined;+ vi.resetModules();+ vi.stubGlobal('BroadcastChannel', MockBroadcastChannel);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('publishes to this tab and both cross-tab transports', async () => {+ const { publishCallResolution, subscribeToCallResolutions } = await import(+ '../call-resolution'+ );+ const handler = vi.fn();+ const unsubscribe = subscribeToCallResolutions(handler);+ const resolution = {+ type: 'answered' as const,+ callId: 'call-1',+ answeredBy: 'macro|[email protected]',+ };++ publishCallResolution(resolution);++ expect(handler).toHaveBeenCalledWith(resolution);+ expect(MockBroadcastChannel.instance?.name).toBe('macro-call-resolution');+ expect(MockBroadcastChannel.instance?.postMessage).toHaveBeenCalledWith(+ resolution+ );+ expect(+ JSON.parse(localStorage.getItem('macro.call-resolution') ?? '')+ ).toEqual(resolution);++ // Both transports can deliver the same cross-tab message.+ MockBroadcastChannel.instance?.emit(resolution);+ window.dispatchEvent(+ new StorageEvent('storage', {+ key: 'macro.call-resolution',+ newValue: JSON.stringify(resolution),+ })+ );+ expect(handler).toHaveBeenCalledTimes(1);+ unsubscribe();+ });++ it('receives valid BroadcastChannel and storage fallback messages', async () => {+ const { subscribeToCallResolutions } = await import('../call-resolution');+ const handler = vi.fn();+ const unsubscribe = subscribeToCallResolutions(handler);+ const answered = {+ type: 'answered',+ callId: 'call-1',+ answeredBy: 'macro|[email protected]',+ };+ const ended = {+ type: 'ended',+ channelId: 'channel-1',+ callId: 'call-2',+ };++ MockBroadcastChannel.instance?.emit(answered);+ MockBroadcastChannel.instance?.emit({ type: 'answered' });+ window.dispatchEvent(+ new StorageEvent('storage', {+ key: 'macro.call-resolution',+ newValue: JSON.stringify(ended),+ })+ );++ expect(handler).toHaveBeenNthCalledWith(1, answered);+ expect(handler).toHaveBeenNthCalledWith(2, ended);+ expect(handler).toHaveBeenCalledTimes(2);+ unsubscribe();+ });++ it('createCallResolutionsEffect unsubscribes when its owner is disposed', async () => {+ const { createRoot } = await import('solid-js');+ const { createCallResolutionsEffect, publishCallResolution } = await import(+ '../call-resolution'+ );+ const handler = vi.fn();+ const whileMounted = {+ type: 'ended' as const,+ channelId: 'channel-1',+ callId: 'call-1',+ };++ createRoot((dispose) => {+ createCallResolutionsEffect(handler);+ publishCallResolution(whileMounted);+ dispose();+ });+ publishCallResolution({ ...whileMounted, callId: 'call-2' });++ expect(handler).toHaveBeenCalledTimes(1);+ expect(handler).toHaveBeenCalledWith(whileMounted);+ });+});++describe('getCallRecordResolution', () => {+ it('resolves an active call after the user has joined, even if they left', async () => {+ const { getCallRecordResolution } = await import('../call-resolution');++ expect(+ getCallRecordResolution(+ {+ callId: 'call-1',+ channelId: 'channel-1',+ isActive: true,+ participants: [+ {+ userId: 'macro|[email protected]',+ joinedAt: '2026-08-10T10:00:00.000Z',+ leftAt: '2026-08-10T10:01:00.000Z',+ },+ ],+ },+ 'macro|[email protected]'+ )+ ).toEqual({+ type: 'answered',+ callId: 'call-1',+ answeredBy: 'macro|[email protected]',+ });+ });++ it('keeps ringing when a different user answered', async () => {+ const { getCallRecordResolution } = await import('../call-resolution');++ expect(+ getCallRecordResolution(+ {+ callId: 'call-1',+ channelId: 'channel-1',+ isActive: true,+ participants: [+ {+ userId: 'macro|[email protected]',+ joinedAt: '2026-08-10T10:00:00.000Z',+ leftAt: '2026-08-10T10:01:00.000Z',+ },+ ],+ },+ 'macro|[email protected]'+ )+ ).toBeNull();+ });++ it('resolves an inactive call as ended and leaves an unanswered call alone', async () => {+ const { getCallRecordResolution } = await import('../call-resolution');+ const unansweredRecord = {+ callId: 'call-1',+ channelId: 'channel-1',+ isActive: true,+ participants: [],+ };++ expect(+ getCallRecordResolution(unansweredRecord, 'macro|[email protected]')+ ).toBeNull();+ expect(+ getCallRecordResolution(+ { ...unansweredRecord, isActive: false },+ 'macro|[email protected]'+ )+ ).toEqual({+ type: 'ended',+ callId: 'call-1',+ channelId: 'channel-1',+ });+ });+});diff --git a/apps/web/src/features/channel/Call/use-call.ts b/apps/web/src/features/channel/Call/use-call.tsindex 7b7dcf0c20..28c19d96b4 100644--- a/apps/web/src/features/channel/Call/use-call.ts+++ b/apps/web/src/features/channel/Call/use-call.ts@@ -1,5 +1,6 @@import { analytics } from '@app/lib/analytics';import { useChannelsContext } from '@core/context/channels';+import { useUserId } from '@core/context/user';import { throwOnErr } from '@core/util/result';import {invalidateActiveCallQueries,@@ -10,6 +11,7 @@ import { useMutation } from '@tanstack/solid-query';import type { DisconnectReason } from 'livekit-client';import { createEffect, createSignal, onCleanup } from 'solid-js';import { useCallContext } from './CallContext';+import { publishCallResolution } from './call-resolution';import { LK_DISCONNECT_REASON, LK_ROOM_EVENT } from './livekit-loader';import { registerCallKitCallEndedHandler } from './use-callkit';@@ -67,6 +69,7 @@ let leaveInFlight = false;export function useCall(channelId: () => string, options?: UseCallOptions) {const callCtx = useCallContext();const channelsCtx = useChannelsContext();+ const userId = useUserId();const leaveMutation = useLeaveCallMutation();// Track the disconnect listener so we can swap it when the room changes.@@ -176,6 +179,19 @@ export function useCall(channelId: () => string, options?: UseCallOptions) {channelTitle:channelsCtx.channelsById()[tokenResponse.channelId]?.name ?? null,});+ if (cancelled) return;++ // Publish only once the session is connected — a cancelled or+ // timed-out join must not silence this user's ring on other tabs.+ // (onError sets `cancelled` via cancelCurrentJoin.)+ const answeringUserId = userId();+ if (answeringUserId) {+ publishCallResolution({+ type: 'answered',+ callId: tokenResponse.callId,+ answeredBy: answeringUserId,+ });+ }};const timeout = new Promise<never>((_, reject) =>diff --git a/apps/web/src/lib/queries/call/call.ts b/apps/web/src/lib/queries/call/call.tsindex 97b0b11946..79b6ef3e47 100644--- a/apps/web/src/lib/queries/call/call.ts+++ b/apps/web/src/lib/queries/call/call.ts@@ -158,6 +158,18 @@ export function useCallRecordQuery(callId: Accessor<string>) {}));}+export function fetchCallRecord(+ callId: string,+ staleTimeMs: number+): Promise<CallRecord> {+ return queryClient.fetchQuery({+ queryKey: callKeys.record(callId).queryKey,+ queryFn: async () =>+ await throwOnErr(() => callServiceClient.getCallRecord(callId)),+ staleTime: staleTimeMs,+ });+}+export function setCallRecordShareWithTeamCache(callId: string,shareWithTeam: boolean