1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
|
import { useState, useCallback, useRef, useEffect } from "react";
import { LISTEN_ENDPOINT } from "../lib/api";
import type {
ClientMessage,
ServerMessage,
TranscriptEntry,
} from "../types/messages";
export type ConnectionStatus =
| "disconnected"
| "connecting"
| "connected"
| "error";
export interface WebSocketState {
status: ConnectionStatus;
sessionId: string | null;
error: string | null;
transcripts: TranscriptEntry[];
}
interface UseWebSocketOptions {
onReady?: (sessionId: string) => void;
onTranscript?: (transcript: TranscriptEntry) => void;
onError?: (code: string, message: string) => void;
onStopped?: (reason: string) => void;
onTranscriptSaved?: (fileId: string, contractId: string) => void;
}
export function useWebSocket(options: UseWebSocketOptions = {}) {
const { onReady, onTranscript, onError, onStopped, onTranscriptSaved } = options;
const [state, setState] = useState<WebSocketState>({
status: "disconnected",
sessionId: null,
error: null,
transcripts: [],
});
const wsRef = useRef<WebSocket | null>(null);
const transcriptIdRef = useRef(0);
const stoppingRef = useRef(false);
const pendingDisconnectRef = useRef(false);
// Store callbacks in refs to avoid recreating handlers
const callbacksRef = useRef({ onReady, onTranscript, onError, onStopped, onTranscriptSaved });
useEffect(() => {
callbacksRef.current = { onReady, onTranscript, onError, onStopped, onTranscriptSaved };
}, [onReady, onTranscript, onError, onStopped, onTranscriptSaved]);
const connect = useCallback((): Promise<boolean> => {
return new Promise((resolve) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
resolve(true);
return;
}
// Close any existing connection
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
setState((s) => ({ ...s, status: "connecting", error: null }));
try {
const ws = new WebSocket(LISTEN_ENDPOINT);
wsRef.current = ws;
ws.onopen = () => {
setState((s) => ({ ...s, status: "connected", error: null }));
resolve(true);
};
ws.onmessage = (event) => {
try {
const message: ServerMessage = JSON.parse(event.data);
switch (message.type) {
case "ready":
setState((s) => ({ ...s, sessionId: message.sessionId }));
callbacksRef.current.onReady?.(message.sessionId);
break;
case "transcript": {
const entry: TranscriptEntry = {
id: `t-${++transcriptIdRef.current}`,
speaker: message.speaker,
start: message.start,
end: message.end,
text: message.text,
isFinal: message.isFinal,
};
setState((s) => {
// Find existing transcript with same speaker and overlapping timestamp
const existingIdx = s.transcripts.findIndex(
(t) =>
t.speaker === message.speaker &&
Math.abs(t.start - message.start) < 0.1
);
let newTranscripts: TranscriptEntry[];
if (existingIdx >= 0) {
// Replace existing transcript (final replaces non-final, or update in place)
newTranscripts = [...s.transcripts];
newTranscripts[existingIdx] = entry;
} else {
// No overlap - insert in time order
newTranscripts = [...s.transcripts, entry];
}
// Sort by start time to maintain chronological order
newTranscripts.sort((a, b) => a.start - b.start);
return { ...s, transcripts: newTranscripts };
});
callbacksRef.current.onTranscript?.(entry);
break;
}
case "error":
setState((s) => ({ ...s, error: message.message }));
callbacksRef.current.onError?.(message.code, message.message);
break;
case "stopped":
stoppingRef.current = false;
setState((s) => ({ ...s, status: "disconnected" }));
callbacksRef.current.onStopped?.(message.reason);
// Execute pending disconnect if requested during stopping
if (pendingDisconnectRef.current) {
pendingDisconnectRef.current = false;
if (wsRef.current) {
wsRef.current.close(1000, "User disconnected");
wsRef.current = null;
}
}
break;
case "transcriptSaved":
callbacksRef.current.onTranscriptSaved?.(message.fileId, message.contractId);
break;
}
} catch {
console.error("Failed to parse WebSocket message:", event.data);
}
};
ws.onerror = () => {
setState((s) => ({
...s,
status: "error",
error: "Failed to connect to server",
}));
resolve(false);
};
ws.onclose = (event) => {
// Check for specific close codes
let errorMessage: string | null = null;
if (event.code === 1006) {
errorMessage = "Connection failed - server may be unavailable";
} else if (event.code !== 1000 && event.code !== 1001) {
errorMessage = `Connection closed unexpectedly (code: ${event.code})`;
}
setState((s) => ({
...s,
status: "disconnected",
sessionId: null,
error: errorMessage || s.error,
}));
wsRef.current = null;
};
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to create WebSocket connection";
setState((s) => ({
...s,
status: "error",
error: message,
}));
resolve(false);
}
});
}, []);
const disconnect = useCallback(() => {
if (stoppingRef.current) {
// Defer disconnect until "stopped" message is received
pendingDisconnectRef.current = true;
return;
}
if (wsRef.current) {
wsRef.current.close(1000, "User disconnected");
wsRef.current = null;
}
setState((s) => ({ ...s, status: "disconnected", sessionId: null }));
}, []);
const sendMessage = useCallback((message: ClientMessage) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(message));
}
}, []);
const sendAudio = useCallback((samples: Float32Array) => {
if (wsRef.current?.readyState === WebSocket.OPEN) {
// Convert Float32Array to bytes (little-endian)
const bytes = new Uint8Array(samples.length * 4);
const view = new DataView(bytes.buffer);
for (let i = 0; i < samples.length; i++) {
view.setFloat32(i * 4, samples[i], true);
}
wsRef.current.send(bytes);
}
}, []);
const startSession = useCallback(
(sampleRate: number, channels: number = 1, contractId?: string | null, authToken?: string | null) => {
sendMessage({
type: "start",
sampleRate,
channels,
encoding: "pcm32f",
...(contractId && authToken ? { contractId, authToken } : {}),
});
},
[sendMessage]
);
const stopSession = useCallback(
(reason?: string) => {
stoppingRef.current = true;
sendMessage({
type: "stop",
reason,
});
},
[sendMessage]
);
const clearTranscripts = useCallback(() => {
stoppingRef.current = false;
pendingDisconnectRef.current = false;
setState((s) => ({ ...s, transcripts: [], error: null }));
}, []);
// Cleanup on unmount
useEffect(() => {
return () => {
if (wsRef.current) {
wsRef.current.close();
}
};
}, []);
return {
...state,
connect,
disconnect,
sendAudio,
startSession,
stopSession,
clearTranscripts,
isConnected: state.status === "connected",
};
}
|