@voxdiscover/voiceserver-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Voxdiscover
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,418 @@
1
+ # @voxdiscover/voiceserver-react
2
+
3
+ React adapter for Voice_server voice agents. Provides hooks, context provider, and automatic state management for building real-time voice AI applications.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @voxdiscover/voiceserver-react @voxdiscover/voiceserver @daily-co/daily-js
9
+ ```
10
+
11
+ Or with npm/yarn:
12
+
13
+ ```bash
14
+ npm install @voxdiscover/voiceserver-react @voxdiscover/voiceserver @daily-co/daily-js
15
+ yarn add @voxdiscover/voiceserver-react @voxdiscover/voiceserver @daily-co/daily-js
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ```tsx
21
+ import { VoiceAgentProvider, useVoiceAgent } from '@voxdiscover/voiceserver-react';
22
+
23
+ function App() {
24
+ return (
25
+ <VoiceAgentProvider token="your-session-token">
26
+ <VoiceChat />
27
+ </VoiceAgentProvider>
28
+ );
29
+ }
30
+
31
+ function VoiceChat() {
32
+ const { connect, disconnect, isConnected, transcripts } = useVoiceAgent();
33
+
34
+ return (
35
+ <div>
36
+ <button onClick={connect} disabled={isConnected}>
37
+ Start Call
38
+ </button>
39
+ <button onClick={disconnect} disabled={!isConnected}>
40
+ End Call
41
+ </button>
42
+ <div>
43
+ {transcripts.map((t, i) => (
44
+ <p key={i}>{t.speaker}: {t.text}</p>
45
+ ))}
46
+ </div>
47
+ </div>
48
+ );
49
+ }
50
+ ```
51
+
52
+ ## Features
53
+
54
+ - **React Hooks**: Single comprehensive `useVoiceAgent` hook with all functionality
55
+ - **Automatic State Management**: Connection state, transcripts, and errors synced with React
56
+ - **TypeScript Support**: Full type definitions included
57
+ - **SSR-Safe**: Works with Next.js, Remix, and other SSR frameworks
58
+ - **Transcript Persistence**: Automatically saves transcripts to sessionStorage
59
+ - **Retry Logic**: Built-in exponential backoff with countdown UI feedback
60
+ - **Concurrent-Safe**: Uses `useSyncExternalStore` for React 18+ concurrent features
61
+ - **Memory Leak Protection**: Automatic cleanup on unmount
62
+
63
+ ## Usage
64
+
65
+ ### Provider Setup
66
+
67
+ Wrap your app (or part of it) with `VoiceAgentProvider`:
68
+
69
+ ```tsx
70
+ import { VoiceAgentProvider } from '@voxdiscover/voiceserver-react';
71
+
72
+ function App() {
73
+ return (
74
+ <VoiceAgentProvider
75
+ token="your-session-token"
76
+ baseUrl="https://voiceserver.voxdiscover.com" // Optional, defaults to https://voiceserver.voxdiscover.com
77
+ reconnection={{
78
+ enabled: true,
79
+ maxAttempts: 5,
80
+ initialDelay: 1000,
81
+ }}
82
+ onConnect={() => console.log('Connected!')}
83
+ onDisconnect={() => console.log('Disconnected')}
84
+ onError={(error) => console.error('Error:', error)}
85
+ >
86
+ <YourApp />
87
+ </VoiceAgentProvider>
88
+ );
89
+ }
90
+ ```
91
+
92
+ ### useVoiceAgent Hook
93
+
94
+ Access all voice agent functionality from the hook:
95
+
96
+ ```tsx
97
+ import { useVoiceAgent } from '@voxdiscover/voiceserver-react';
98
+
99
+ function VoiceChat() {
100
+ const {
101
+ // Raw agent instance for advanced use cases
102
+ agent,
103
+
104
+ // Connection state
105
+ callState, // 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed'
106
+ isConnected,
107
+ isConnecting,
108
+ isReconnecting,
109
+
110
+ // Transcripts and errors
111
+ transcripts, // Array of TranscriptData
112
+ error, // Current error, auto-cleared on success
113
+
114
+ // Retry state
115
+ retryState, // { isRetrying, attempt, maxAttempts, nextRetryIn }
116
+
117
+ // Actions
118
+ connect,
119
+ disconnect,
120
+ mute,
121
+ unmute,
122
+ retryConnect,
123
+ } = useVoiceAgent();
124
+
125
+ return (
126
+ <div>
127
+ {/* Your UI */}
128
+ </div>
129
+ );
130
+ }
131
+ ```
132
+
133
+ ### Connection Management
134
+
135
+ ```tsx
136
+ function ConnectionControls() {
137
+ const { connect, disconnect, isConnected, isConnecting } = useVoiceAgent();
138
+
139
+ return (
140
+ <div>
141
+ <button
142
+ onClick={connect}
143
+ disabled={isConnected || isConnecting}
144
+ >
145
+ {isConnecting ? 'Connecting...' : 'Start Call'}
146
+ </button>
147
+ <button
148
+ onClick={disconnect}
149
+ disabled={!isConnected}
150
+ >
151
+ End Call
152
+ </button>
153
+ </div>
154
+ );
155
+ }
156
+ ```
157
+
158
+ ### Audio Controls
159
+
160
+ ```tsx
161
+ function AudioControls() {
162
+ const { mute, unmute, isConnected } = useVoiceAgent();
163
+ const [isMuted, setIsMuted] = useState(false);
164
+
165
+ const toggleMute = () => {
166
+ if (isMuted) {
167
+ unmute();
168
+ setIsMuted(false);
169
+ } else {
170
+ mute();
171
+ setIsMuted(true);
172
+ }
173
+ };
174
+
175
+ return (
176
+ <button onClick={toggleMute} disabled={!isConnected}>
177
+ {isMuted ? 'Unmute' : 'Mute'}
178
+ </button>
179
+ );
180
+ }
181
+ ```
182
+
183
+ ### Displaying Transcripts
184
+
185
+ ```tsx
186
+ function TranscriptDisplay() {
187
+ const { transcripts } = useVoiceAgent();
188
+ const transcriptEndRef = useRef<HTMLDivElement>(null);
189
+
190
+ // Auto-scroll to bottom
191
+ useEffect(() => {
192
+ transcriptEndRef.current?.scrollIntoView({ behavior: 'smooth' });
193
+ }, [transcripts]);
194
+
195
+ return (
196
+ <div className="transcript-list">
197
+ {transcripts.map((transcript, index) => (
198
+ <div key={index} className={transcript.speaker}>
199
+ <strong>{transcript.speaker}:</strong> {transcript.text}
200
+ </div>
201
+ ))}
202
+ <div ref={transcriptEndRef} />
203
+ </div>
204
+ );
205
+ }
206
+ ```
207
+
208
+ ### Error Handling
209
+
210
+ ```tsx
211
+ function ErrorDisplay() {
212
+ const { error, retryState, retryConnect } = useVoiceAgent();
213
+
214
+ if (!error && !retryState.isRetrying) return null;
215
+
216
+ return (
217
+ <div className="error-banner">
218
+ {error && (
219
+ <div className="error-message">
220
+ <strong>Error:</strong> {error.message}
221
+ </div>
222
+ )}
223
+ {retryState.isRetrying && (
224
+ <div className="retry-info">
225
+ Retrying... attempt {retryState.attempt}/{retryState.maxAttempts}
226
+ <br />
227
+ Next retry in {Math.ceil(retryState.nextRetryIn / 1000)}s
228
+ <button onClick={retryConnect}>Retry Now</button>
229
+ </div>
230
+ )}
231
+ </div>
232
+ );
233
+ }
234
+ ```
235
+
236
+ ### Advanced: Direct Agent Access
237
+
238
+ For advanced use cases, access the raw `VoiceAgent` instance:
239
+
240
+ ```tsx
241
+ function AdvancedControls() {
242
+ const { agent } = useVoiceAgent();
243
+
244
+ const handleCustomEvent = () => {
245
+ agent.on('custom:event', (data) => {
246
+ console.log('Custom event:', data);
247
+ });
248
+ };
249
+
250
+ return <button onClick={handleCustomEvent}>Setup Custom Listener</button>;
251
+ }
252
+ ```
253
+
254
+ ## API Reference
255
+
256
+ ### VoiceAgentProvider Props
257
+
258
+ ```tsx
259
+ interface VoiceAgentProviderProps {
260
+ children: ReactNode;
261
+ token: string; // Session token from backend
262
+ baseUrl?: string; // Backend URL, defaults to https://voiceserver.voxdiscover.com
263
+ reconnection?: {
264
+ enabled?: boolean;
265
+ maxAttempts?: number;
266
+ initialDelay?: number;
267
+ };
268
+ onConnect?: () => void;
269
+ onDisconnect?: () => void;
270
+ onError?: (error: Error) => void;
271
+ }
272
+ ```
273
+
274
+ ### useVoiceAgent Return Type
275
+
276
+ ```tsx
277
+ interface UseVoiceAgentReturn {
278
+ agent: VoiceAgent; // Raw agent instance
279
+ callState: ConnectionState; // Current connection state
280
+ transcripts: TranscriptData[]; // All transcripts
281
+ error: Error | null; // Current error (auto-cleared)
282
+ isConnected: boolean; // Derived from callState
283
+ isConnecting: boolean; // Derived from callState
284
+ isReconnecting: boolean; // Derived from callState
285
+ retryState: RetryState; // Retry attempt info
286
+ connect: () => Promise<void>; // Connect to session
287
+ disconnect: () => Promise<void>; // Disconnect from session
288
+ mute: () => void; // Mute microphone
289
+ unmute: () => void; // Unmute microphone
290
+ retryConnect: () => Promise<void>; // Manual retry
291
+ }
292
+ ```
293
+
294
+ ### Types
295
+
296
+ ```tsx
297
+ // Connection states
298
+ type ConnectionState =
299
+ | 'disconnected'
300
+ | 'connecting'
301
+ | 'connected'
302
+ | 'reconnecting'
303
+ | 'failed';
304
+
305
+ // Transcript data
306
+ interface TranscriptData {
307
+ speaker: 'user' | 'agent';
308
+ text: string;
309
+ timestamp: number;
310
+ isFinal: boolean;
311
+ }
312
+
313
+ // Retry state
314
+ interface RetryState {
315
+ isRetrying: boolean;
316
+ attempt: number;
317
+ maxAttempts: number;
318
+ nextRetryIn: number; // milliseconds
319
+ }
320
+ ```
321
+
322
+ ## Examples
323
+
324
+ See the [examples/basic-app](./examples/basic-app) directory for a complete working example demonstrating:
325
+
326
+ - Connection lifecycle management
327
+ - Audio controls (mute/unmute)
328
+ - Real-time transcript display with auto-scroll
329
+ - Error handling with visual feedback
330
+ - Retry state display with countdown
331
+ - Connection status indicators
332
+
333
+ To run the example:
334
+
335
+ ```bash
336
+ cd examples/basic-app
337
+ cp .env.example .env
338
+ # Edit .env and add your session token
339
+ pnpm dev
340
+ ```
341
+
342
+ Visit http://localhost:3001 to see the example app.
343
+
344
+ ## Troubleshooting
345
+
346
+ ### "useVoiceAgent must be used within VoiceAgentProvider"
347
+
348
+ Make sure your component using `useVoiceAgent` is wrapped with `<VoiceAgentProvider>`:
349
+
350
+ ```tsx
351
+ // ❌ Wrong
352
+ function App() {
353
+ const { connect } = useVoiceAgent(); // Error!
354
+ return <div>...</div>;
355
+ }
356
+
357
+ // ✅ Correct
358
+ function App() {
359
+ return (
360
+ <VoiceAgentProvider token={token}>
361
+ <VoiceChat />
362
+ </VoiceAgentProvider>
363
+ );
364
+ }
365
+
366
+ function VoiceChat() {
367
+ const { connect } = useVoiceAgent(); // Works!
368
+ return <div>...</div>;
369
+ }
370
+ ```
371
+
372
+ ### SSR Hydration Errors
373
+
374
+ The React adapter is SSR-safe by default. Storage operations use `typeof window` guards to prevent server-side errors.
375
+
376
+ If you still experience issues with Next.js, you can force client-side rendering:
377
+
378
+ ```tsx
379
+ import dynamic from 'next/dynamic';
380
+
381
+ const VoiceChat = dynamic(() => import('./VoiceChat'), { ssr: false });
382
+ ```
383
+
384
+ ### Storage Quota Exceeded
385
+
386
+ Transcript persistence silently handles storage quota errors. If you hit quota limits:
387
+
388
+ 1. Transcripts will stop persisting but the app continues working
389
+ 2. Check browser console for "Failed to persist transcripts" warnings
390
+ 3. Clear sessionStorage to free up space: `sessionStorage.clear()`
391
+
392
+ ### Connection Errors
393
+
394
+ If you experience connection errors:
395
+
396
+ 1. Verify your session token is valid (not expired)
397
+ 2. Check that your backend URL is correct
398
+ 3. Ensure your backend is running and accessible
399
+ 4. Check browser console for detailed error messages
400
+
401
+ ## TypeScript
402
+
403
+ This package is written in TypeScript and includes full type definitions. All types are exported:
404
+
405
+ ```tsx
406
+ import type {
407
+ VoiceAgentProviderProps,
408
+ UseVoiceAgentReturn,
409
+ RetryState,
410
+ ConnectionState,
411
+ TranscriptData,
412
+ VoiceAgentConfig,
413
+ } from '@voxdiscover/voiceserver-react';
414
+ ```
415
+
416
+ ## License
417
+
418
+ MIT