Spaces:
Running

audio / frontend /js /websocket-client.js
michdubai's picture
Update frontend/js/websocket-client.js
df1116b verified
Raw History Blame Contribute Delete
8.88 kB
/**
* WebSocket client for communicating with the Gemini backend
* Handles connection setup, data transmission, auto-reconnection, and event handling
*/
export class WebSocketClient {
constructor() {
this.websocket = null;
this.clientId = null;
this.callbacks = {
onMessage: null,
onClose: null,
onError: null,
onReconnectAttempt: null, // Hook to notify UI during reconnect cycles
onReconnectSuccess: null // Hook to clear UI error overlays on recovery
};
this._url = null;
// Configuration & Reconnection State Tracking
this._cachedConfig = null;
this._isIntentionalDisconnect = false;
this._reattemptCount = 0;
this._maxReattemptLimit = 10;
this._baseBackoffDelay = 1500; // ms
}
/**
* Establish WebSocket connection and configure event handlers
* @param {Object} config - Configuration for Gemini
* @param {Object} callbacks - Event callbacks
* @returns {Promise} - Resolves when connection is established
*/
connect(config, callbacks) {
return new Promise((resolve, reject) => {
// Cache configuration assets to enable self-healing on connection loss
if (config) this._cachedConfig = config;
if (callbacks) {
this.callbacks = { ...this.callbacks, ...callbacks };
}
this._isIntentionalDisconnect = false;
// Clean up any existing stale socket interfaces
if (this.websocket) {
try {
this.websocket.close();
} catch (e) {
// ignore
}
this.websocket = null;
}
// Retain or establish Client Identity across sessions
if (!this.clientId) {
this.clientId = crypto.randomUUID();
}
let resolved = false;
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
this._url = `${protocol}//${window.location.host}/ws/${this.clientId}`;
console.log(`[WS] πŸ“‘ Initiating pipeline connection to: ${this._url}`);
this.websocket = new WebSocket(this._url);
this.websocket.onopen = () => {
console.log("[WS] βœ… Network socket connection established.");
this._reattemptCount = 0; // Reset backoff constraints on success
if (this.callbacks.onReconnectSuccess && this._reattemptCount > 0) {
this.callbacks.onReconnectSuccess();
}
const sendInitialConfig = () => {
if (!this.websocket) return;
if (this.websocket.readyState === WebSocket.OPEN) {
this.websocket.send(JSON.stringify({
type: 'config',
config: this._cachedConfig
}));
if (!resolved) {
resolved = true;
resolve();
}
} else if (this.websocket.readyState === WebSocket.CONNECTING) {
setTimeout(sendInitialConfig, 20);
} else {
if (!resolved) {
resolved = true;
reject(new Error("WebSocket dropped prematurely during channel setup."));
}
}
};
sendInitialConfig();
};
this.websocket.onmessage = (event) => {
try {
const response = JSON.parse(event.data);
if (this.callbacks.onMessage) {
this.callbacks.onMessage(response);
}
} catch (error) {
console.error('[WS] Error parsing incoming stream frame:', error);
}
};
this.websocket.onclose = (event) => {
console.warn(`[WS] Pipeline disconnected. Code: ${event.code}, Reason: ${event.reason}`);
this.websocket = null;
// Trigger reconnection routine if the drop wasn't explicitly triggered by the user
if (!this._isIntentionalDisconnect) {
this._executeAutoRecovery();
} else if (this.callbacks.onClose) {
this.callbacks.onClose();
}
};
this.websocket.onerror = (error) => {
console.error("[WS] Pipeline interface error caught:", error);
// Don't reject if we are already in an active session; let onclose manage lifecycle
if (!resolved) {
resolved = true;
reject(error);
}
};
});
}
/**
* Managed backoff algorithm to cleanly re-route through firewalls/WAFs after drops
*/
async _executeAutoRecovery() {
if (this._reattemptCount >= this._maxReattemptLimit) {
console.error(`[WS] πŸ”₯ Self-healing aborted. Exceeded max limits (${this._maxReattemptLimit}).`);
if (this.callbacks.onClose) this.callbacks.onClose();
return;
}
this._reattemptCount++;
// Exponential backoff delay formulation: e.g., 1.5s, 3s, 6s, 12s...
const backoffDelay = this._baseBackoffDelay * Math.pow(2, this._reattemptCount - 1);
console.warn(`[WS] πŸ”„ Network anomaly detected. Reconnecting attempt #${this._reattemptCount} in ${backoffDelay}ms...`);
if (this.callbacks.onReconnectAttempt) {
this.callbacks.onReconnectAttempt(this._reattemptCount, backoffDelay);
}
await new Promise(resolve => setTimeout(resolve, backoffDelay));
try {
await this.connect(this._cachedConfig, this.callbacks);
console.log("[WS] πŸŽ‰ Auto-recovery sequence completed successfully.");
} catch (err) {
console.error("[WS] ❌ Reconnection attempt failed. Nesting deeper retry loop...", err);
// The embedded onclose handler will automatically capture this failure and safely step to the next index
}
}
/**
* Check if websocket is connected
* @returns {boolean} - True if connected
*/
isConnected() {
return this.websocket && this.websocket.readyState === WebSocket.OPEN;
}
/**
* Send audio data to the server
* @param {string} base64Audio - Base64 encoded audio data
*/
sendAudio(base64Audio) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'audio',
data: base64Audio
}));
}
/**
* Send image data to the server
* @param {string} base64Image - Base64 encoded image data
*/
sendImage(base64Image) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'image',
data: base64Image
}));
}
/**
* Send text message to the server
* @param {string} text - Text to send
*/
sendText(text) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'text',
data: text
}));
}
/**
* Send a file reference (already uploaded) to the server
* @param {string} uri - Gemini file URI
* @param {string} mime_type - MIME type
*/
sendFile(uri, mime_type) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'file',
uri: uri,
mime_type: mime_type
}));
}
/**
* Send raw file bytes for backend upload proxy
* @param {string} base64Data - Base64 encoded file bytes
* @param {string} mime_type - MIME type
*/
sendFileUpload(base64Data, mime_type) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'file_upload',
data: base64Data,
mime_type: mime_type
}));
}
/**
* Send model switch request
* @param {string} model - New model name
*/
sendModelSwitch(model) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'model_switch',
model: model
}));
}
/**
* Send tool response back to server
* @param {Array} responses - Array of {name, result} objects
*/
sendToolResponse(responses) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify({
type: 'tool_response',
responses: responses
}));
}
/**
* Custom message gateway for generic structures
* @param {Object} payload
*/
sendMessage(payload) {
if (!this.isConnected()) return;
this.websocket.send(JSON.stringify(payload));
}
/**
* Close the WebSocket connection intentionally
*/
disconnect() {
this._isIntentionalDisconnect = true;
this._cachedConfig = null;
this._reattemptCount = 0;
if (this.websocket) {
this.websocket.close();
this.websocket = null;
}
console.log("[WS] 🧹 Connection disconnected intentionally by application context.");
}
}