adityaverma977 commited on
Commit
56215c3
·
1 Parent(s): 0e54f19

Fix websocket backend URL for HF Space deployments

Browse files
Files changed (1) hide show
  1. frontend/lib/websocket.ts +35 -0
frontend/lib/websocket.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const BACKEND_URL = (process.env.NEXT_PUBLIC_BACKEND_URL || "http://localhost:8000").replace(/\/$/, "")
2
+
3
+ export function createSimulationSocket(
4
+ simulationId: string,
5
+ onMessage: (msg: any) => void,
6
+ onError: () => void
7
+ ) {
8
+ const wsBase = BACKEND_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:")
9
+ const wsUrl = `${wsBase}/ws/${simulationId}`
10
+
11
+ const ws = new WebSocket(wsUrl)
12
+
13
+ ws.onmessage = (event) => {
14
+ try {
15
+ const msg = JSON.parse(event.data)
16
+ // DEBUG: surface incoming websocket payload for troubleshooting
17
+ try { console.debug("WS_RECV", msg) } catch (e) {}
18
+ onMessage(msg)
19
+ } catch (e) {
20
+ console.error("Failed to parse WebSocket message:", e)
21
+ }
22
+ }
23
+
24
+ ws.onerror = (error) => {
25
+ console.error("WebSocket error:", error)
26
+ onError()
27
+ }
28
+
29
+ ws.onclose = (event) => {
30
+ console.log("WebSocket closed", { code: event.code, reason: event.reason })
31
+ onError()
32
+ }
33
+
34
+ return ws
35
+ }