v50: WS — trySend полинг вместо onopen, фикс race condition

This commit is contained in:
“Naeel”
2026-05-22 17:17:52 +04:00
parent f4ac9cf717
commit 8fc986fe7f
+21 -20
View File
@@ -53,7 +53,7 @@ let mediaRecorder, audioChunks = [], userAudioBlob = null, ttsText = '';
let isRecording = false, isAnalyzing = false, micAnalyser = null, micAnimId = null;
let recordStartTime = 0, recordDuration = 0;
// ---------- Версия ----------
const VERSION = 'v49';
const VERSION = 'v50';
document.getElementById('ver').textContent = VERSION;
// ---------- Перевод на русский (Groq) ----------
@@ -627,30 +627,31 @@ async function transcribe(blob) {
return new Promise((resolve) => {
let settled = false;
const done = (result) => { if (settled) return; settled = true; ws.close(); resolve(result); };
const done = (r) => { if (settled) return; settled = true; try { ws.close(); } catch(e){} resolve(r); };
const payload = JSON.stringify({ token: GROQ_API_KEY, audio_b64: base64, mime: blob.type || 'audio/webm' });
const ws = new WebSocket('wss://proxy.kube5s.ru/ws');
const timeout = setTimeout(() => { console.log('[WS] timeout'); done({ text: '', error: 'timeout' }); }, 60000);
ws.onopen = () => {
setTimeout(() => {
try {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ token: GROQ_API_KEY, audio_b64: base64, mime: blob.type || 'audio/webm' }));
console.log('[WS] sent');
} else {
console.log('[WS] not open, state=' + ws.readyState);
clearTimeout(timeout);
done({ text: '', error: 'network' });
}
} catch (e) {
console.log('[WS] send error:', e);
clearTimeout(timeout);
done({ text: '', error: 'network' });
}
}, 0);
// Полинг readyState — onopen может не сработать если WS открылся до присвоения
const trySend = () => {
if (settled) return;
const st = ws.readyState;
if (st === WebSocket.OPEN) {
try { ws.send(payload); console.log('[WS] sent'); } catch(e) { console.log('[WS] send err:', e); done({ text: '', error: 'network' }); }
return;
}
if (st === WebSocket.CONNECTING) { setTimeout(trySend, 20); return; }
// CLOSING or CLOSED
console.log('[WS] aborted, state=' + st);
clearTimeout(timeout);
done({ text: '', error: 'network' });
};
ws.onopen = trySend;
// Если WS уже открыт — onopen не вызовется, trySend сам отработает
trySend();
ws.onmessage = (e) => {
clearTimeout(timeout);
const data = JSON.parse(e.data);
@@ -659,7 +660,7 @@ async function transcribe(blob) {
};
ws.onerror = () => { console.log('[WS] error'); clearTimeout(timeout); done({ text: '', error: 'network' }); };
ws.onclose = (e) => { console.log('[WS] close code=' + e.code + ' reason=' + e.reason); clearTimeout(timeout); done({ text: '', error: 'network' }); };
ws.onclose = (e) => { console.log('[WS] close code=' + e.code); clearTimeout(timeout); done({ text: '', error: 'network' }); };
});
}