-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
1717 lines (1480 loc) · 74 KB
/
server.js
File metadata and controls
1717 lines (1480 loc) · 74 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const { createServer } = require('http');
const { parse } = require('url');
const next = require('next');
const { Hocuspocus } = require('@hocuspocus/server'); // ← ここ重要(Server ではなく Hocuspocus)
const { WebSocketServer } = require('ws');
const WebSocket = require('ws');
const { HttpsProxyAgent } = require('https-proxy-agent');
if (!process.env.OPENAI_API_KEY) {
console.error('❌ ERROR: OPENAI_API_KEY environment variable is required');
process.exit(1);
}
const dev = process.env.NODE_ENV !== 'production';
const hostname = '0.0.0.0';
// Port
let port = 8888;
const portArgIndex = process.argv.findIndex(arg => arg === '-p');
if (portArgIndex !== -1 && process.argv[portArgIndex + 1]) {
port = parseInt(process.argv[portArgIndex + 1]) || 8888;
} else if (process.env.PORT) {
port = parseInt(process.env.PORT) || 8888;
}
console.log('Using port:', port);
const app = next({ dev, hostname });
const handle = app.getRequestHandler();
// Hocuspocus(内蔵サーバなし)
const hocuspocus = new Hocuspocus({
async onAuthenticate({ connection, document, context }) {
console.log(`[Hocuspocus] Authentication request for document: ${document?.name || 'unknown'}`);
return true;
},
async onLoadDocument({ documentName }) {
console.log(`[Hocuspocus] Loading document: ${documentName}`);
return null; // 空で開始
},
onConnect({ connection, document }) {
console.log(`[Hocuspocus] ✅ Client connected to document: ${document?.name || 'unknown'}`);
},
onDisconnect({ connection, document }) {
console.log(`[Hocuspocus] 🔌 Client disconnected from document: ${document?.name || 'unknown'}`);
},
onStateless({ payload, document }) {
console.log(`[Hocuspocus] 📨 Stateless for ${document.name}:`, payload);
},
});
app.prepare().then(() => {
console.log('Next.js app prepared successfully');
const server = createServer(async (req, res) => {
console.log('🔵 [HTTP] Request received:', req.method, req.url);
try {
const parsedUrl = parse(req.url, true);
console.log('🔵 [HTTP] Parsed URL:', parsedUrl.pathname);
// /collarecox/api/yjs-sessions エンドポイント: アクティブなYjsセッション一覧を返す
if (parsedUrl.pathname === '/collarecox/api/yjs-sessions') {
const sessions = Array.from(hocuspocus.documents.keys()).map(roomName => {
const sessionId = roomName.replace('transcribe-editor-v2-', '');
const doc = hocuspocus.documents.get(roomName);
return {
sessionId,
roomName,
connectionCount: doc?.getConnectionsCount?.() || 0
};
});
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(JSON.stringify({ sessions }));
return;
}
// Next.js へ
console.log('🔵 [HTTP] Calling Next.js handle()...');
await handle(req, res, parsedUrl);
console.log('🔵 [HTTP] Next.js handle() completed');
} catch (err) {
console.error('Error occurred handling', req.url, err);
res.statusCode = 500;
res.end('internal server error');
}
});
// WebSocket servers
const yjsWss = new WebSocketServer({ noServer: true }); // For Hocuspocus
const realtimeWss = new WebSocketServer({ noServer: true }); // For realtime audio
// Add comprehensive upgrade debugging
server.on('upgrade', (request, socket, head) => {
console.log(`[WebSocket] 🔄 UPGRADE EVENT TRIGGERED!`);
console.log(`[WebSocket] Request URL: ${request.url}`);
console.log(`[WebSocket] Request headers:`, request.headers);
const { pathname } = parse(request.url);
console.log(`[WebSocket] Parsed pathname: ${pathname}`);
if (pathname.startsWith('/collarecox/api/yjs-ws')) {
console.log('[WebSocket] Processing /collarecox/api/yjs-ws upgrade request');
try {
yjsWss.handleUpgrade(request, socket, head, (ws) => {
console.log('[WebSocket] ✅ WebSocket upgrade successful, passing to Hocuspocus');
try {
// ここが肝:Hocuspocus に WebSocket を引き渡す
hocuspocus.handleConnection(ws, request);
console.log('[WebSocket] ✅ Hocuspocus handleConnection called successfully');
} catch (hocuspocusError) {
console.error('[WebSocket] ❌ Hocuspocus handleConnection error:', hocuspocusError);
ws.close();
}
});
} catch (upgradeError) {
console.error('[WebSocket] ❌ WebSocket upgrade error:', upgradeError);
socket.destroy();
}
} else if (pathname === '/collarecox/api/realtime-ws') {
console.log('[WebSocket] Processing /collarecox/api/realtime-ws upgrade request');
console.log('[WebSocket] Socket readable:', socket.readable);
console.log('[WebSocket] Socket writable:', socket.writable);
console.log('[WebSocket] Head length:', head.length);
console.log('[WebSocket] About to call handleUpgrade...');
try {
realtimeWss.handleUpgrade(request, socket, head, (ws) => {
console.log('[WebSocket] ✅ handleUpgrade callback called, about to emit connection event');
realtimeWss.emit('connection', ws, request);
console.log('[WebSocket] ✅ connection event emitted');
});
console.log('[WebSocket] handleUpgrade called (but callback may not have executed yet)');
} catch (upgradeError) {
console.error('[WebSocket] ❌ Realtime WebSocket upgrade error:', upgradeError);
socket.destroy();
}
} else if (pathname === '/_next/webpack-hmr' || pathname === '/collarecox/_next/webpack-hmr') {
console.log('[WebSocket] Processing HMR WebSocket upgrade request');
// Let Next.js handle HMR WebSocket
if (handle.upgrade) {
handle.upgrade(request, socket, head);
} else {
console.error('[WebSocket] ❌ Next.js handle.upgrade not available');
socket.destroy();
}
} else {
console.log(`[WebSocket] ❌ Unknown WebSocket path: ${pathname}, destroying socket`);
socket.destroy();
}
});
// Additional error handlers
server.on('error', (error) => {
console.error('[Server] ❌ HTTP Server error:', error);
});
yjsWss.on('error', (error) => {
console.error('[WebSocket] ❌ YJS WebSocketServer error:', error);
});
realtimeWss.on('error', (error) => {
console.error('[WebSocket] ❌ Realtime WebSocketServer error:', error);
});
// Handle realtime audio WebSocket connections
realtimeWss.on('connection', function connection(clientWs, request) {
console.log('Client connected to realtime WebSocket');
// No need to parse model parameter - using fixed model
// Audio buffer tracking
let audioBufferDuration = 0; // in milliseconds
let lastAudioTimestamp = Date.now();
let accumulatedSilenceDuration = 0; // 累積無音時間(ms)- 有音チャンクでリセット
let audioChunkCount = 0;
let autoCommitTimer = null;
let paragraphBreakTimer = null; // Timer for delayed paragraph break detection
let responseInProgress = false;
let lastCommitTime = 0; // Prevent too frequent commits
let isDummyAudioSending = false; // Flag to prevent duplicate dummy audio sends
let dummyAudioTimeoutId = null; // Timeout ID for stopping dummy audio sending
// Transcription prompt tracking
let transcriptionPrompt = '';
// Transcription model tracking
let transcriptionModel = 'gpt-4o-transcribe'; // Default model
// Speech break detection settings
let speechBreakDetection = false;
let speechBreakMarker = '↩️'; // デフォルト: 改行絵文字
// VAD parameters - controls when OpenAI detects speech end (Server VAD mode only)
// vadSilenceDuration: OpenAI's VAD will fire speech_stopped after this much silence
let vadEnabled = true; // VAD enabled/disabled (default: true)
let vadThreshold = 0.2;
let vadSilenceDuration = 600; // VAD発話終了判定時間: OpenAIがspeech_stoppedを発火する無音時間(推奨: 500-700ms)
let vadPrefixPadding = 300;
// Paragraph break threshold - controls when to insert paragraph break marker
// This is independent from VAD silence duration
// Paragraph break is inserted only when actual silence gap >= this threshold
let paragraphBreakThreshold = 2500; // パラグラフ区切り判定時間: この時間以上の無音でマーカー挿入(推奨: 2000-2500ms)
// Auto-rewrite on paragraph break - automatically rewrite the completed paragraph
let autoRewriteOnParagraphBreak = false; // デフォルト: 無効
let rewriteModel = 'gpt-4.1-mini'; // AI再編モデル(デフォルト: gpt-4.1-mini)
// Force line break at period - adds newline after each Japanese period (。)
let forceLineBreakAtPeriod = true; // デフォルト: 有効
// Auto-commit threshold (milliseconds) - can be adjusted by client
let autoCommitThresholdMs = 5000; // Default: 5 seconds for VA-Cable testing (longer segments = better transcription)
let autoCommitTimerDelayMs = 3000; // Default: 3 seconds delay before timer-commit
let audioBufferSize = 4096; // Default buffer size
let batchMultiplier = 8; // Default batch multiplier
// Session management for Hocuspocus integration
let currentSessionId = null;
let forceCommitObserver = null; // Store observer function for cleanup
let forceCommitStatusMap = null; // Store statusMap reference for cleanup
// Use Realtime API in transcription-only mode (cost-effective)
// Connect with mini model, but configure for ASR-only processing
const realtimeModel = 'gpt-4o-mini-realtime-preview';
// Connect to OpenAI Realtime API (will be configured for transcription-only)
const openaiUrl = `wss://api.openai.com/v1/realtime?model=${realtimeModel}`;
console.log('Connecting to OpenAI Realtime API (transcription-only mode):', openaiUrl);
// Create proxy agent if HTTPS_PROXY is set
const proxyAgent = process.env.HTTPS_PROXY ? new HttpsProxyAgent(process.env.HTTPS_PROXY) : undefined;
const openaiWs = new WebSocket(openaiUrl, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'OpenAI-Beta': 'realtime=v1'
},
agent: proxyAgent
});
// Function to create session configuration for transcription-only mode
// Optimized to minimize Realtime model usage and maximize transcription accuracy
const createSessionConfig = (prompt = '', asrModel = 'gpt-4o-transcribe') => ({
type: 'session.update',
session: {
modalities: ['text'], // Only text output (no audio responses)
instructions: 'Transcription only mode.', // Minimal instructions
input_audio_format: 'pcm16',
input_audio_transcription: {
model: asrModel, // Use dedicated ASR model (gpt-4o-transcribe)
language: 'ja', // Explicitly specify Japanese to prevent other language detection
...(prompt ? { prompt: prompt } : {})
},
// Conditionally enable/disable VAD based on vadEnabled flag
turn_detection: vadEnabled ? {
type: 'server_vad',
threshold: vadThreshold,
prefix_padding_ms: vadPrefixPadding,
silence_duration_ms: vadSilenceDuration
} : null, // null = disable VAD
temperature: 0.6, // Minimum allowed value for Realtime API
max_response_output_tokens: 1 // Minimize response generation
}
});
// Initial session configuration (will be updated when prompt/model is received)
let sessionConfig = createSessionConfig(transcriptionPrompt, transcriptionModel);
openaiWs.on('open', () => {
console.log('🔗 Connected to OpenAI Realtime API');
console.log('📋 Sending session config:', JSON.stringify(sessionConfig, null, 2));
openaiWs.send(JSON.stringify(sessionConfig));
// Send ready signal to client
clientWs.send(JSON.stringify({
type: 'ready',
message: 'Connected to OpenAI Realtime API'
}));
});
openaiWs.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
console.log('OpenAI message type:', message.type);
// Handle different message types
switch (message.type) {
case 'session.created':
console.log('OpenAI session created:', message.session?.id || 'unknown');
break;
case 'session.updated':
console.log('OpenAI session updated successfully');
break;
case 'conversation.item.created':
console.log('Conversation item created:', message.item?.id);
break;
case 'conversation.item.input_audio_transcription.completed':
console.log('✅ Audio transcription completed:', message.transcript);
responseInProgress = false; // Reset response flag
// Clear any pending auto-commit timer to prevent race condition
if (autoCommitTimer) {
clearTimeout(autoCommitTimer);
autoCommitTimer = null;
console.log('🧹 Cleared auto-commit timer after transcription completion');
}
// Reset buffer tracking after successful transcription
audioBufferDuration = 0;
audioChunkCount = 0;
console.log('Buffer reset after transcription completion');
// Apply force line break at period processing if enabled
let processedTranscript = message.transcript;
if (forceLineBreakAtPeriod && processedTranscript) {
processedTranscript = processedTranscript.replace(/。/g, '。\n');
console.log('📝 Applied force line break at period');
}
// Send the actual transcription to client
clientWs.send(JSON.stringify({
type: 'transcription',
text: processedTranscript,
item_id: message.item_id
}));
// Note: dummy_audio_completed is now sent from sendDummyAudioData when all chunks are sent
// Send text to Hocuspocus document if session is active
console.log(`[Debug] currentSessionId: "${currentSessionId}", processedTranscript: "${processedTranscript}"`);
if (currentSessionId && processedTranscript) {
sendTextToHocuspocusDocument(currentSessionId, processedTranscript);
// Clear pending text after transcription is complete
clearPendingText(currentSessionId);
} else {
console.log(`[Debug] ❌ Hocuspocus integration NOT triggered - currentSessionId: ${currentSessionId ? 'SET' : 'UNDEFINED'}, transcript: ${processedTranscript ? 'HAS_CONTENT' : 'EMPTY'}`);
}
break;
case 'conversation.item.input_audio_transcription.failed':
console.log('Transcription failed:', message.error);
responseInProgress = false; // Reset response flag on failure
// Clear any pending auto-commit timer to prevent race condition
if (autoCommitTimer) {
clearTimeout(autoCommitTimer);
autoCommitTimer = null;
console.log('🧹 Cleared auto-commit timer after transcription failure');
}
clientWs.send(JSON.stringify({
type: 'transcription_error',
error: message.error?.message || 'Transcription failed',
item_id: message.item_id
}));
break;
case 'input_audio_buffer.committed':
console.log('✅ Audio buffer committed successfully:', message.item_id);
break;
case 'conversation.item.input_audio_transcription.started':
console.log('🎤 Audio transcription started:', message.item_id);
break;
case 'conversation.item.input_audio_transcription.delta':
// Forward partial transcription to client for "recognition in progress" display
console.log('🔤 Transcription delta:', message.delta, '(item_id:', message.item_id, ')');
if (message.delta) {
clientWs.send(JSON.stringify({
type: 'transcription_delta',
delta: message.delta,
item_id: message.item_id
}));
// Also broadcast pending text to collaborative editor via Yjs
if (currentSessionId) {
updatePendingText(currentSessionId, message.delta);
}
}
break;
case 'input_audio_buffer.cleared':
console.log('Audio buffer cleared');
break;
case 'input_audio_buffer.speech_started':
console.log('Speech detected');
// Cancel pending paragraph break timer (speech resumed before threshold reached)
if (paragraphBreakTimer) {
clearTimeout(paragraphBreakTimer);
paragraphBreakTimer = null;
console.log('⏹️ Cancelled pending paragraph break timer (speech resumed)');
}
// Reset accumulated silence when speech starts
accumulatedSilenceDuration = 0;
clientWs.send(JSON.stringify({
type: 'speech_started',
audio_start_ms: message.audio_start_ms
}));
// Update transcription status in Hocuspocus document
if (currentSessionId) {
updateTranscriptionStatus(currentSessionId, true);
}
break;
case 'input_audio_buffer.speech_stopped':
// VAD fires speech_stopped after detecting vadSilenceDuration ms of silence
// Use the larger of: accumulated silence OR vadSilenceDuration (VAD's minimum)
const silenceGapMs = Math.max(accumulatedSilenceDuration, vadSilenceDuration);
console.log(`Speech ended (accumulated: ${accumulatedSilenceDuration.toFixed(0)}ms, VAD min: ${vadSilenceDuration}ms, using: ${silenceGapMs.toFixed(0)}ms, paragraph threshold: ${paragraphBreakThreshold}ms)`);
// Send speech_stopped to client immediately
clientWs.send(JSON.stringify({
type: 'speech_stopped',
audio_end_ms: message.audio_end_ms,
marker: speechBreakDetection ? speechBreakMarker : null,
silence_gap_ms: silenceGapMs,
silence_threshold_ms: paragraphBreakThreshold
}));
// For paragraph breaks: if current silence is already enough, insert immediately
// Otherwise, set a timer to wait for more silence and insert if speech doesn't resume
if (speechBreakDetection && silenceGapMs >= paragraphBreakThreshold) {
console.log(`🔸 Immediate paragraph break (silence: ${silenceGapMs.toFixed(0)}ms >= threshold: ${paragraphBreakThreshold}ms)`);
// Send marker to client for text display
clientWs.send(JSON.stringify({
type: 'paragraph_break',
marker: speechBreakMarker
}));
if (currentSessionId) {
createParagraphBreak(currentSessionId, speechBreakMarker);
// Auto-rewrite the completed paragraph if enabled
if (autoRewriteOnParagraphBreak) {
autoRewriteLastParagraph(currentSessionId, clientWs, rewriteModel);
}
}
} else if (speechBreakDetection && paragraphBreakThreshold > vadSilenceDuration) {
// Set a delayed timer to insert paragraph break if silence continues
const remainingWaitMs = paragraphBreakThreshold - silenceGapMs;
console.log(`⏳ Waiting ${remainingWaitMs}ms more for paragraph break...`);
// Store the timer so we can cancel it if speech_started fires
if (paragraphBreakTimer) {
clearTimeout(paragraphBreakTimer);
}
paragraphBreakTimer = setTimeout(() => {
console.log(`🔸 Delayed paragraph break after ${paragraphBreakThreshold}ms total silence`);
clientWs.send(JSON.stringify({
type: 'paragraph_break',
marker: speechBreakMarker
}));
if (currentSessionId) {
createParagraphBreak(currentSessionId, speechBreakMarker);
// Auto-rewrite the completed paragraph if enabled
if (autoRewriteOnParagraphBreak) {
autoRewriteLastParagraph(currentSessionId, clientWs, rewriteModel);
}
}
paragraphBreakTimer = null;
}, remainingWaitMs);
}
// Clear transcription status (will be confirmed in transcription_completed)
if (currentSessionId) {
updateTranscriptionStatus(currentSessionId, false);
}
break;
case 'response.created':
console.log('Response created:', message.response?.id);
break;
case 'response.done':
console.log('Response completed:', message.response?.id);
responseInProgress = false; // Reset response flag when response is done
break;
case 'rate_limits.updated':
// Handle rate limit updates silently
console.log('Rate limits updated');
break;
case 'response.output_item.added':
console.log('Output item added:', message.item?.type);
break;
case 'response.text.delta':
// Handle streaming text deltas
if (message.delta) {
console.log('Text delta received:', message.delta);
// Don't reset response flag - text is still streaming
}
break;
case 'response.text.done':
// Text streaming completed
console.log('Text streaming completed');
// Don't reset response flag yet - wait for content_part.done
break;
case 'response.content_part.added':
if (message.part?.type === 'text') {
console.log('Text content added:', message.part.text);
}
break;
case 'response.content_part.done':
if (message.part?.type === 'text') {
console.log('⚠️ Text response completed (ignoring for transcription):', message.part.text);
responseInProgress = false; // Reset response flag
// Don't send generic text responses to client - only real transcriptions
// The actual transcriptions come from conversation.item.input_audio_transcription.completed
}
break;
case 'response.output_item.done':
console.log('Output item completed:', message.item?.id);
// Don't reset response flag - wait for response.done
break;
case 'error':
console.log('OpenAI API error:', message.error);
responseInProgress = false; // Reset response flag on error
// Handle buffer-related errors gracefully
if (message.error && message.error.message && message.error.message.includes('buffer')) {
// This is expected when Server VAD auto-commits an already-committed buffer
// Just log as warning and don't send to client (it's not a real error)
console.log('⚠️ Buffer-related warning (expected with Server VAD):', message.error.message);
console.log('📝 This occurs when OpenAI VAD tries to auto-commit after manual commit - not a problem');
audioBufferDuration = 0;
audioChunkCount = 0;
// Clear any pending timer
if (autoCommitTimer) {
clearTimeout(autoCommitTimer);
autoCommitTimer = null;
}
// Don't send this error to client - it's not a user-facing issue
break;
}
// Send other errors to client
clientWs.send(JSON.stringify({
type: 'error',
error: message.error?.message || 'Unknown error from OpenAI'
}));
break;
default:
// Log other message types for debugging
console.log('Unhandled OpenAI message type:', message.type);
// Don't automatically reset response flag - let specific handlers manage it
// Only reset on actual error conditions, not unknown message types
}
} catch (error) {
console.error('Error parsing OpenAI message:', error);
// Reset response flag on parsing error
responseInProgress = false;
}
});
openaiWs.on('error', (error) => {
console.error('OpenAI WebSocket error:', error);
clientWs.send(JSON.stringify({
type: 'error',
error: 'Connection to OpenAI failed: ' + error.message
}));
});
openaiWs.on('close', () => {
console.log('OpenAI WebSocket closed');
clientWs.close();
});
// Handle messages from client
clientWs.on('message', (data) => {
try {
const message = JSON.parse(data.toString());
switch (message.type) {
case 'set_session_id':
// Set current session ID for Hocuspocus integration
if (message.sessionId) {
currentSessionId = message.sessionId;
console.log(`📋 Set current session ID: ${currentSessionId}`);
console.log(`[Debug] Session ID successfully stored for Hocuspocus integration`);
// Set up forceCommit observer on statusMap
// Clean up previous observer if exists
if (forceCommitObserver && forceCommitStatusMap) {
try {
forceCommitStatusMap.unobserve(forceCommitObserver);
console.log(`[Yjs] 🧹 Cleaned up previous forceCommit observer`);
} catch (cleanupError) {
console.warn(`[Yjs] ⚠️ Failed to clean up previous observer:`, cleanupError);
}
}
try {
const roomName = `transcribe-editor-v2-${message.sessionId}`;
const document = hocuspocus.documents.get(roomName);
if (document) {
const statusMap = document.getMap(`status-${message.sessionId}`);
// Create observer function and store reference for cleanup
forceCommitObserver = (event) => {
const forceCommit = statusMap.get('forceCommit');
if (forceCommit === true) {
console.log(`[Yjs] 🎤 Force commit requested for session ${message.sessionId}`);
statusMap.set('forceCommit', false); // Reset immediately
if (openaiWs && openaiWs.readyState === WebSocket.OPEN) {
openaiWs.send(JSON.stringify({
type: 'input_audio_buffer.commit'
}));
console.log('[Server] 🎤 Force commit sent to OpenAI');
} else {
console.log('[Server] ⚠️ No active OpenAI connection for force commit');
}
}
};
forceCommitStatusMap = statusMap;
statusMap.observe(forceCommitObserver);
console.log(`[Yjs] 👀 ForceCommit observer set up for session ${message.sessionId}`);
} else {
console.log(`[Yjs] ⚠️ Document not found for forceCommit observer: ${roomName}`);
}
} catch (observerError) {
console.error(`[Yjs] ❌ Error setting up forceCommit observer:`, observerError);
}
} else {
console.log(`[Debug] ❌ set_session_id message received but sessionId is empty:`, message);
}
break;
case 'set_prompt':
// Update transcription prompt
if (message.prompt !== undefined) {
transcriptionPrompt = message.prompt;
console.log('📝 Received transcription prompt:', transcriptionPrompt || '(empty)');
// Update session configuration with new prompt
sessionConfig = createSessionConfig(transcriptionPrompt, transcriptionModel);
// Send updated session config to OpenAI if connection is open
if (openaiWs.readyState === 1) { // WebSocket.OPEN
console.log('🔄 Updating OpenAI session with new prompt...');
openaiWs.send(JSON.stringify(sessionConfig));
console.log('✅ Session updated with transcription prompt');
}
}
break;
case 'set_transcription_model':
// Update transcription model
if (message.model) {
const validTranscriptionModels = ['whisper-1', 'gpt-4o-transcribe', 'gpt-4o-mini-transcribe'];
if (validTranscriptionModels.includes(message.model)) {
transcriptionModel = message.model;
console.log('🎤 Received transcription model:', transcriptionModel);
// Update session configuration with new model
sessionConfig = createSessionConfig(transcriptionPrompt, transcriptionModel);
// Send updated session config to OpenAI if connection is open
if (openaiWs.readyState === 1) { // WebSocket.OPEN
console.log('🔄 Updating OpenAI session with new transcription model...');
openaiWs.send(JSON.stringify(sessionConfig));
console.log('✅ Session updated with transcription model');
}
} else {
console.error('❌ Invalid transcription model:', message.model);
clientWs.send(JSON.stringify({
type: 'error',
error: `Invalid transcription model. Use: ${validTranscriptionModels.join(', ')}`
}));
}
}
break;
case 'set_speech_break_detection':
// Update speech break detection settings
if (message.enabled !== undefined) {
speechBreakDetection = message.enabled;
console.log('🔸 Speech break detection enabled:', speechBreakDetection);
}
if (message.marker) {
speechBreakMarker = message.marker;
console.log('🔸 Speech break marker set to:', speechBreakMarker);
}
break;
case 'set_vad_params':
// Update VAD parameters (with validation to prevent null values)
// VAD発話終了判定時間: OpenAIがspeech_stoppedを発火する無音時間
if (message.enabled !== undefined) {
vadEnabled = message.enabled;
console.log('🎛️ VAD enabled set to:', vadEnabled);
}
if (message.threshold !== undefined && message.threshold !== null && typeof message.threshold === 'number') {
vadThreshold = Math.max(0.0, Math.min(1.0, Number(message.threshold))); // Ensure number and clamp to 0.0-1.0
console.log('🎛️ VAD threshold set to:', vadThreshold);
}
if (message.silence_duration_ms !== undefined && message.silence_duration_ms !== null && typeof message.silence_duration_ms === 'number') {
vadSilenceDuration = Math.max(200, Math.min(10000, Number(message.silence_duration_ms))); // Ensure number and clamp to valid range
console.log('🎛️ VAD発話終了判定時間 set to:', vadSilenceDuration + 'ms');
}
if (message.prefix_padding_ms !== undefined && message.prefix_padding_ms !== null && typeof message.prefix_padding_ms === 'number') {
vadPrefixPadding = Math.max(0, Math.min(2000, Number(message.prefix_padding_ms))); // Ensure number and clamp to 0-2000
console.log('🎛️ VAD prefix padding set to:', vadPrefixPadding + 'ms');
}
// パラグラフ区切り判定時間: この時間以上の無音でマーカー挿入
if (message.paragraph_break_threshold_ms !== undefined && message.paragraph_break_threshold_ms !== null && typeof message.paragraph_break_threshold_ms === 'number') {
paragraphBreakThreshold = Math.max(500, Math.min(30000, Number(message.paragraph_break_threshold_ms))); // Ensure number and clamp to 500-30000
console.log('📝 パラグラフ区切り判定時間 set to:', paragraphBreakThreshold + 'ms');
}
// Update session configuration with new VAD parameters
sessionConfig = createSessionConfig(transcriptionPrompt, transcriptionModel);
// Send updated session config to OpenAI if connection is open
if (openaiWs.readyState === 1) { // WebSocket.OPEN
console.log('🔄 Updating OpenAI session with new VAD parameters...');
openaiWs.send(JSON.stringify(sessionConfig));
console.log('✅ Session updated with VAD parameters');
}
break;
case 'set_auto_rewrite':
// Update auto-rewrite on paragraph break setting
if (message.enabled !== undefined) {
autoRewriteOnParagraphBreak = message.enabled;
console.log('🔄 Auto-rewrite on paragraph break:', autoRewriteOnParagraphBreak ? 'enabled' : 'disabled');
}
// Update rewrite model
if (message.model) {
const validRewriteModels = ['gpt-4o-mini', 'gpt-4o', 'gpt-4.1-mini', 'gpt-4.1'];
if (validRewriteModels.includes(message.model)) {
rewriteModel = message.model;
console.log('🤖 Rewrite model set to:', rewriteModel);
} else {
console.error('❌ Invalid rewrite model:', message.model);
clientWs.send(JSON.stringify({
type: 'error',
error: `Invalid rewrite model. Use: ${validRewriteModels.join(', ')}`
}));
}
}
break;
case 'set_force_line_break':
// Update force line break at period setting
if (message.enabled !== undefined) {
forceLineBreakAtPeriod = message.enabled;
console.log('📝 Force line break at period:', forceLineBreakAtPeriod ? 'enabled' : 'disabled');
}
break;
case 'set_commit_threshold':
// Update auto-commit threshold from client
if (message.threshold_ms !== undefined && message.threshold_ms > 0) {
autoCommitThresholdMs = message.threshold_ms;
autoCommitTimerDelayMs = Math.max(autoCommitThresholdMs * 2, 2000); // At least 2 seconds
if (message.buffer_size !== undefined) {
audioBufferSize = message.buffer_size;
}
if (message.batch_multiplier !== undefined) {
batchMultiplier = message.batch_multiplier;
}
console.log(`⏱️ Auto-commit threshold set to: ${autoCommitThresholdMs}ms (buffer: ${audioBufferSize}, batch: ${batchMultiplier}, timer delay: ${autoCommitTimerDelayMs}ms)`);
}
break;
case 'audio_chunk':
// Only process if we have actual audio data
if (!message.audio || message.audio.length === 0) {
console.warn('Received empty audio chunk, skipping');
return;
}
// Validate audio data first
const audioData = Buffer.from(message.audio, 'base64');
// Node.js Bufferの共有プール問題とbyteOffsetアライメント問題を回避
// audioData.bufferは共有プールを指す可能性があり、byteOffsetが2バイト境界でない場合、
// Int16Arrayの読み取りが正しく動作しない
const arrayBuffer = audioData.buffer.slice(audioData.byteOffset, audioData.byteOffset + audioData.length);
const int16Array = new Int16Array(arrayBuffer);
// Use loop instead of spread operator to avoid stack overflow with large arrays
let maxSample = 0;
let sumSample = 0;
for (let i = 0; i < int16Array.length; i++) {
const absVal = Math.abs(int16Array[i]);
if (absVal > maxSample) maxSample = absVal;
sumSample += absVal;
}
const avgSample = sumSample / int16Array.length;
audioChunkCount++;
// Log silent audio chunks but don't skip (for accurate VAD detection)
// Track accumulated silence duration for paragraph break detection
const sampleDurationMs = (audioData.length / 2 / 24000) * 1000; // ms per chunk at 24kHz
if (maxSample < 100) {
// Silent chunk - accumulate silence duration
accumulatedSilenceDuration += sampleDurationMs;
console.log(`📊 Silent audio chunk ${audioChunkCount}: max sample=${maxSample}, accumulated silence=${accumulatedSilenceDuration.toFixed(0)}ms`);
} else {
// Voice detected - reset accumulated silence
if (accumulatedSilenceDuration > 0) {
console.log(`🎤 Voice detected - resetting accumulated silence (was ${accumulatedSilenceDuration.toFixed(0)}ms)`);
}
accumulatedSilenceDuration = 0;
}
// Track audio buffer duration for all chunks (including silent)
const sampleCount = audioData.length / 2; // 16-bit = 2 bytes per sample
const chunkDurationMs = (sampleCount / 24000) * 1000; // duration at 24kHz
audioBufferDuration += chunkDurationMs;
lastAudioTimestamp = Date.now();
console.log(`Audio chunk ${audioChunkCount}: buffer=${audioBufferDuration}ms, size=${message.audio.length} chars, max sample=${maxSample}`);
// Log first few samples for debugging
if (audioChunkCount <= 3) {
console.log(`First 10 samples:`, Array.from(int16Array.slice(0, 10)));
}
// Send valid audio data with actual content
const audioEvent = {
type: 'input_audio_buffer.append',
audio: message.audio // Base64 encoded PCM16 audio
};
// Check WebSocket state before sending
if (openaiWs.readyState === 1) { // WebSocket.OPEN
openaiWs.send(JSON.stringify(audioEvent));
console.log(`✅ Audio sent to OpenAI: ${audioData.length} bytes, max sample: ${maxSample}`);
} else {
console.log(`⚠️ OpenAI WebSocket not ready (state: ${openaiWs.readyState}), skipping audio chunk`);
}
// Clear any existing timer
if (autoCommitTimer) {
clearTimeout(autoCommitTimer);
}
// When Server VAD is enabled, skip manual commit - let OpenAI handle it automatically
if (vadEnabled) {
// VAD mode: OpenAI's Server VAD handles transcription timing automatically
// Just track buffer for logging purposes, don't send manual commits
break;
}
// Auto-commit when we have enough audio with rate limiting (only when VAD is disabled)
const now = Date.now();
const timeSinceLastCommit = now - lastCommitTime;
if (audioBufferDuration >= autoCommitThresholdMs && !responseInProgress && timeSinceLastCommit >= (autoCommitThresholdMs * 2)) {
console.log(`Auto-committing audio buffer: ${audioBufferDuration}ms (threshold: ${autoCommitThresholdMs}ms), ${audioChunkCount} chunks`);
responseInProgress = true;
lastCommitTime = now;
// Just commit the audio buffer - transcription should happen automatically
const commitEvent = {
type: 'input_audio_buffer.commit'
};
if (openaiWs.readyState === 1) { // WebSocket.OPEN
openaiWs.send(JSON.stringify(commitEvent));
console.log('✅ Audio buffer committed, waiting for automatic transcription...');
} else {
console.log(`⚠️ OpenAI WebSocket not ready for commit (state: ${openaiWs.readyState})`);
responseInProgress = false; // Reset flag
}
// Don't reset buffer tracking immediately - let transcription complete first
// audioBufferDuration = 0;
// audioChunkCount = 0;
} else {
// Set a timer to commit after specified delay with no new audio
autoCommitTimer = setTimeout(() => {
const timerNow = Date.now();
const timerTimeSinceLastCommit = timerNow - lastCommitTime;
// Check buffer duration again to prevent race condition with transcription completion
const minBufferForTimer = Math.max(500, autoCommitThresholdMs * 0.5); // At least 50% of threshold
const minTimeSinceLastCommit = Math.max(1500, autoCommitThresholdMs * 1.5); // At least 1.5x threshold
if (audioBufferDuration >= minBufferForTimer && !responseInProgress && timerTimeSinceLastCommit >= minTimeSinceLastCommit) {
console.log(`Timer-based commit: ${audioBufferDuration}ms (min: ${minBufferForTimer}ms), ${audioChunkCount} chunks`);
responseInProgress = true;
lastCommitTime = timerNow;
// Just commit the audio buffer - transcription should happen automatically
const commitEvent = {
type: 'input_audio_buffer.commit'
};
if (openaiWs.readyState === 1) { // WebSocket.OPEN
openaiWs.send(JSON.stringify(commitEvent));
console.log('✅ Audio buffer committed (timer), waiting for automatic transcription...');
} else {
console.log(`⚠️ OpenAI WebSocket not ready for timer commit (state: ${openaiWs.readyState})`);
responseInProgress = false; // Reset flag
}
// Don't reset buffer tracking immediately
// audioBufferDuration = 0;
// audioChunkCount = 0;
} else {
// Log why commit was skipped
if (audioBufferDuration < minBufferForTimer) {
console.log(`⏭️ Skipping timer commit - buffer too small: ${audioBufferDuration}ms (minimum: ${minBufferForTimer}ms)`);
} else if (responseInProgress) {
console.log('⏭️ Skipping timer commit - response already in progress');
} else if (timerTimeSinceLastCommit < minTimeSinceLastCommit) {
console.log(`⏭️ Skipping timer commit - too soon after last commit: ${timerTimeSinceLastCommit}ms (minimum: ${minTimeSinceLastCommit}ms)`);
}
}
}, autoCommitTimerDelayMs);
}
break;
case 'audio_commit':
// Only commit if we have enough audio and not already processing
if (audioBufferDuration >= 100 && !responseInProgress) {
console.log(`Manual commit: ${audioBufferDuration}ms, ${audioChunkCount} chunks`);
responseInProgress = true;
lastCommitTime = Date.now();
// Just commit the audio buffer - transcription should happen automatically
const commitEvent = {
type: 'input_audio_buffer.commit'
};
if (openaiWs.readyState === 1) { // WebSocket.OPEN
openaiWs.send(JSON.stringify(commitEvent));
console.log('✅ Audio buffer committed (manual), waiting for automatic transcription...');
} else {
console.log(`⚠️ OpenAI WebSocket not ready for manual commit (state: ${openaiWs.readyState})`);
responseInProgress = false; // Reset flag
}
// Don't reset buffer tracking immediately
// audioBufferDuration = 0;
// audioChunkCount = 0;
} else {
console.log(`Skipping manual commit - insufficient audio: ${audioBufferDuration}ms (need >= 100ms) or response in progress: ${responseInProgress}`);
}
break;
case 'clear_audio_buffer':
// Clear the audio buffer
const clearEvent = {
type: 'input_audio_buffer.clear'
};
if (openaiWs.readyState === 1) { // WebSocket.OPEN
openaiWs.send(JSON.stringify(clearEvent));
console.log('Audio buffer cleared');
} else {
console.log(`⚠️ OpenAI WebSocket not ready for clear (state: ${openaiWs.readyState})`);
}
// Reset buffer tracking
audioBufferDuration = 0;
audioChunkCount = 0;
break;
case 'send_dummy_audio_data':
// Send dummy audio data directly from client (localStorage)
if (isDummyAudioSending) {
console.log('⚠️ Dummy audio is already being sent, ignoring new request');
clientWs.send(JSON.stringify({
type: 'error',
error: '録音データ送信中です。完了をお待ちください。'
}));
break;
}
if (message.audioData) {
isDummyAudioSending = true;
const sendInterval = message.sendInterval || 50; // Default to 50ms if not specified
console.log(`[Dummy Audio] Using send interval: ${sendInterval}ms`);
dummyAudioTimeoutId = sendDummyAudioData(message.audioData, message.name || 'Client Recording', clientWs, openaiWs, () => {
responseInProgress = true;
lastCommitTime = Date.now();
}, () => {
// onComplete callback - reset flag when sending is done
isDummyAudioSending = false;
dummyAudioTimeoutId = null;
}, sendInterval);