Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@
],
"license": "",
"peerDependencies": {
"@vapi-ai/web": "^2.3.7",
"@vapi-ai/web": "^2.5.0",
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
Expand Down
43 changes: 36 additions & 7 deletions src/components/VapiWidget.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState, useEffect, useRef } from 'react';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useVapiWidget } from '../hooks';

import { VapiWidgetProps, ColorScheme, StyleConfig } from './types';
Expand Down Expand Up @@ -61,6 +61,8 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
// Voice configuration
voiceShowTranscript,
showTranscript = false, // deprecated
voiceAutoReconnect = false,
reconnectStorageKey = 'vapi_widget_web_call',
// Consent configuration
consentRequired,
requireConsent = false, // deprecated
Expand All @@ -77,14 +79,39 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
onMessage,
onError,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
// Create storage key for expanded state
const expandedStorageKey = `vapi_widget_expanded`;

// Initialize expanded state from localStorage
const [isExpanded, setIsExpanded] = useState(() => {
try {
const stored = sessionStorage.getItem(expandedStorageKey);
return stored === 'true';
} catch {
return false;
}
});

const [hasConsent, setHasConsent] = useState(false);
const [chatInput, setChatInput] = useState('');
const [showEndScreen, setShowEndScreen] = useState(false);

const conversationEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);

// Custom setter that updates both state and localStorage
const updateExpandedState = useCallback(
(expanded: boolean) => {
setIsExpanded(expanded);
try {
sessionStorage.setItem(expandedStorageKey, expanded.toString());
} catch (error) {
console.warn('Failed to save expanded state to localStorage:', error);
}
},
[expandedStorageKey]
);

const effectiveBorderRadius = borderRadius ?? radius;
const effectiveBaseBgColor = baseBgColor ?? baseColor;
const effectiveAccentColor = accentColor ?? '#14B8A6';
Expand Down Expand Up @@ -122,6 +149,8 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
assistantOverrides,
apiUrl,
firstChatMessage: effectiveChatFirstMessage,
voiceAutoReconnect,
reconnectStorageKey,
onCallStart: effectiveOnVoiceStart,
onCallEnd: effectiveOnVoiceEnd,
onMessage,
Expand Down Expand Up @@ -232,11 +261,11 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
};

const handleConsentCancel = () => {
setIsExpanded(false);
updateExpandedState(false);
};

const handleToggleCall = async () => {
await vapi.voice.toggleCall();
await vapi.voice.toggleCall({ force: voiceAutoReconnect });
};

const handleSendMessage = async () => {
Expand All @@ -260,7 +289,7 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
setShowEndScreen(false);

if (vapi.voice.isCallActive) {
vapi.voice.endCall();
vapi.voice.endCall({ force: voiceAutoReconnect });
}

setChatInput('');
Expand Down Expand Up @@ -297,11 +326,11 @@ const VapiWidget: React.FC<VapiWidgetProps> = ({
setShowEndScreen(false);
setChatInput('');
}
setIsExpanded(false);
updateExpandedState(false);
};

const handleFloatingButtonClick = () => {
setIsExpanded(true);
updateExpandedState(true);
};

const renderConversationMessages = () => {
Expand Down
2 changes: 2 additions & 0 deletions src/components/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ export interface VapiWidgetProps {

// Voice Configuration
voiceShowTranscript?: boolean;
voiceAutoReconnect?: boolean;
reconnectStorageKey?: string;

// Consent Configuration
consentRequired?: boolean;
Expand Down
141 changes: 120 additions & 21 deletions src/hooks/useVapiCall.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import Vapi from '@vapi-ai/web';
import * as vapiCallStorage from '../utils/vapiCallStorage';

export interface VapiCallState {
isCallActive: boolean;
Expand All @@ -11,16 +12,20 @@ export interface VapiCallState {

export interface VapiCallHandlers {
startCall: () => Promise<void>;
endCall: () => Promise<void>;
toggleCall: () => Promise<void>;
endCall: (opts?: { force?: boolean }) => Promise<void>;
toggleCall: (opts?: { force?: boolean }) => Promise<void>;
toggleMute: () => void;
reconnect: () => Promise<void>;
clearStoredCall: () => void;
}

export interface UseVapiCallOptions {
publicKey: string;
callOptions: any;
apiUrl?: string;
enabled?: boolean;
voiceAutoReconnect?: boolean;
reconnectStorageKey?: string;
onCallStart?: () => void;
onCallEnd?: () => void;
onMessage?: (message: any) => void;
Expand All @@ -37,6 +42,8 @@ export const useVapiCall = ({
callOptions,
apiUrl,
enabled = true,
voiceAutoReconnect = false,
reconnectStorageKey = 'vapi_widget_web_call',
onCallStart,
onCallEnd,
onMessage,
Expand Down Expand Up @@ -90,6 +97,8 @@ export const useVapiCall = ({
setVolumeLevel(0);
setIsSpeaking(false);
setIsMuted(false);
// Clear stored call data on successful call end
vapiCallStorage.clearStoredCall(reconnectStorageKey);
callbacksRef.current.onCallEnd?.();
};

Expand Down Expand Up @@ -144,7 +153,7 @@ export const useVapiCall = ({
vapi.removeListener('message', handleMessage);
vapi.removeListener('error', handleError);
};
}, [vapi]);
}, [vapi, reconnectStorageKey]);

useEffect(() => {
return () => {
Expand All @@ -161,33 +170,68 @@ export const useVapiCall = ({
}

try {
console.log('Starting call with options:', callOptions);
console.log('Starting call with configuration:', callOptions);
console.log('Starting call with options:', {
voiceAutoReconnect,
});
setConnectionStatus('connecting');
await vapi.start(callOptions);
const call = await vapi.start(
// assistant
callOptions,
// assistant overrides,
undefined,
// squad
undefined,
// workflow
undefined,
// workflow overrides
undefined,
// options
{
roomDeleteOnUserLeaveEnabled: !voiceAutoReconnect,
}
);

// Store call data for reconnection if call was successful and auto-reconnect is enabled
if (call && voiceAutoReconnect) {
vapiCallStorage.storeCallData(reconnectStorageKey, call, callOptions);
}
} catch (error) {
console.error('Error starting call:', error);
setConnectionStatus('disconnected');
callbacksRef.current.onError?.(error as Error);
}
}, [vapi, callOptions, enabled]);
}, [vapi, callOptions, enabled, voiceAutoReconnect, reconnectStorageKey]);

const endCall = useCallback(async () => {
if (!vapi) {
console.log('Cannot end call: no vapi instance');
return;
}
const endCall = useCallback(
async ({ force = false }: { force?: boolean } = {}) => {
if (!vapi) {
console.log('Cannot end call: no vapi instance');
return;
}

console.log('Ending call');
vapi.stop();
}, [vapi]);
console.log('Ending call with force:', force);
if (force) {
// end vapi call and delete daily room
vapi.end();
} else {
// simply disconnect from daily room
vapi.stop();
}
},
[vapi]
);

const toggleCall = useCallback(async () => {
if (isCallActive) {
await endCall();
} else {
await startCall();
}
}, [isCallActive, startCall, endCall]);
const toggleCall = useCallback(
async ({ force = false }: { force?: boolean } = {}) => {
if (isCallActive) {
await endCall({ force });
} else {
await startCall();
}
},
[isCallActive, startCall, endCall]
);

const toggleMute = useCallback(() => {
if (!vapi || !isCallActive) {
Expand All @@ -200,6 +244,59 @@ export const useVapiCall = ({
setIsMuted(newMutedState);
}, [vapi, isCallActive, isMuted]);

const reconnect = useCallback(async () => {
if (!vapi || !enabled) {
console.error('Cannot reconnect: no vapi instance or not enabled');
return;
}

const storedData = vapiCallStorage.getStoredCallData(reconnectStorageKey);

if (!storedData) {
console.warn('No stored call data found for reconnection');
return;
}

// Check if callOptions match before reconnecting
if (
!vapiCallStorage.areCallOptionsEqual(storedData.callOptions, callOptions)
) {
console.warn(
'CallOptions have changed since last call, clearing stored data and skipping reconnection'
);
vapiCallStorage.clearStoredCall(reconnectStorageKey);
return;
}

setConnectionStatus('connecting');

try {
await vapi.reconnect({
webCallUrl: storedData.webCallUrl,
id: storedData.id,
artifactPlan: storedData.artifactPlan,
assistant: storedData.assistant,
});
console.log('Successfully reconnected to call');
} catch (error) {
setConnectionStatus('disconnected');
console.error('Reconnection failed:', error);
vapiCallStorage.clearStoredCall(reconnectStorageKey);
callbacksRef.current.onError?.(error as Error);
}
}, [vapi, enabled, reconnectStorageKey, callOptions]);

const clearStoredCall = useCallback(() => {
vapiCallStorage.clearStoredCall(reconnectStorageKey);
}, [reconnectStorageKey]);

useEffect(() => {
if (!vapi || !enabled || !voiceAutoReconnect) {
return;
}
reconnect();
}, [vapi, enabled, voiceAutoReconnect, reconnect, reconnectStorageKey]);

return {
// State
isCallActive,
Expand All @@ -212,5 +309,7 @@ export const useVapiCall = ({
endCall,
toggleCall,
toggleMute,
reconnect,
clearStoredCall,
};
};
Loading
Loading