fix(voice): align outbound WhatsApp call lifecycle with real pickup
A pile of related fixes around the dashboard's WhatsApp call flow:
- ConversationHeader / Contacts/VoiceCallButton: drop the immediate
setCallActive at initiate time. The call sits in incomingCalls
(callDirection: outbound) until the backend signals real pickup, so
the duration timer never starts pre-pickup. Phone button is disabled
whenever there is an active or incoming call.
- FloatingCallWidget:
* Loop a ringtone (bell.mp3) for inbound ringing only.
* Hide the green Join button for outbound — the agent has nothing to
"join", and clicking it routed through acceptIncomingCall →
prepareInboundAnswer → cleanup() and tore down the live outbound
session before the API 409 ("already accepted by another agent").
* Auto-join watcher skips whatsapp outbound (Twilio's joinConference
flow only).
- useCallSession:
* joinCall short-circuits for outbound calls — defense-in-depth so
no future surface can re-trigger the destroyed-session bug.
* endCall + outbound rejectIncomingCall pass call.callId to
endActiveCall, so terminate fires even if module state was wiped.
- useWhatsappCallSession:
* New recorderArmed flag, reset by cleanup. ontrack only calls
setupRecorder when armed.
* Inbound's acceptIncomingCall arms the recorder before the API
round-trip (agent click = pickup).
* armOutboundRecorder exported for the cable handler when ACCEPTED
arrives.
* endActiveCall accepts a callIdOverride to fall back when the
module's activeCallId was nulled by an earlier cleanup.
- actionCable:
* Split the cable contract: outbound_connected only applies the SDP
answer (tunnel-up signal); outbound_accepted (new) is the real
pickup signal — flips active and arms the recorder.
This commit is contained in:
@@ -93,6 +93,8 @@ const startWhatsappCall = async inboxId => {
|
||||
}
|
||||
|
||||
const callsStore = useCallsStore();
|
||||
// Stay non-active until the connect cable event arrives — flipping to active
|
||||
// here would start the duration timer before the contact picks up.
|
||||
callsStore.addCall({
|
||||
callSid: response.call_id,
|
||||
callId: response.id,
|
||||
@@ -101,7 +103,6 @@ const startWhatsappCall = async inboxId => {
|
||||
callDirection: 'outbound',
|
||||
provider: 'whatsapp',
|
||||
});
|
||||
callsStore.setCallActive(response.call_id);
|
||||
|
||||
useAlert(t('CONTACT_PANEL.CALL_INITIATED'));
|
||||
navigateToConversation(conversationId);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useStore } from 'vuex';
|
||||
import { useCallSession } from 'dashboard/composables/useCallSession';
|
||||
@@ -7,6 +7,8 @@ import { setWhatsappCallMuted } from 'dashboard/composables/useWhatsappCallSessi
|
||||
import WindowVisibilityHelper from 'dashboard/helper/AudioAlerts/WindowVisibilityHelper';
|
||||
import Avatar from 'dashboard/components-next/avatar/Avatar.vue';
|
||||
|
||||
const RINGTONE_URL = '/audio/dashboard/bell.mp3';
|
||||
|
||||
const router = useRouter();
|
||||
const store = useStore();
|
||||
|
||||
@@ -97,12 +99,15 @@ const handleJoinCall = async call => {
|
||||
}
|
||||
};
|
||||
|
||||
// Auto-join outbound calls when window is visible
|
||||
// Auto-join outbound calls when window is visible. WhatsApp outbound has no
|
||||
// separate join step (the offer was sent at initiate time and the answer is
|
||||
// applied directly by the cable handler), so this only covers Twilio.
|
||||
watch(
|
||||
() => incomingCalls.value[0],
|
||||
call => {
|
||||
if (
|
||||
call?.callDirection === 'outbound' &&
|
||||
call?.provider !== 'whatsapp' &&
|
||||
!hasActiveCall.value &&
|
||||
WindowVisibilityHelper.isWindowVisible()
|
||||
) {
|
||||
@@ -111,6 +116,37 @@ watch(
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
// Loop the ringtone while an inbound call is unanswered. Stop the moment any
|
||||
// call is active (we joined), every inbound call cleared, or the widget tears
|
||||
// down. Browser autoplay may reject the first play() if the tab has no prior
|
||||
// user gesture; that's fine — the visual widget still surfaces the call.
|
||||
const ringtone = new Audio(RINGTONE_URL);
|
||||
ringtone.loop = true;
|
||||
ringtone.volume = 1;
|
||||
|
||||
const stopRingtone = () => {
|
||||
ringtone.pause();
|
||||
ringtone.currentTime = 0;
|
||||
};
|
||||
|
||||
const ringingInbound = computed(() =>
|
||||
incomingCalls.value.some(call => call.callDirection !== 'outbound')
|
||||
);
|
||||
|
||||
watch(
|
||||
() => ringingInbound.value && !hasActiveCall.value,
|
||||
shouldRing => {
|
||||
if (shouldRing) {
|
||||
ringtone.play().catch(() => {});
|
||||
} else {
|
||||
stopRingtone();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
onBeforeUnmount(stopRingtone);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -223,7 +259,9 @@ watch(
|
||||
<i class="text-lg text-white i-ph-phone-x-bold" />
|
||||
</button>
|
||||
<button
|
||||
v-if="!hasActiveCall"
|
||||
v-if="
|
||||
!hasActiveCall && incomingCalls[0]?.callDirection !== 'outbound'
|
||||
"
|
||||
class="flex justify-center items-center w-10 h-10 bg-n-teal-9 hover:bg-n-teal-10 rounded-full transition-colors"
|
||||
@click="handleJoinCall(incomingCalls[0])"
|
||||
>
|
||||
|
||||
@@ -107,6 +107,13 @@ const isWhatsappVoiceInbox = computed(
|
||||
() => getVoiceCallProvider(inbox.value) === VOICE_CALL_PROVIDERS.WHATSAPP
|
||||
);
|
||||
|
||||
const isWhatsappCallButtonDisabled = computed(
|
||||
() =>
|
||||
whatsappCallSession.isInitiating.value ||
|
||||
callsStore.hasActiveCall ||
|
||||
callsStore.hasIncomingCall
|
||||
);
|
||||
|
||||
const startWhatsappCall = async () => {
|
||||
if (whatsappCallSession.isInitiating.value) return;
|
||||
try {
|
||||
@@ -125,6 +132,8 @@ const startWhatsappCall = async () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Stay non-active until Meta delivers the connect webhook (sdp_answer);
|
||||
// flipping to active here would start the duration timer before pickup.
|
||||
callsStore.addCall({
|
||||
callSid: response.call_id,
|
||||
callId: response.id,
|
||||
@@ -133,7 +142,6 @@ const startWhatsappCall = async () => {
|
||||
callDirection: 'outbound',
|
||||
provider: 'whatsapp',
|
||||
});
|
||||
callsStore.setCallActive(response.call_id);
|
||||
} catch (error) {
|
||||
useAlert(error?.message || t('CONVERSATION.HEADER.WHATSAPP_CALL_FAILED'));
|
||||
}
|
||||
@@ -207,7 +215,7 @@ const startWhatsappCall = async () => {
|
||||
color="slate"
|
||||
icon="i-lucide-phone"
|
||||
:is-loading="whatsappCallSession.isInitiating.value"
|
||||
:disabled="whatsappCallSession.isInitiating.value"
|
||||
:disabled="isWhatsappCallButtonDisabled"
|
||||
class="rounded-md hover:bg-n-alpha-2"
|
||||
@click="startWhatsappCall"
|
||||
/>
|
||||
|
||||
@@ -106,8 +106,11 @@ export function useCallSession() {
|
||||
const findCall = callSid => callsStore.calls.find(c => c.callSid === callSid);
|
||||
|
||||
const endCall = async ({ conversationId, inboxId, callSid }) => {
|
||||
if (isWhatsappCall(findCall(callSid))) {
|
||||
await whatsappSession.endActiveCall();
|
||||
const call = findCall(callSid);
|
||||
if (isWhatsappCall(call)) {
|
||||
// Pass call.callId so a wiped module state (e.g. a prior accept attempt
|
||||
// tore down the WebRTC session) doesn't stop us hitting /terminate.
|
||||
await whatsappSession.endActiveCall(call.callId);
|
||||
durationTimer.stop();
|
||||
callsStore.clearActiveCall();
|
||||
return;
|
||||
@@ -122,9 +125,15 @@ export function useCallSession() {
|
||||
const joinCall = async ({ conversationId, inboxId, callSid }) => {
|
||||
if (isJoining.value) return null;
|
||||
|
||||
const call = findCall(callSid);
|
||||
// Outbound calls were initiated by this agent — there is no inbound offer
|
||||
// to accept and the WebRTC session is already mid-handshake. Routing
|
||||
// through acceptIncomingCall would call prepareInboundAnswer → cleanup()
|
||||
// and destroy the live outbound session, then 409 from the backend.
|
||||
if (call?.callDirection === 'outbound') return null;
|
||||
|
||||
isJoining.value = true;
|
||||
try {
|
||||
const call = findCall(callSid);
|
||||
if (isWhatsappCall(call)) {
|
||||
await whatsappSession.acceptIncomingCall({
|
||||
callId: call.callId,
|
||||
@@ -174,7 +183,14 @@ export function useCallSession() {
|
||||
const rejectIncomingCall = callSid => {
|
||||
const call = findCall(callSid);
|
||||
if (isWhatsappCall(call) && call?.callId) {
|
||||
whatsappSession.rejectIncomingCall(call.callId);
|
||||
// Outbound calls that are still ringing must be terminated, not rejected
|
||||
// (reject is the inbound-side verb on Meta's API). Pass call.callId so
|
||||
// a wiped module state still hits /terminate.
|
||||
if (call.callDirection === 'outbound') {
|
||||
whatsappSession.endActiveCall(call.callId);
|
||||
} else {
|
||||
whatsappSession.rejectIncomingCall(call.callId);
|
||||
}
|
||||
} else {
|
||||
TwilioVoiceClient.endClientCall();
|
||||
}
|
||||
|
||||
@@ -13,6 +13,12 @@ let recorderChunks = [];
|
||||
let audioContext = null;
|
||||
let activeCallId = null;
|
||||
let intentionallyClosing = false;
|
||||
// Inbound calls record from the moment the agent clicks accept (their click =
|
||||
// pickup). Outbound calls must wait — Meta's `connect` webhook (which lands
|
||||
// during ringing) negotiates remote tracks ~20s before the contact actually
|
||||
// answers, and we don't want pre-pickup audio in the recording. This flag is
|
||||
// flipped to true by armOutboundRecorder() when the ACCEPTED status arrives.
|
||||
let recorderArmed = false;
|
||||
|
||||
const ensureRemoteAudioElement = () => {
|
||||
if (remoteAudioEl) return remoteAudioEl;
|
||||
@@ -38,6 +44,7 @@ const playRemoteStream = stream => {
|
||||
// that races cleanup still has data to upload.
|
||||
const RECORDING_TIMESLICE_MS = 1000;
|
||||
const ICE_GATHER_TIMEOUT_MS = 10000;
|
||||
|
||||
const RECORDER_MIME_CANDIDATES = [
|
||||
'audio/webm;codecs=opus',
|
||||
'audio/webm',
|
||||
@@ -64,32 +71,6 @@ const waitForIceGatheringComplete = peer =>
|
||||
});
|
||||
});
|
||||
|
||||
const cleanup = () => {
|
||||
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||
try {
|
||||
mediaRecorder.stop();
|
||||
} catch (_) {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
if (audioContext && audioContext.state !== 'closed') {
|
||||
audioContext.close().catch(() => {});
|
||||
}
|
||||
if (localStream) localStream.getTracks().forEach(t => t.stop());
|
||||
if (remoteStream) remoteStream.getTracks().forEach(t => t.stop());
|
||||
if (pc) pc.close();
|
||||
if (remoteAudioEl) remoteAudioEl.srcObject = null;
|
||||
|
||||
pc = null;
|
||||
localStream = null;
|
||||
remoteStream = null;
|
||||
mediaRecorder = null;
|
||||
recorderChunks = [];
|
||||
audioContext = null;
|
||||
activeCallId = null;
|
||||
intentionallyClosing = false;
|
||||
};
|
||||
|
||||
const setupRecorder = () => {
|
||||
if (!localStream || !remoteStream || mediaRecorder) return;
|
||||
// createMediaStreamSource on a stream with no audio tracks wires up to
|
||||
@@ -118,6 +99,33 @@ const setupRecorder = () => {
|
||||
mediaRecorder.start(RECORDING_TIMESLICE_MS);
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
|
||||
try {
|
||||
mediaRecorder.stop();
|
||||
} catch (_) {
|
||||
/* noop */
|
||||
}
|
||||
}
|
||||
if (audioContext && audioContext.state !== 'closed') {
|
||||
audioContext.close().catch(() => {});
|
||||
}
|
||||
if (localStream) localStream.getTracks().forEach(t => t.stop());
|
||||
if (remoteStream) remoteStream.getTracks().forEach(t => t.stop());
|
||||
if (pc) pc.close();
|
||||
if (remoteAudioEl) remoteAudioEl.srcObject = null;
|
||||
|
||||
pc = null;
|
||||
localStream = null;
|
||||
remoteStream = null;
|
||||
mediaRecorder = null;
|
||||
recorderChunks = [];
|
||||
audioContext = null;
|
||||
activeCallId = null;
|
||||
intentionallyClosing = false;
|
||||
recorderArmed = false;
|
||||
};
|
||||
|
||||
const buildPeerConnection = iceServers => {
|
||||
const config = iceServers && iceServers.length ? { iceServers } : {};
|
||||
pc = new RTCPeerConnection(config);
|
||||
@@ -134,7 +142,10 @@ const buildPeerConnection = iceServers => {
|
||||
remoteStream.addTrack(track);
|
||||
});
|
||||
playRemoteStream(remoteStream);
|
||||
setupRecorder();
|
||||
// Only arm the recorder when the call is actually accepted. For outbound
|
||||
// this is the ACCEPTED status webhook; for inbound this is the agent's
|
||||
// own click (acceptIncomingCall flips recorderArmed before returning).
|
||||
if (recorderArmed) setupRecorder();
|
||||
};
|
||||
return pc;
|
||||
};
|
||||
@@ -255,6 +266,11 @@ export function useWhatsappCallSession() {
|
||||
|
||||
const sdpAnswer = await prepareInboundAnswer(offer, ice);
|
||||
activeCallId = callId;
|
||||
// Inbound: agent's click is the pickup. Arm the recorder before the API
|
||||
// round-trip so when ontrack fires (triggered by setRemoteDescription
|
||||
// back in prepareInboundAnswer) the recorder is already authorized.
|
||||
recorderArmed = true;
|
||||
setupRecorder();
|
||||
await WhatsappCallsAPI.accept(callId, sdpAnswer);
|
||||
};
|
||||
|
||||
@@ -287,16 +303,20 @@ export function useWhatsappCallSession() {
|
||||
}
|
||||
};
|
||||
|
||||
const endActiveCall = async () => {
|
||||
if (!activeCallId) {
|
||||
// callIdOverride is the call.id from the dashboard's calls store. Module
|
||||
// `activeCallId` may be null after a prior accept attempt's cleanup() — but
|
||||
// the call still exists on Meta and must still be terminated. Falling back
|
||||
// to the override means hangup is robust to a wiped local session.
|
||||
const endActiveCall = async (callIdOverride = null) => {
|
||||
const callId = activeCallId || callIdOverride;
|
||||
if (!callId) {
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
intentionallyClosing = true;
|
||||
const callIdSnapshot = activeCallId;
|
||||
try {
|
||||
await stopRecorderAndUpload(callIdSnapshot);
|
||||
await WhatsappCallsAPI.terminate(callIdSnapshot).catch(() => {});
|
||||
await stopRecorderAndUpload(callId);
|
||||
await WhatsappCallsAPI.terminate(callId).catch(() => {});
|
||||
} finally {
|
||||
cleanup();
|
||||
}
|
||||
@@ -322,6 +342,15 @@ export const applyOutboundAnswer = async (callId, sdpAnswer) => {
|
||||
await pc.setRemoteDescription({ type: 'answer', sdp: sdpAnswer });
|
||||
};
|
||||
|
||||
// Called by the cable handler when Meta delivers status=ACCEPTED for the
|
||||
// outbound call (real pickup). Flips the recorder gate and starts the
|
||||
// MediaRecorder. Idempotent — safe if ontrack hasn't fired yet (setupRecorder
|
||||
// bails until the remote stream has audio tracks; ontrack will retry).
|
||||
export const armOutboundRecorder = () => {
|
||||
recorderArmed = true;
|
||||
setupRecorder();
|
||||
};
|
||||
|
||||
export const cleanupWhatsappSession = () => cleanup();
|
||||
|
||||
export const handleWhatsappRemoteEnd = async callId => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useImpersonation } from 'dashboard/composables/useImpersonation';
|
||||
import { useCallsStore } from 'dashboard/stores/calls';
|
||||
import {
|
||||
applyOutboundAnswer,
|
||||
armOutboundRecorder,
|
||||
handleWhatsappRemoteEnd,
|
||||
} from 'dashboard/composables/useWhatsappCallSession';
|
||||
|
||||
@@ -42,6 +43,7 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
'copilot.message.created': this.onCopilotMessageCreated,
|
||||
'voice_call.incoming': this.onVoiceCallIncoming,
|
||||
'voice_call.outbound_connected': this.onVoiceCallOutboundConnected,
|
||||
'voice_call.outbound_accepted': this.onVoiceCallOutboundAccepted,
|
||||
'voice_call.ended': this.onVoiceCallEnded,
|
||||
};
|
||||
}
|
||||
@@ -230,10 +232,28 @@ class ActionCableConnector extends BaseActionCableConnector {
|
||||
});
|
||||
};
|
||||
|
||||
// `connect` is the WebRTC tunnel-ready signal (fires ~20s before pickup
|
||||
// for outbound). Apply the SDP answer so the handshake completes during
|
||||
// ringing, but stay non-active until `outbound_accepted` arrives.
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
onVoiceCallOutboundConnected = data => {
|
||||
onVoiceCallOutboundConnected = async data => {
|
||||
if (data?.provider !== 'whatsapp' || !data.sdp_answer) return;
|
||||
applyOutboundAnswer(data.id, data.sdp_answer).catch(() => {});
|
||||
try {
|
||||
await applyOutboundAnswer(data.id, data.sdp_answer);
|
||||
} catch (_) {
|
||||
/* noop */
|
||||
}
|
||||
};
|
||||
|
||||
// Real pickup signal — Meta sends status=ACCEPTED on the call when the
|
||||
// contact answers. Flip active (timer starts) and arm the recorder.
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
onVoiceCallOutboundAccepted = data => {
|
||||
if (data?.provider !== 'whatsapp') return;
|
||||
const store = useCallsStore();
|
||||
if (!store.calls.some(c => c.callSid === data.call_id)) return;
|
||||
store.setCallActive(data.call_id);
|
||||
armOutboundRecorder();
|
||||
};
|
||||
|
||||
// eslint-disable-next-line class-methods-use-this
|
||||
|
||||
Reference in New Issue
Block a user