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(call): stop desktop ringing when call answered on another device (#4846)

Peter Chinmanc75f5d5c446d
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index 4d5df93497..8228b14cc7 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -3,11 +3,8 @@ import { ROUTER_BASE_CONCAT } from '@app/constants/routerBase';
import Banner from '@app/features/auth/banner/Banner';
import { GithubReauthenticationPrompt } from '@app/features/auth/GithubReauthenticationPrompt';
import { GmailReauthenticationPrompt } from '@app/features/auth/GmailReauthenticationPrompt';
-import {
- IncomingCallWidgetEvents,
- SidebarActiveCallWidget,
- useIncomingCallWidgetVisible,
-} from '@app/features/block-call/sidebar/active-call-widget';
+import { SidebarActiveCallWidget } from '@app/features/block-call/sidebar/active-call-widget';
+import { useIncomingCallWidgetVisible } from '@app/features/block-call/sidebar/incoming-calls';
import { CommandMenu } from '@app/features/command';
import { FavoritesCommands } from '@app/features/command/FavoritesCommands';
import {
@@ -426,9 +423,6 @@ function LayoutInner(props: RouteSectionProps) {
<CommandMenu />
</Suspense>
</Show>
- <Show when={isSidebarVisible()}>
- <IncomingCallWidgetEvents />
- </Show>
<Suspense>
<PropertyEditorModal />
</Suspense>
diff --git a/apps/web/src/features/block-call/sidebar/active-call-widget.tsx b/apps/web/src/features/block-call/sidebar/active-call-widget.tsx
index ee34c2c260..7f57768c73 100644
--- a/apps/web/src/features/block-call/sidebar/active-call-widget.tsx
+++ b/apps/web/src/features/block-call/sidebar/active-call-widget.tsx
@@ -1,22 +1,16 @@
-import { useCallContextOptional } from '@channel/Call/CallContext';
-import { stopCallRinger } from '@channel/Call/CallStartedNotifier';
import { joinChannelCall } from '@channel/Call/join-channel-call';
import { openChannelCallTab } from '@channel/Call/open-channel-call-tab';
import type { SidebarState } from '@components/app/app-sidebar/sidebar';
import { ContextMenuContent, MenuItem } from '@core/component/ContextMenu';
-import { DEV_MODE_ENV, ENABLE_CALLS } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
import { useUserId } from '@core/context/user';
import PhoneIcon from '@icon/wide-call.svg';
import { ContextMenu } from '@kobalte/core/context-menu';
import XIcon from '@phosphor/x.svg';
-import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';
import { ChannelTypeEnum } from '@service-storage/client';
import { Avatar, Button, cn, Tooltip } from '@ui';
import {
- type Accessor,
- createEffect,
createMemo,
createSignal,
type FlowComponent,
@@ -24,46 +18,9 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import { dismissIncomingCall, useVisibleIncomingCalls } from './incoming-calls';
const SLIM_MAX = 4;
-const MAX_RING_DURATION_MS = 30_000;
-
-type IncomingCall = {
- channelId: string;
- callId: string;
- createdAt: string;
- createdBy: string | null;
-};
-
-type CallStartedPayload = {
- channel_id?: string;
- call_id?: string;
- created_by?: string | null;
-};
-
-type CallEndedPayload = {
- channel_id?: string;
- call_id?: string;
-};
-
-type DebugIncomingCallOptions = {
- channelId?: string;
- callId?: string;
- createdAt?: string;
- createdBy?: string | null;
-};
-
-declare global {
- interface Window {
- macroDebugIncomingCall?: (
- options?: DebugIncomingCallOptions
- ) => IncomingCall | null;
- macroClearDebugIncomingCalls?: () => void;
- }
-}
-
-const [incomingCalls, setIncomingCalls] = createSignal<IncomingCall[]>([]);
-const incomingCallTimeouts = new Map<string, number>();
function displayName(channel: ApiChannelWithLatest | undefined) {
if (!channel) return 'Channel';
@@ -151,25 +108,6 @@ function formatDuration(startedAt: string | undefined, nowMs: number) {
return `${minutes}:${seconds.toString().padStart(2, '0')}`;
}
-function safeJsonParse(s: string): unknown {
- try {
- return JSON.parse(s);
- } catch {
- return null;
- }
-}
-
-function parsePayload(raw: unknown): CallStartedPayload | null {
- const obj =
- typeof raw === 'string'
- ? safeJsonParse(raw)
- : typeof raw === 'object'
- ? raw
- : null;
- if (!obj || typeof obj !== 'object') return null;
- return obj as CallStartedPayload;
-}
-
type IncomingCallContextMenuProps = {
callId: string;
channelId: string;
@@ -198,169 +136,6 @@ const IncomingCallContextMenu: FlowComponent<IncomingCallContextMenuProps> = (
);
};
-function clearIncomingCallTimeouts() {
- for (const timeoutId of incomingCallTimeouts.values()) {
- window.clearTimeout(timeoutId);
- }
- incomingCallTimeouts.clear();
-}
-
-function dismissIncomingCall(callId: string) {
- stopCallRinger(callId);
- const timeoutId = incomingCallTimeouts.get(callId);
- if (timeoutId !== undefined) {
- window.clearTimeout(timeoutId);
- incomingCallTimeouts.delete(callId);
- }
- setIncomingCalls((calls) => calls.filter((call) => call.callId !== callId));
-}
-
-function addIncomingCall(call: IncomingCall) {
- const existingTimeoutId = incomingCallTimeouts.get(call.callId);
- if (existingTimeoutId !== undefined) {
- window.clearTimeout(existingTimeoutId);
- }
- incomingCallTimeouts.set(
- call.callId,
- window.setTimeout(
- () => dismissIncomingCall(call.callId),
- MAX_RING_DURATION_MS
- )
- );
-
- setIncomingCalls((calls) => {
- const withoutDuplicate = calls.filter(
- (candidate) =>
- candidate.callId !== call.callId &&
- candidate.channelId !== call.channelId
- );
- return [call, ...withoutDuplicate].sort(
- (a, b) =>
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
- );
- });
-}
-
-function useVisibleIncomingCalls(): Accessor<IncomingCall[]> {
- const channelsCtx = useChannelsContext();
- const callCtx = useCallContextOptional();
-
- return createMemo(() => {
- const channelsById = channelsCtx.channelsById();
- const joinedChannelId = callCtx?.isInCall()
- ? callCtx.activeChannelId()
- : null;
- const joinedCallId = callCtx?.isInCall() ? callCtx.activeCallId() : null;
-
- return incomingCalls()
- .filter((call) => {
- if (!channelsById[call.channelId]) return false;
- return (
- call.channelId !== joinedChannelId && call.callId !== joinedCallId
- );
- })
- .sort(
- (a, b) =>
- new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
- );
- });
-}
-
-export function useIncomingCallWidgetVisible() {
- const visibleIncomingCalls = useVisibleIncomingCalls();
- return createMemo(() => visibleIncomingCalls().length > 0);
-}
-
-export function IncomingCallWidgetEvents() {
- const callCtx = useCallContextOptional();
- const channelsCtx = useChannelsContext();
- const userId = useUserId();
-
- createEffect(() => {
- if (!DEV_MODE_ENV) return;
-
- window.macroDebugIncomingCall = (options = {}) => {
- const channelsById = channelsCtx.channelsById();
- const channelId = options.channelId ?? Object.keys(channelsById)[0];
-
- if (!channelId || !channelsById[channelId]) {
- console.warn(
- '[incoming-call-widget] No cached channel found for debug call',
- options
- );
- return null;
- }
-
- const call = {
- channelId,
- callId:
- options.callId ??
- `debug-${globalThis.crypto?.randomUUID?.() ?? Date.now()}`,
- createdAt: options.createdAt ?? new Date().toISOString(),
- createdBy: options.createdBy ?? 'debug',
- };
- addIncomingCall(call);
- return call;
- };
-
- window.macroClearDebugIncomingCalls = () => {
- clearIncomingCallTimeouts();
- setIncomingCalls([]);
- };
-
- onCleanup(() => {
- delete window.macroDebugIncomingCall;
- delete window.macroClearDebugIncomingCalls;
- });
- });
-
- onCleanup(() => {
- clearIncomingCallTimeouts();
- setIncomingCalls([]);
- });
-
- createEffect(() => {
- const activeCallId = callCtx?.activeCallId();
- if (activeCallId) dismissIncomingCall(activeCallId);
- });
-
- createConnectionWebsocketEffect((data) => {
- if (!ENABLE_CALLS()) return;
-
- const payload = parsePayload(data.data);
- if (!payload) return;
-
- if (data.type === 'call_ended') {
- const { channel_id: channelId, call_id: callId } =
- payload as CallEndedPayload;
- if (!channelId || !callId) return;
-
- dismissIncomingCall(callId);
- return;
- }
-
- if (data.type !== 'call_started') return;
-
- const {
- channel_id: channelId,
- call_id: callId,
- created_by: createdBy,
- } = payload;
- if (!channelId || !callId) return;
- if (callCtx?.activeCallId() === callId) return;
- if (createdBy && createdBy === userId()) return;
-
- addIncomingCall({
- channelId,
- callId,
- createdAt: new Date().toISOString(),
- createdBy: createdBy ?? null,
- });
- });
-
- return null;
-}
-
export function SidebarActiveCallWidget(props: {
sidebarState: SidebarState;
class?: string;
diff --git a/apps/web/src/features/block-call/sidebar/incoming-calls.ts b/apps/web/src/features/block-call/sidebar/incoming-calls.ts
new file mode 100644
index 0000000000..3b1090d212
--- /dev/null
+++ b/apps/web/src/features/block-call/sidebar/incoming-calls.ts
@@ -0,0 +1,192 @@
+import { useCallContextOptional } from '@channel/Call/CallContext';
+import {
+ MAX_RING_DURATION_MS,
+ stopCallRinger,
+} from '@channel/Call/CallStartedNotifier';
+import { createCallEventsEffect } from '@channel/Call/call-events';
+import { DEV_MODE_ENV } from '@core/constant/featureFlags';
+import { useChannelsContext } from '@core/context/channels';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ onCleanup,
+} from 'solid-js';
+
+export type IncomingCall = {
+ channelId: string;
+ callId: string;
+ createdAt: string;
+ createdBy: string | null;
+};
+
+type DebugIncomingCallOptions = {
+ channelId?: string;
+ callId?: string;
+ createdAt?: string;
+ createdBy?: string | null;
+};
+
+declare global {
+ interface Window {
+ macroDebugIncomingCall?: (
+ options?: DebugIncomingCallOptions
+ ) => IncomingCall | null;
+ macroClearDebugIncomingCalls?: () => void;
+ }
+}
+
+// Module-level so the store outlives any single widget mount — the sidebar that
+// renders incoming calls can be hidden while a call is still ringing.
+const [incomingCalls, setIncomingCalls] = createSignal<IncomingCall[]>([]);
+const incomingCallTimeouts = new Map<string, number>();
+
+function clearIncomingCallTimeouts() {
+ for (const timeoutId of incomingCallTimeouts.values()) {
+ window.clearTimeout(timeoutId);
+ }
+ incomingCallTimeouts.clear();
+}
+
+export function dismissIncomingCall(callId: string) {
+ stopCallRinger(callId);
+ const timeoutId = incomingCallTimeouts.get(callId);
+ if (timeoutId !== undefined) {
+ window.clearTimeout(timeoutId);
+ incomingCallTimeouts.delete(callId);
+ }
+ setIncomingCalls((calls) => calls.filter((call) => call.callId !== callId));
+}
+
+function addIncomingCall(call: IncomingCall) {
+ const existingTimeoutId = incomingCallTimeouts.get(call.callId);
+ if (existingTimeoutId !== undefined) {
+ window.clearTimeout(existingTimeoutId);
+ }
+ incomingCallTimeouts.set(
+ call.callId,
+ window.setTimeout(
+ () => dismissIncomingCall(call.callId),
+ MAX_RING_DURATION_MS
+ )
+ );
+
+ setIncomingCalls((calls) => {
+ const withoutDuplicate = calls.filter(
+ (candidate) =>
+ candidate.callId !== call.callId &&
+ candidate.channelId !== call.channelId
+ );
+ return [call, ...withoutDuplicate].sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+ );
+ });
+}
+
+export function useVisibleIncomingCalls(): Accessor<IncomingCall[]> {
+ const channelsCtx = useChannelsContext();
+ const callCtx = useCallContextOptional();
+
+ return createMemo(() => {
+ const channelsById = channelsCtx.channelsById();
+ const joinedChannelId = callCtx?.isInCall()
+ ? callCtx.activeChannelId()
+ : null;
+ const joinedCallId = callCtx?.isInCall() ? callCtx.activeCallId() : null;
+
+ return incomingCalls()
+ .filter((call) => {
+ if (!channelsById[call.channelId]) return false;
+ return (
+ call.channelId !== joinedChannelId && call.callId !== joinedCallId
+ );
+ })
+ .sort(
+ (a, b) =>
+ new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
+ );
+ });
+}
+
+export function useIncomingCallWidgetVisible() {
+ const visibleIncomingCalls = useVisibleIncomingCalls();
+ return createMemo(() => visibleIncomingCalls().length > 0);
+}
+
+/**
+ * Keeps the incoming-call store in sync with the call websocket events.
+ *
+ * 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.
+ */
+export function IncomingCallEvents() {
+ const callCtx = useCallContextOptional();
+ const channelsCtx = useChannelsContext();
+
+ createEffect(() => {
+ if (!DEV_MODE_ENV) return;
+
+ window.macroDebugIncomingCall = (options = {}) => {
+ const channelsById = channelsCtx.channelsById();
+ const channelId = options.channelId ?? Object.keys(channelsById)[0];
+
+ if (!channelId || !channelsById[channelId]) {
+ console.warn(
+ '[incoming-call-widget] No cached channel found for debug call',
+ options
+ );
+ return null;
+ }
+
+ const call = {
+ channelId,
+ callId:
+ options.callId ??
+ `debug-${globalThis.crypto?.randomUUID?.() ?? Date.now()}`,
+ createdAt: options.createdAt ?? new Date().toISOString(),
+ createdBy: options.createdBy ?? 'debug',
+ };
+ addIncomingCall(call);
+ return call;
+ };
+
+ window.macroClearDebugIncomingCalls = () => {
+ clearIncomingCallTimeouts();
+ setIncomingCalls([]);
+ };
+
+ onCleanup(() => {
+ delete window.macroDebugIncomingCall;
+ delete window.macroClearDebugIncomingCalls;
+ });
+ });
+
+ createEffect(() => {
+ const activeCallId = callCtx?.activeCallId();
+ if (activeCallId) dismissIncomingCall(activeCallId);
+ });
+
+ createCallEventsEffect({
+ onCallEnded: ({ callId }) => dismissIncomingCall(callId),
+
+ onCallAnswered: ({ callId }) => dismissIncomingCall(callId),
+
+ onCallStarted: ({ channelId, callId, createdBy, isFromSelf }) => {
+ if (callCtx?.activeCallId() === callId) return;
+ if (isFromSelf) return;
+
+ addIncomingCall({
+ channelId,
+ callId,
+ createdAt: new Date().toISOString(),
+ createdBy,
+ });
+ },
+ });
+
+ return null;
+}
diff --git a/apps/web/src/features/channel/Call/CallEventSync.tsx b/apps/web/src/features/channel/Call/CallEventSync.tsx
index 4d5a7ac457..7b6cba3600 100644
--- a/apps/web/src/features/channel/Call/CallEventSync.tsx
+++ b/apps/web/src/features/channel/Call/CallEventSync.tsx
@@ -1,13 +1,5 @@
-import { createConnectionWebsocketEffect } from '@service-connection/websocket';
-import { match } from 'ts-pattern';
import { useCallContext } from './CallContext';
-
-type CallShareWithTeamToggledPayload = {
- call_id: string;
- channel_id: string;
- share_with_team: boolean;
- toggled_by: string | null;
-};
+import { createCallEventsEffect } from './call-events';
/**
* Applies connection-gateway events that mutate active-call state held in
@@ -23,17 +15,11 @@ type CallShareWithTeamToggledPayload = {
export function CallEventSync() {
const callCtx = useCallContext();
- createConnectionWebsocketEffect((data) => {
- const payload =
- typeof data.data === 'string' ? JSON.parse(data.data) : data.data;
-
- match(data)
- .with({ type: 'call_share_with_team_toggled' }, () => {
- const typed = payload as CallShareWithTeamToggledPayload;
- if (typed.call_id !== callCtx.activeCallId()) return;
- callCtx.setSharedWithTeam(typed.share_with_team);
- })
- .otherwise(() => {});
+ createCallEventsEffect({
+ onShareWithTeamToggled: ({ callId, shareWithTeam }) => {
+ if (callId !== callCtx.activeCallId()) return;
+ callCtx.setSharedWithTeam(shareWithTeam);
+ },
});
return null;
diff --git a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
index 74f26ee336..053ed94cb0 100644
--- a/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
+++ b/apps/web/src/features/channel/Call/CallStartedNotifier.tsx
@@ -1,6 +1,4 @@
-import { ENABLE_CALLS } from '@core/constant/featureFlags';
import { useChannelsContext } from '@core/context/channels';
-import { useUserId } from '@core/context/user';
import { usePlatformNotificationState } from '@notifications';
import { DefaultUserNameResolver } from '@notifications/notification-resolvers';
import {
@@ -8,21 +6,10 @@ import {
setActiveCallEndedCache,
setActiveCallStartedCache,
} from '@queries/call/call';
-import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import { useCallContext } from './CallContext';
+import { createCallEventsEffect } from './call-events';
import { joinChannelCall } from './join-channel-call';
-type CallStartedPayload = {
- channel_id?: string;
- call_id?: string;
- created_by?: string | null;
-};
-
-type CallEndedPayload = {
- channel_id?: string;
- call_id?: string;
-};
-
const RING_VOLUME = 0.11;
const RING_NOTE_DURATION_S = 0.09;
const RING_NOTE_GAP_S = 0.075;
@@ -34,9 +21,12 @@ const RING_CHIME_FREQUENCIES_HZ = [
];
// Phone-style cadence: re-ring every few seconds while the call is incoming.
const RING_INTERVAL_MS = 4_000;
-// Stop ringing after this long if the user neither answers nor dismisses, so
-// a missed call doesn't keep noise-making forever.
-const MAX_RING_DURATION_MS = 30_000;
+/**
+ * Stop ringing after this long if the user neither answers nor dismisses, so
+ * a missed call doesn't keep noise-making forever. Shared with the incoming
+ * call store so its auto-dismiss stays in lockstep with the ringer.
+ */
+export const MAX_RING_DURATION_MS = 30_000;
type WebkitWindow = Window & { webkitAudioContext?: typeof AudioContext };
type RingSound = { durationMs: number; stop: () => void };
@@ -44,11 +34,28 @@ type Ringer = { stop: () => void };
const activeCallRingers = new Map<string, Ringer>();
+// Incoming-call notification handles by call id, so the toast can be closed
+// when the ring resolves remotely (answered on another device). Best-effort:
+// the Tauri notification handle's close() is currently a no-op.
+const activeCallNotifications = new Map<string, { close: () => void }>();
+
+// Notifications still being created (showNotification is async), so a remote
+// answer that lands mid-flight can cancel the toast once it materializes
+// instead of leaving a stale requireInteraction toast up indefinitely.
+const pendingCallNotifications = new Map<string, { cancelled: boolean }>();
+
export function stopCallRinger(callId: string) {
activeCallRingers.get(callId)?.stop();
activeCallRingers.delete(callId);
}
+function closeCallNotification(callId: string) {
+ const pending = pendingCallNotifications.get(callId);
+ if (pending) pending.cancelled = true;
+ activeCallNotifications.get(callId)?.close();
+ activeCallNotifications.delete(callId);
+}
+
function startCallRinger(
callId: string,
shouldStop: () => boolean,
@@ -172,29 +179,15 @@ function startRingingLoop(
return { stop };
}
-function safeJsonParse(s: string): unknown {
- try {
- return JSON.parse(s);
- } catch {
- return null;
- }
-}
-
-function parsePayload(raw: unknown): CallStartedPayload | null {
- const obj =
- typeof raw === 'string'
- ? safeJsonParse(raw)
- : typeof raw === 'object'
- ? raw
- : null;
- if (!obj || typeof obj !== 'object') return null;
- return obj as CallStartedPayload;
-}
-
/**
* Listens for `call_started` websocket events broadcast to channel members
* and surfaces a browser notification + ring tone for the recipients.
*
+ * Also resolves the ring remotely: `call_answered` (sent to just this user
+ * when they join the call on any device, e.g. answering on iPhone) and
+ * `call_ended` both stop the ring; `call_answered` additionally closes the
+ * incoming-call notification since the user is already in the call.
+ *
* 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
@@ -203,56 +196,45 @@ function parsePayload(raw: unknown): CallStartedPayload | null {
*/
export function CallStartedNotifier() {
const callCtx = useCallContext();
- const userId = useUserId();
const channelsCtx = useChannelsContext();
const notif = usePlatformNotificationState();
- createConnectionWebsocketEffect((data) => {
- if (!ENABLE_CALLS()) return;
-
- const payload = parsePayload(data.data);
- if (!payload) return;
-
- if (data.type === 'call_ended') {
- const { channel_id: channelId, call_id: callId } =
- payload as CallEndedPayload;
- if (!channelId || !callId) return;
-
+ createCallEventsEffect({
+ onCallEnded: ({ channelId, callId }) => {
stopCallRinger(callId);
setActiveCallEndedCache({ channelId, callId });
void invalidateActiveCallQueries();
- return;
- }
+ },
- if (data.type !== 'call_started') return;
-
- const {
- channel_id: channelId,
- call_id: callId,
- created_by: createdBy,
- } = payload;
- if (!channelId || !callId) return;
-
- const createdAt = new Date().toISOString();
- setActiveCallStartedCache({
- channelId,
- callId,
- createdAt,
- createdBy: createdBy ?? '',
- });
- void invalidateActiveCallQueries();
-
- if (callCtx.activeCallId() === callId) return;
- if (createdBy && createdBy === userId()) return;
-
- void emitCallStartedNotification({
- channelId,
- callId,
- createdBy: createdBy ?? null,
- channelName: channelsCtx.channelsById()[channelId]?.name ?? undefined,
- notif,
- isJoined: () => callCtx.activeCallId() === callId,
- });
+ onCallAnswered: ({ callId }) => {
+ stopCallRinger(callId);
+ closeCallNotification(callId);
+ },
+
+ onCallStarted: ({ channelId, callId, createdBy, isFromSelf }) => {
+ const createdAt = new Date().toISOString();
+ setActiveCallStartedCache({
+ channelId,
+ callId,
+ createdAt,
+ createdBy: createdBy ?? '',
+ });
+ void invalidateActiveCallQueries();
+
+ // The cache above is updated for every call, including our own; only the
+ // ring and the toast are skipped when we're already in it or started it.
+ if (callCtx.activeCallId() === callId) return;
+ if (isFromSelf) return;
+
+ void emitCallStartedNotification({
+ channelId,
+ callId,
+ createdBy,
+ channelName: channelsCtx.channelsById()[channelId]?.name ?? undefined,
+ notif,
+ isJoined: () => callCtx.activeCallId() === callId,
+ });
+ },
});
return null;
@@ -276,32 +258,55 @@ async function emitCallStartedNotification(args: {
if (notif === 'not-supported') return;
- const callerName =
- (createdBy ? await DefaultUserNameResolver(createdBy) : undefined) ??
- 'Someone';
- const target = channelName ? ` in ${channelName}` : '';
-
- const handle = await notif.showNotification({
- title: `Incoming call${target}`,
- options: {
- body: `${callerName} started a call`,
- // Keep the toast visible until the user answers or dismisses it,
- // instead of the browser's default few-second auto-dismiss.
- requireInteraction: true,
- // Collapse duplicate broadcasts (e.g. multi-device) into one toast.
- tag: `call-${callId}`,
- },
- });
+ const pending = { cancelled: false };
+ pendingCallNotifications.set(callId, pending);
+ try {
+ const callerName =
+ (createdBy ? await DefaultUserNameResolver(createdBy) : undefined) ??
+ 'Someone';
+ const target = channelName ? ` in ${channelName}` : '';
+
+ const handle = await notif.showNotification({
+ title: `Incoming call${target}`,
+ options: {
+ body: `${callerName} started a call`,
+ // Keep the toast visible until the user answers or dismisses it,
+ // instead of the browser's default few-second auto-dismiss.
+ requireInteraction: true,
+ // Collapse duplicate broadcasts (e.g. multi-device) into one toast.
+ tag: `call-${callId}`,
+ },
+ });
- if (handle === 'not-granted' || handle === 'disabled-in-ui') return;
+ if (handle === 'not-granted' || handle === 'disabled-in-ui') return;
- handle.onClick(() => {
- window.focus();
- void joinChannelCall(channelId);
- handle.close();
- ringer.stop();
- });
- handle.onDismiss(() => {
- ringer.stop();
- });
+ // The call was answered remotely while the toast was being created.
+ if (pending.cancelled) {
+ handle.close();
+ return;
+ }
+
+ activeCallNotifications.set(callId, handle);
+
+ const untrack = () => {
+ if (activeCallNotifications.get(callId) === handle) {
+ activeCallNotifications.delete(callId);
+ }
+ };
+ handle.onClick(() => {
+ window.focus();
+ void joinChannelCall(channelId);
+ handle.close();
+ untrack();
+ ringer.stop();
+ });
+ handle.onDismiss(() => {
+ untrack();
+ ringer.stop();
+ });
+ } finally {
+ if (pendingCallNotifications.get(callId) === pending) {
+ pendingCallNotifications.delete(callId);
+ }
+ }
}
diff --git a/apps/web/src/features/channel/Call/call-events.ts b/apps/web/src/features/channel/Call/call-events.ts
new file mode 100644
index 0000000000..093d848eaa
--- /dev/null
+++ b/apps/web/src/features/channel/Call/call-events.ts
@@ -0,0 +1,231 @@
+import { ENABLE_CALLS } from '@core/constant/featureFlags';
+import { useUserId } from '@core/context/user';
+import {
+ createConnectionWebsocketEffect,
+ parseWebsocketPayload,
+} from '@service-connection/websocket';
+import { match } from 'ts-pattern';
+
+/**
+ * Single source of truth for the call events broadcast over the connection
+ * gateway websocket. The wire payloads are hand-rolled `serde_json::json!`
+ * literals in `crates/call/src/domain/service.rs` — there are no generated
+ * types for them — so the snake_case shapes below are mirrored by hand and kept
+ * private to this module. Consumers only ever see the normalized camelCase
+ * events.
+ */
+
+type CallStartedWirePayload = {
+ channel_id?: string;
+ call_id?: string;
+ created_by?: string | null;
+};
+
+type CallEndedWirePayload = {
+ channel_id?: string;
+ call_id?: string;
+};
+
+type CallAnsweredWirePayload = {
+ channel_id?: string;
+ call_id?: string;
+ user_id?: string | null;
+};
+
+type CallShareWithTeamToggledWirePayload = {
+ channel_id?: string;
+ call_id?: string;
+ share_with_team?: boolean;
+ toggled_by?: string | null;
+};
+
+/** A call was started in a channel the user is a member of. */
+export type CallStartedEvent = {
+ channelId: string;
+ callId: string;
+ createdBy: string | null;
+};
+
+/** A call ended — broadcast to every member of the channel. */
+export type CallEndedEvent = {
+ channelId: string;
+ callId: string;
+};
+
+/**
+ * The user joined a call on one of their devices. Sent only to the answering
+ * user's own connections, so every other device can stop ringing.
+ */
+export type CallAnsweredEvent = {
+ channelId: string | null;
+ callId: string;
+ answeredBy: string | null;
+};
+
+/** A participant flipped the call's share-with-team flag. */
+export type CallShareWithTeamToggledEvent = {
+ channelId: string;
+ callId: string;
+ shareWithTeam: boolean;
+ toggledBy: string | null;
+};
+
+export type CallEvent =
+ | ({ type: 'call_started' } & CallStartedEvent)
+ | ({ type: 'call_ended' } & CallEndedEvent)
+ | ({ type: 'call_answered' } & CallAnsweredEvent)
+ | ({
+ type: 'call_share_with_team_toggled';
+ } & CallShareWithTeamToggledEvent);
+
+export type CallEventType = CallEvent['type'];
+
+const CALL_EVENT_TYPES = new Set<string>([
+ 'call_started',
+ 'call_ended',
+ 'call_answered',
+ 'call_share_with_team_toggled',
+]);
+
+export function isCallEventType(type: string): type is CallEventType {
+ return CALL_EVENT_TYPES.has(type);
+}
+
+/**
+ * Normalizes a raw websocket frame into a typed call event, or `null` when the
+ * frame is not a call event, is malformed, or is missing the identifiers every
+ * consumer needs. Pure — exported for tests.
+ */
+export function parseCallEvent(
+ type: string,
+ rawData: unknown
+): CallEvent | null {
+ if (!isCallEventType(type)) return null;
+
+ const payload = parseWebsocketPayload<unknown>(type, rawData);
+ if (!payload || typeof payload !== 'object') return null;
+
+ return match(type)
+ .with('call_started', (eventType) => {
+ const {
+ channel_id: channelId,
+ call_id: callId,
+ created_by: createdBy,
+ } = payload as CallStartedWirePayload;
+ if (!channelId || !callId) return null;
+ return {
+ type: eventType,
+ channelId,
+ callId,
+ createdBy: createdBy ?? null,
+ };
+ })
+ .with('call_ended', (eventType) => {
+ const { channel_id: channelId, call_id: callId } =
+ payload as CallEndedWirePayload;
+ if (!channelId || !callId) return null;
+ return { type: eventType, channelId, callId };
+ })
+ .with('call_answered', (eventType) => {
+ // `channel_id` is on the wire but no consumer needs it, so only the call
+ // id is required here.
+ const {
+ channel_id: channelId,
+ call_id: callId,
+ user_id: answeredBy,
+ } = payload as CallAnsweredWirePayload;
+ if (!callId) return null;
+ return {
+ type: eventType,
+ channelId: channelId ?? null,
+ callId,
+ answeredBy: answeredBy ?? null,
+ };
+ })
+ .with('call_share_with_team_toggled', (eventType) => {
+ const {
+ channel_id: channelId,
+ call_id: callId,
+ share_with_team: shareWithTeam,
+ toggled_by: toggledBy,
+ } = payload as CallShareWithTeamToggledWirePayload;
+ if (!channelId || !callId || typeof shareWithTeam !== 'boolean') {
+ return null;
+ }
+ return {
+ type: eventType,
+ channelId,
+ callId,
+ shareWithTeam,
+ toggledBy: toggledBy ?? null,
+ };
+ })
+ .exhaustive();
+}
+
+type CallEventHandlers = {
+ /**
+ * `isFromSelf` is true when this client's user started the call, i.e. a
+ * multi-device echo. The event is still delivered so consumers can update
+ * shared state before deciding whether to notify.
+ */
+ onCallStarted?: (event: CallStartedEvent & { isFromSelf: boolean }) => void;
+ onCallEnded?: (event: CallEndedEvent) => void;
+ onCallAnswered?: (event: CallAnsweredEvent) => void;
+ onShareWithTeamToggled?: (event: CallShareWithTeamToggledEvent) => void;
+};
+
+/**
+ * Subscribes to the call events on the connection-gateway websocket, handling
+ * the feature-flag gate, payload parsing, field validation and the answered-on-
+ * another-device self-filter once for every consumer.
+ *
+ * Must be called during component setup, under `<UserContextProvider>`.
+ */
+export function createCallEventsEffect(handlers: CallEventHandlers) {
+ const userId = useUserId();
+
+ createConnectionWebsocketEffect((data) => {
+ // Check the type before parsing so we don't JSON.parse every frame the app
+ // receives just to discard it.
+ if (!isCallEventType(data.type)) return;
+ if (!ENABLE_CALLS()) return;
+
+ const event = parseCallEvent(data.type, data.data);
+ if (!event) return;
+
+ match(event)
+ .with({ type: 'call_started' }, (event) => {
+ handlers.onCallStarted?.({
+ channelId: event.channelId,
+ callId: event.callId,
+ createdBy: event.createdBy,
+ isFromSelf: !!event.createdBy && event.createdBy === userId(),
+ });
+ })
+ .with({ type: 'call_ended' }, (event) => {
+ handlers.onCallEnded?.({
+ channelId: event.channelId,
+ callId: event.callId,
+ });
+ })
+ .with({ type: 'call_answered' }, (event) => {
+ // Sent only to the answering user's connections, but guard anyway.
+ if (event.answeredBy && event.answeredBy !== userId()) return;
+ handlers.onCallAnswered?.({
+ channelId: event.channelId,
+ callId: event.callId,
+ answeredBy: event.answeredBy,
+ });
+ })
+ .with({ type: 'call_share_with_team_toggled' }, (event) => {
+ handlers.onShareWithTeamToggled?.({
+ channelId: event.channelId,
+ callId: event.callId,
+ shareWithTeam: event.shareWithTeam,
+ toggledBy: event.toggledBy,
+ });
+ })
+ .exhaustive();
+ });
+}
diff --git a/apps/web/src/features/channel/Call/index.ts b/apps/web/src/features/channel/Call/index.ts
index d144bf2a0f..51ceebec08 100644
--- a/apps/web/src/features/channel/Call/index.ts
+++ b/apps/web/src/features/channel/Call/index.ts
@@ -12,10 +12,27 @@ export type {
export { CallControls } from './CallControls/CallControls';
export { CallEventSync } from './CallEventSync';
export { CallOverlay } from './CallOverlay';
-export { CallStartedNotifier, stopCallRinger } from './CallStartedNotifier';
+export {
+ CallStartedNotifier,
+ MAX_RING_DURATION_MS,
+ stopCallRinger,
+} from './CallStartedNotifier';
export { ChannelCallAutoJoin } from './ChannelCallAutoJoin';
export { ChannelCallButton } from './ChannelCallButton';
export { ChannelCallTab } from './ChannelCallTab';
+export type {
+ CallAnsweredEvent,
+ CallEndedEvent,
+ CallEvent,
+ CallEventType,
+ CallShareWithTeamToggledEvent,
+ CallStartedEvent,
+} from './call-events';
+export {
+ createCallEventsEffect,
+ isCallEventType,
+ parseCallEvent,
+} from './call-events';
export { getCallJoinTab, getCallLeaveTab } from './call-tabs';
export type {
InCallPanelControls,
diff --git a/apps/web/src/features/channel/Call/tests/call-events.test.ts b/apps/web/src/features/channel/Call/tests/call-events.test.ts
new file mode 100644
index 0000000000..747d7cc16f
--- /dev/null
+++ b/apps/web/src/features/channel/Call/tests/call-events.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it, vi } from 'vitest';
+import { isCallEventType, parseCallEvent } from '../call-events';
+
+// The connection gateway always sends `data` as a JSON string — see
+// `services/connection_gateway/src/model/message.rs`.
+const wire = (payload: unknown) => JSON.stringify(payload);
+
+describe('isCallEventType', () => {
+ it('accepts the four call events', () => {
+ expect(isCallEventType('call_started')).toBe(true);
+ expect(isCallEventType('call_ended')).toBe(true);
+ expect(isCallEventType('call_answered')).toBe(true);
+ expect(isCallEventType('call_share_with_team_toggled')).toBe(true);
+ });
+
+ it('rejects unrelated event types', () => {
+ expect(isCallEventType('comms_message')).toBe(false);
+ expect(isCallEventType('')).toBe(false);
+ });
+});
+
+describe('parseCallEvent', () => {
+ it('parses call_started from a JSON string', () => {
+ expect(
+ parseCallEvent(
+ 'call_started',
+ wire({ channel_id: 'chan-1', call_id: 'call-1', created_by: 'user-1' })
+ )
+ ).toEqual({
+ type: 'call_started',
+ channelId: 'chan-1',
+ callId: 'call-1',
+ createdBy: 'user-1',
+ });
+ });
+
+ it('parses an already-parsed object payload', () => {
+ expect(
+ parseCallEvent('call_ended', { channel_id: 'chan-1', call_id: 'call-1' })
+ ).toEqual({ type: 'call_ended', channelId: 'chan-1', callId: 'call-1' });
+ });
+
+ it('parses call_answered and defaults the optional fields', () => {
+ expect(
+ parseCallEvent('call_answered', wire({ call_id: 'call-1' }))
+ ).toEqual({
+ type: 'call_answered',
+ channelId: null,
+ callId: 'call-1',
+ answeredBy: null,
+ });
+ });
+
+ it('keeps the answering user id when present', () => {
+ expect(
+ parseCallEvent(
+ 'call_answered',
+ wire({ channel_id: 'chan-1', call_id: 'call-1', user_id: 'user-2' })
+ )
+ ).toEqual({
+ type: 'call_answered',
+ channelId: 'chan-1',
+ callId: 'call-1',
+ answeredBy: 'user-2',
+ });
+ });
+
+ it('parses call_share_with_team_toggled', () => {
+ expect(
+ parseCallEvent(
+ 'call_share_with_team_toggled',
+ wire({
+ channel_id: 'chan-1',
+ call_id: 'call-1',
+ share_with_team: true,
+ toggled_by: 'user-3',
+ })
+ )
+ ).toEqual({
+ type: 'call_share_with_team_toggled',
+ channelId: 'chan-1',
+ callId: 'call-1',
+ shareWithTeam: true,
+ toggledBy: 'user-3',
+ });
+ });
+
+ it('returns null for a non-call event type', () => {
+ expect(parseCallEvent('comms_message', wire({ call_id: 'call-1' }))).toBe(
+ null
+ );
+ });
+
+ it('returns null for malformed JSON without throwing', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(parseCallEvent('call_started', 'not json')).toBe(null);
+ warn.mockRestore();
+ });
+
+ it.each([
+ ['call_started', { call_id: 'call-1' }],
+ ['call_started', { channel_id: 'chan-1' }],
+ ['call_ended', { call_id: 'call-1' }],
+ ['call_ended', { channel_id: 'chan-1' }],
+ ['call_answered', { channel_id: 'chan-1' }],
+ ])('returns null when %s is missing a required id', (type, payload) => {
+ expect(parseCallEvent(type, wire(payload))).toBe(null);
+ });
+
+ it('returns null when share_with_team is not a boolean', () => {
+ expect(
+ parseCallEvent(
+ 'call_share_with_team_toggled',
+ wire({ channel_id: 'chan-1', call_id: 'call-1' })
+ )
+ ).toBe(null);
+ });
+
+ it('returns null for a null payload', () => {
+ expect(parseCallEvent('call_started', wire(null))).toBe(null);
+ });
+});
diff --git a/apps/web/src/lib/queries/sync/SyncProvider.tsx b/apps/web/src/lib/queries/sync/SyncProvider.tsx
index 719fb62834..11b699e7e4 100644
--- a/apps/web/src/lib/queries/sync/SyncProvider.tsx
+++ b/apps/web/src/lib/queries/sync/SyncProvider.tsx
@@ -18,7 +18,10 @@ import { handleTaskDuplicateMatchesUpdated } from '@queries/storage/task-duplica
// listener. Must be imported somewhere that always loads on app start — this
// provider is guaranteed to mount alongside the other sync handlers.
import '@queries/agent-schedule/sync';
-import { createConnectionWebsocketEffect } from '@service-connection/websocket';
+import {
+ createConnectionWebsocketEffect,
+ parseWebsocketPayload,
+} from '@service-connection/websocket';
import type { Accessor, ParentProps } from 'solid-js';
import { match } from 'ts-pattern';
@@ -26,20 +29,6 @@ type SyncProviderProps = ParentProps<{
userId: Accessor<string | undefined>;
}>;
-function parseWebsocketPayload<T>(
- type: string,
- payload: unknown
-): T | undefined {
- if (typeof payload !== 'string') return payload as T;
-
- try {
- return JSON.parse(payload) as T;
- } catch (error) {
- console.warn('Malformed websocket payload', { type, payload, error });
- return undefined;
- }
-}
-
function withParsedWebsocketPayload<T>(
type: string,
payload: unknown,
diff --git a/apps/web/src/lib/service-clients/service-connection/websocket.ts b/apps/web/src/lib/service-clients/service-connection/websocket.ts
index d0dc1f1188..3e847120aa 100644
--- a/apps/web/src/lib/service-clients/service-connection/websocket.ts
+++ b/apps/web/src/lib/service-clients/service-connection/websocket.ts
@@ -27,6 +27,26 @@ export type FromWebsocketMessage = {
data: any;
};
+/**
+ * Safely reads a websocket frame's `data`. The connection gateway always sends
+ * it as a JSON string (see `services/connection_gateway/src/model/message.rs`),
+ * but already-parsed objects pass through unchanged so callers don't need to
+ * care. Returns `undefined` — never throws — when the payload is malformed.
+ */
+export function parseWebsocketPayload<T>(
+ type: string,
+ payload: unknown
+): T | undefined {
+ if (typeof payload !== 'string') return payload as T;
+
+ try {
+ return JSON.parse(payload) as T;
+ } catch (error) {
+ console.warn('Malformed websocket payload', { type, payload, error });
+ return undefined;
+ }
+}
+
async function resolveWsUrl() {
if (ENABLE_BEARER_TOKEN_AUTH) {
const apiToken = await getMacroApiToken();
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index dfa0ff4cb8..a7a3efcf55 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -25,6 +25,7 @@ import { useInvalidateQueriesOnReconnect } from '@app/lib/queries/invalidate-on-
import { useSoupBackfills } from '@app/lib/queries/soup/backfill';
import { setHotkeyRoot } from '@app/signal/hotkeyRoot';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { IncomingCallEvents } from '@block-call/sidebar/incoming-calls';
import { CallProvider } from '@channel/Call/CallContext';
import { CallStartedNotifier } from '@channel/Call/CallStartedNotifier';
import { CallKitSync } from '@channel/Call/use-callkit';
@@ -700,6 +701,7 @@ export function Root() {
<CallProvider>
<CallKitSync />
<CallStartedNotifier />
+ <IncomingCallEvents />
<QuickAccessProvider>
<SearchProvider>
<ChatAttachmentsInit />
diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rs
index 6e290e306a..aed5a13aab 100644
--- a/crates/call/src/domain/service.rs
+++ b/crates/call/src/domain/service.rs
@@ -368,6 +368,33 @@ impl<
.await
.inspect_err(|e| tracing::error!(error=?e, message_type, "failed to send call participant event"));
}
+
+ /// Notify a user's own connections that they answered a call (best-effort).
+ ///
+ /// Unlike [`Self::send_call_event`], this targets only the answering
+ /// user, across all their connected clients, so devices still showing
+ /// the incoming-call UI can dismiss it when the call is answered
+ /// elsewhere (e.g. stop the desktop ring after an iPhone pickup).
+ async fn send_call_answered_event(
+ &self,
+ channel_id: &Uuid,
+ call_id: &Uuid,
+ user_id: MacroUserIdStr<'_>,
+ ) {
+ let _ = self
+ .connection_service
+ .send_channel_message(
+ &[user_id.copied()],
+ "call_answered",
+ serde_json::json!({
+ "channel_id": channel_id,
+ "call_id": call_id,
+ "user_id": user_id,
+ }),
+ )
+ .await
+ .inspect_err(|e| tracing::error!(error=?e, "failed to send call answered event"));
+ }
}
/// Decide the per-user ring status from the room's active call (if any),
@@ -790,6 +817,11 @@ impl<
}
}
+ // Tell the user's other devices the call was answered here so they
+ // can stop showing the incoming-call UI (best-effort).
+ self.send_call_answered_event(channel_id, &call.id, user_id.copied())
+ .await;
+
// Always generate a fresh token (supports reconnection from different devices).
let token = self
.rtc_client
@@ -969,6 +1001,16 @@ impl<
participant = participant_identity.as_ref(),
"reconciled participant_joined via webhook"
);
+ // Native answers (e.g. iPhone CallKit pickup) connect
+ // straight to LiveKit without hitting the join API, so
+ // this webhook is where the user's other devices learn
+ // the ring was answered (best-effort).
+ self.send_call_answered_event(
+ &call.channel_id,
+ &call.id,
+ participant_identity.copied(),
+ )
+ .await;
}
Err(AddParticipantError::UserAlreadyActive) => {
tracing::warn!(
diff --git a/crates/call/src/domain/service/test.rs b/crates/call/src/domain/service/test.rs
index 2a2f2c0ca9..88710a37ea 100644
--- a/crates/call/src/domain/service/test.rs
+++ b/crates/call/src/domain/service/test.rs
@@ -18,9 +18,9 @@ use serde_json::json;
use uuid::Uuid;
use crate::domain::models::{
- ArchivedCall, Call, CallError, CallParticipant, CallRecord, CallRecordTranscriptSegment,
- CallWebhookEvent, DeletedCallRecordStorageKeys, EditCallRecordRequest, EgressS3Config,
- RingStatus, VerifiedRingToken, VoipPushPayloadRequest,
+ AddParticipantError, ArchivedCall, Call, CallError, CallParticipant, CallRecord,
+ CallRecordTranscriptSegment, CallWebhookEvent, DeletedCallRecordStorageKeys,
+ EditCallRecordRequest, EgressS3Config, RingStatus, VerifiedRingToken, VoipPushPayloadRequest,
};
use crate::domain::ports::{
CallRtcClient, CallService, CallSummarizer, MockCallRepository, MockCallRtcClient,
@@ -267,6 +267,47 @@ impl ConnectionService for StubConnectionService {
}
}
+#[derive(Clone)]
+struct SentChannelMessage {
+ users: Vec<String>,
+ message_type: String,
+ message: serde_json::Value,
+}
+
+#[derive(Clone, Default)]
+struct RecordingConnectionService {
+ messages: Arc<Mutex<Vec<SentChannelMessage>>>,
+}
+
+impl RecordingConnectionService {
+ fn messages(&self) -> Vec<SentChannelMessage> {
+ self.messages.lock().unwrap().clone()
+ }
+}
+
+impl ConnectionService for RecordingConnectionService {
+ async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ _invalidation_event: InvalidationEvent<'a, T>,
+ ) -> Result<(), ConnectionError> {
+ Ok(())
+ }
+
+ async fn send_channel_message<'a>(
+ &self,
+ users: &[MacroUserIdStr<'a>],
+ message_type: &str,
+ message: serde_json::Value,
+ ) -> Result<(), ConnectionError> {
+ self.messages.lock().unwrap().push(SentChannelMessage {
+ users: users.iter().map(|u| u.as_ref().to_string()).collect(),
+ message_type: message_type.to_string(),
+ message,
+ });
+ Ok(())
+ }
+}
+
#[derive(Clone, Copy)]
struct StubNotificationIngress;
@@ -406,25 +447,26 @@ fn mock_get_or_create_repo(
repo
}
-type BaseGetOrCreateCallService = CallServiceImpl<
+type BaseGetOrCreateCallService<Cn> = CallServiceImpl<
MockCallRepository,
MockRtcClient,
- StubConnectionService,
+ Cn,
NoOpEntityAccessService,
StubNotificationIngress,
StubRecordingStorage,
NoopCallSummarizer,
>;
-fn build_get_or_create_service<B: MacroEventBroker + Clone>(
+fn build_get_or_create_service<B: MacroEventBroker + Clone, Cn: ConnectionService>(
repo: MockCallRepository,
+ connection_service: Cn,
event_broker: B,
recording_enabled: bool,
) -> impl CallService {
- let service: BaseGetOrCreateCallService = CallServiceImpl::new(
+ let service: BaseGetOrCreateCallService<Cn> = CallServiceImpl::new(
repo,
MockRtcClient::new(),
- StubConnectionService,
+ connection_service,
NoOpEntityAccessService,
StubNotificationIngress,
StubRecordingStorage,
@@ -452,7 +494,8 @@ async fn get_or_create_call(
) -> Result<crate::domain::models::CallTokenResponse, CallError> {
let call = started_event_call(created_by);
let repo = mock_get_or_create_repo(scenario, call, recording_enabled);
- let service = build_get_or_create_service(repo, broker, recording_enabled);
+ let service =
+ build_get_or_create_service(repo, StubConnectionService, broker, recording_enabled);
service
.get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]"))
@@ -573,6 +616,42 @@ async fn malformed_stored_creator_skips_only_started_event() {
assert!(broker.events().is_empty());
}
+#[tokio::test]
+async fn get_or_create_call_sends_call_answered_to_joining_user() {
+ let call = started_event_call(STARTED_EVENT_CREATOR);
+ let repo = mock_get_or_create_repo(GetOrCreateScenario::ExistingCall, call, false);
+ let connection_service = RecordingConnectionService::default();
+ let service = build_get_or_create_service(
+ repo,
+ connection_service.clone(),
+ RecordingEventBroker::default(),
+ false,
+ );
+
+ service
+ .get_or_create_call(&STARTED_EVENT_CHANNEL_ID, user("[email protected]"))
+ .await
+ .expect("joining an existing call succeeds");
+
+ let messages = connection_service.messages();
+ let [message] = messages.as_slice() else {
+ panic!("expected exactly one channel message")
+ };
+ assert_eq!(message.message_type, "call_answered");
+ assert_eq!(
+ message.users,
+ vec![user("[email protected]").as_ref().to_string()]
+ );
+ assert_eq!(
+ message.message,
+ json!({
+ "channel_id": STARTED_EVENT_CHANNEL_ID,
+ "call_id": STARTED_EVENT_CALL_ID,
+ "user_id": user("[email protected]").as_ref(),
+ })
+ );
+}
+
const ARCHIVED_EVENT_CALL_ID: Uuid = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b6d8);
const ARCHIVED_EVENT_CHANNEL_ID: Uuid = Uuid::from_u128(0x4f6f8b0a_6f9f_4a3f_9c3a_2b1e5d4c7a91);
const ARCHIVED_EVENT_ROOM_NAME: &str = "archived-event-room";
@@ -670,10 +749,10 @@ fn webhook_rtc_client(
rtc_client
}
-type BaseWebhookCallService = CallServiceImpl<
+type BaseWebhookCallService<Cn> = CallServiceImpl<
MockCallRepository,
MockCallRtcClient,
- StubConnectionService,
+ Cn,
NoOpEntityAccessService,
StubNotificationIngress,
StubRecordingStorage,
@@ -685,10 +764,19 @@ fn build_webhook_service(
rtc_client: MockCallRtcClient,
event_broker: RecordingEventBroker,
) -> impl CallService {
- let service: BaseWebhookCallService = CallServiceImpl::new(
+ build_webhook_service_with_connection(repo, rtc_client, StubConnectionService, event_broker)
+}
+
+fn build_webhook_service_with_connection<Cn: ConnectionService>(
+ repo: MockCallRepository,
+ rtc_client: MockCallRtcClient,
+ connection_service: Cn,
+ event_broker: RecordingEventBroker,
+) -> impl CallService {
+ let service: BaseWebhookCallService<Cn> = CallServiceImpl::new(
repo,
rtc_client,
- StubConnectionService,
+ connection_service,
NoOpEntityAccessService,
StubNotificationIngress,
StubRecordingStorage,
@@ -873,6 +961,93 @@ async fn malformed_archived_creator_skips_event_without_undoing_archival() {
assert!(event_broker.events().is_empty());
}
+#[tokio::test]
+async fn participant_joined_webhook_sends_call_answered_to_answering_user() {
+ let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |room_name| {
+ assert_eq!(room_name, ARCHIVED_EVENT_ROOM_NAME);
+ Box::pin(async move { Ok(Some(active_call)) })
+ });
+ repo.expect_add_participant()
+ .times(1)
+ .returning(|call_id, participant_identity| {
+ assert_eq!(*call_id, ARCHIVED_EVENT_CALL_ID);
+ assert_eq!(
+ participant_identity.as_ref(),
+ user(ARCHIVED_EVENT_PARTICIPANT).as_ref()
+ );
+ let participant = CallParticipant {
+ call_id: *call_id,
+ user_id: participant_identity.as_ref().to_string(),
+ joined_at: archived_event_started_at(),
+ };
+ Box::pin(async move { Ok(participant) })
+ });
+
+ let rtc_client = webhook_rtc_client("participant_joined", Some(ARCHIVED_EVENT_PARTICIPANT));
+ let connection_service = RecordingConnectionService::default();
+ let service = build_webhook_service_with_connection(
+ repo,
+ rtc_client,
+ connection_service.clone(),
+ RecordingEventBroker::default(),
+ );
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("participant-joined webhook succeeds");
+
+ let messages = connection_service.messages();
+ let [message] = messages.as_slice() else {
+ panic!("expected exactly one channel message")
+ };
+ assert_eq!(message.message_type, "call_answered");
+ assert_eq!(
+ message.users,
+ vec![user(ARCHIVED_EVENT_PARTICIPANT).as_ref().to_string()]
+ );
+ assert_eq!(
+ message.message,
+ json!({
+ "channel_id": ARCHIVED_EVENT_CHANNEL_ID,
+ "call_id": ARCHIVED_EVENT_CALL_ID,
+ "user_id": user(ARCHIVED_EVENT_PARTICIPANT).as_ref(),
+ })
+ );
+}
+
+#[tokio::test]
+async fn participant_joined_webhook_skips_call_answered_on_state_drift() {
+ let active_call = active_call_for_archived_event(ARCHIVED_EVENT_CREATOR, None);
+ let mut repo = MockCallRepository::new();
+ repo.expect_get_call_by_room_name()
+ .times(1)
+ .return_once(move |_| Box::pin(async move { Ok(Some(active_call)) }));
+ repo.expect_add_participant()
+ .times(1)
+ .returning(|_, _| Box::pin(async { Err(AddParticipantError::UserAlreadyActive) }));
+
+ let rtc_client = webhook_rtc_client("participant_joined", Some(ARCHIVED_EVENT_PARTICIPANT));
+ let connection_service = RecordingConnectionService::default();
+ let service = build_webhook_service_with_connection(
+ repo,
+ rtc_client,
+ connection_service.clone(),
+ RecordingEventBroker::default(),
+ );
+
+ service
+ .process_webhook_event("webhook-body", "webhook-token")
+ .await
+ .expect("state drift does not fail the webhook");
+
+ assert!(connection_service.messages().is_empty());
+}
+
fn assert_recording_ready_event(event_broker: &RecordingEventBroker) {
let events = event_broker.events();
let [published] = events.as_slice() else {