Skip to content

Commit 1932d3b

Browse files
committed
fix: recover from container restart without losing session
When HF Space rebuilds, the in-memory _sessions dict is wiped but WebSocket may survive through the reverse proxy. Previously this caused 'Agent not initialized' because ws.onopen didn't fire. Now: server sends 'request_keys' event when session is lost. Client auto-resends keys from sessionStorage and retries the last message after a 3-second delay for session initialization.
1 parent da771da commit 1932d3b

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

web/routes/websocket.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,13 @@ async def websocket_chat(websocket: WebSocket):
9898
# Get session for this connection (auto-recreate if lost)
9999
session = get_session(connection_id)
100100
if not session:
101-
logger.warning(f"Session lost for {connection_id[:8]}, recreating...")
102-
session = create_session(connection_id)
101+
logger.warning(f"Session lost for {connection_id[:8]}, requesting keys...")
102+
# Ask client to resend keys (e.g., after container restart)
103+
await manager.send_json(websocket, {
104+
"type": "request_keys",
105+
"reason": "Session expired, please reconnect."
106+
})
107+
continue
103108

104109
# Callback for streaming
105110
async def stream_callback(event_type: str, content: str, **kwargs):

web/static/js/chat.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ class EurusChat {
385385
if (!message || !this.isConnected) return;
386386

387387
this.addUserMessage(message);
388+
this._lastSentMessage = message;
388389
this.ws.send(JSON.stringify({ message }));
389390

390391
this.messageInput.value = '';
@@ -406,6 +407,22 @@ class EurusChat {
406407
}
407408
break;
408409

410+
case 'request_keys':
411+
// Server lost our session (e.g., container restart) — resend keys
412+
console.warn('Server requested keys:', data.reason);
413+
this.removeThinkingIndicator();
414+
this.autoSendSessionKeys();
415+
// Retry the last message after a short delay for session init
416+
if (this._lastSentMessage) {
417+
setTimeout(() => {
418+
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
419+
this.ws.send(JSON.stringify({ message: this._lastSentMessage }));
420+
this.showThinkingIndicator();
421+
}
422+
}, 3000);
423+
}
424+
break;
425+
409426
case 'thinking':
410427
this.showThinkingIndicator();
411428
break;

0 commit comments

Comments
 (0)