Spaces:
Runtime error
Runtime error
File size: 6,081 Bytes
c1f04cf | 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 | type EventCallback = (data: any) => void;
export class WebSocketManager {
private websocket: WebSocket | null = null;
private streamWebSocket: WebSocket | null = null;
private eventListeners: Map<string, EventCallback[]> = new Map();
private reconnectAttempts = 0;
private maxReconnectAttempts = 5;
private reconnectDelay = 1000;
public connect(jobId: string): void {
if (this.websocket) {
this.websocket.close();
}
// Detect if we're in development mode (frontend on different port than backend)
const isDev = window.location.port === '5173';
const backendHost = isDev ? 'localhost:8000' : window.location.host;
const wsBase = `${window.location.protocol === "https:" ? "wss" : "ws"}://${backendHost}`;
console.log(`π‘ Connecting to WebSocket: ${wsBase}/ws/${jobId}`);
this.websocket = new WebSocket(`${wsBase}/ws/${jobId}`);
this.websocket.onopen = () => {
console.log('π‘ WebSocket connected successfully');
this.reconnectAttempts = 0;
this.emit('connected', { status: 'connected' });
};
this.websocket.onmessage = (event: MessageEvent) => {
try {
const data = JSON.parse(event.data);
console.log('π¨ WebSocket message received:', data.type, data);
// Handle different message types
switch (data.type) {
case 'proxy_stats':
this.emit('proxy_stats', data.stats || data);
break;
case 'decision':
this.emit('decision', data.decision || data);
break;
case 'screenshot':
this.emit('screenshot', data.screenshot || data);
break;
case 'token_usage':
this.emit('token_usage', data.token_usage || data);
break;
case 'page_info':
this.emit('page_info', data);
break;
case 'extraction':
this.emit('extraction', data);
break;
case 'streaming_info':
this.emit('streaming_info', data);
break;
case 'error':
this.emit('error', data);
break;
default:
if (data.status) {
this.emit('status', data);
} else {
this.emit(data.type, data);
}
}
} catch (error) {
console.error('Error parsing WebSocket message:', error, event.data);
}
};
this.websocket.onclose = (event: CloseEvent) => {
console.log('π‘ WebSocket disconnected:', event.code, event.reason);
this.websocket = null;
if (this.reconnectAttempts < this.maxReconnectAttempts) {
this.reconnectAttempts++;
console.log(`π Attempting reconnection ${this.reconnectAttempts}/${this.maxReconnectAttempts}`);
setTimeout(() => this.connect(jobId), this.reconnectDelay);
this.reconnectDelay *= 2;
}
};
this.websocket.onerror = (error: Event) => {
console.error('π‘ WebSocket error:', error);
this.emit('error', { error: 'WebSocket connection error' });
};
}
public connectStream(jobId: string): void {
if (this.streamWebSocket) {
this.streamWebSocket.close();
}
// Detect if we're in development mode (frontend on different port than backend)
const isDev = window.location.port === '5173';
const backendHost = isDev ? 'localhost:8000' : window.location.host;
const wsBase = `${window.location.protocol === "https:" ? "wss" : "ws"}://${backendHost}`;
console.log(`π₯ Connecting to Stream WebSocket: ${wsBase}/stream/${jobId}`);
this.streamWebSocket = new WebSocket(`${wsBase}/stream/${jobId}`);
this.streamWebSocket.onopen = () => {
console.log('π₯ Stream WebSocket connected successfully');
this.emit('stream_connected', { status: 'connected' });
};
this.streamWebSocket.onmessage = (event: MessageEvent) => {
try {
const data = JSON.parse(event.data);
console.log('π₯ Stream message received:', data.type);
this.emit('stream_' + data.type, data);
} catch (error) {
console.error('Error parsing stream message:', error);
}
};
this.streamWebSocket.onclose = () => {
console.log('π₯ Stream WebSocket disconnected');
this.streamWebSocket = null;
this.emit('stream_disconnected', { status: 'disconnected' });
};
this.streamWebSocket.onerror = (error: Event) => {
console.error('π₯ Stream WebSocket error:', error);
this.emit('stream_error', { error: 'Stream connection error' });
};
}
public sendStreamMessage(message: any): void {
if (this.streamWebSocket && this.streamWebSocket.readyState === WebSocket.OPEN) {
this.streamWebSocket.send(JSON.stringify(message));
} else {
console.warn('Stream WebSocket not connected');
}
}
public on(event: string, callback: EventCallback): void {
if (!this.eventListeners.has(event)) {
this.eventListeners.set(event, []);
}
this.eventListeners.get(event)?.push(callback);
console.log(`π Event listener added for: ${event}`);
}
private emit(event: string, data: any): void {
const listeners = this.eventListeners.get(event) || [];
console.log(`π€ Emitting event: ${event} to ${listeners.length} listeners`);
listeners.forEach(callback => {
try {
callback(data);
} catch (error) {
console.error(`Error in event listener for ${event}:`, error);
}
});
}
public disconnect(): void {
if (this.websocket) {
this.websocket.close();
this.websocket = null;
}
}
public disconnectStream(): void {
if (this.streamWebSocket) {
this.streamWebSocket.close();
this.streamWebSocket = null;
}
}
public isConnected(): boolean {
return this.websocket !== null && this.websocket.readyState === WebSocket.OPEN;
}
public isStreamConnected(): boolean {
return this.streamWebSocket !== null && this.streamWebSocket.readyState === WebSocket.OPEN;
}
} |