feat(websocket, demo): enhance WebSocket connection handling in demo mode with improved feedback and connection logic

This commit is contained in:
2026-01-01 19:09:13 -06:00
parent 459b54db51
commit ddb02a7ee9
2 changed files with 48 additions and 24 deletions

View File

@@ -3,15 +3,34 @@ import mitt from "mitt";
class WebSocketConnection {
constructor() {
this.emitter = mitt();
this.reconnect();
this.isDemoMode = false;
this.ws = null;
this.pingInterval = null;
this.initialized = false;
this.checkDemoModeAndConnect();
}
/**
* ping websocket server every 30 seconds
* this helps to prevent the underlying tcp connection from going stale when there's no traffic for a long time
*/
setInterval(() => {
this.ping();
}, 30000);
async checkDemoModeAndConnect() {
if (typeof window === "undefined" || !window.axios) {
setTimeout(() => this.checkDemoModeAndConnect(), 100);
return;
}
try {
const response = await window.axios.get("/api/v1/app/info");
this.isDemoMode = response.data.app_info?.is_demo === true;
} catch (e) {
// If we can't check, assume not demo mode and try to connect
}
this.initialized = true;
if (!this.isDemoMode) {
this.reconnect();
this.pingInterval = setInterval(() => {
this.ping();
}, 30000);
}
}
// add event listener
@@ -30,15 +49,21 @@ class WebSocketConnection {
}
reconnect() {
if (!this.initialized || this.isDemoMode) {
return;
}
// connect to websocket
const wsUrl = location.origin.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws";
this.ws = new WebSocket(wsUrl);
// auto reconnect when websocket closes
this.ws.addEventListener("close", () => {
setTimeout(() => {
this.reconnect();
}, 1000);
if (!this.isDemoMode) {
setTimeout(() => {
this.reconnect();
}, 1000);
}
});
// emit data received from websocket
@@ -54,6 +79,9 @@ class WebSocketConnection {
}
ping() {
if (this.isDemoMode) {
return;
}
try {
this.send(
JSON.stringify({

View File

@@ -234,23 +234,19 @@ server {
add_header Content-Type application/json;
}
# Improved WebSocket handler
# WebSocket handler for demo mode
location /ws {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# In demo mode, returning 200 for non-WS requests provides better feedback
# For non-WebSocket requests, return a simple message
if ($http_upgrade != "websocket") {
return 200 "WebSocket Mock Endpoint (Active)";
add_header Content-Type text/plain;
return 200 "WebSocket endpoint (Demo Mode - WebSocket not available)";
}
# For actual WS connection attempts, we still return 503 as there is no backend server.
return 503;
# For WebSocket upgrade requests, return 426 Upgrade Required
# This is more appropriate than 503 and prevents constant reconnection attempts
add_header Upgrade websocket;
add_header Connection Upgrade;
return 426;
}
# Error pages