Skip to content

Commit d16e15d

Browse files
committed
Fix websocket race conditions by scoping event listeners to local socket instances
1 parent b1435f5 commit d16e15d

1 file changed

Lines changed: 16 additions & 11 deletions

File tree

‎apps/browser/src/background/websocket.ts‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ export const check_server_health = async (): Promise<boolean> => {
1717

1818
export const check_and_recover_connection = () => {
1919
if (websocket?.readyState === WebSocket.OPEN) {
20-
// Server sends ping every 10s. If we missed pings (e.g., system slept), connection is a zombie.
2120
if (Date.now() - last_ping_timestamp > 20000) {
2221
console.warn(
2322
'WebSocket connection is stale (no recent pings). Force reconnecting...'
@@ -52,7 +51,6 @@ export const connect_websocket = async (): Promise<void> => {
5251
const is_healthy = await check_server_health()
5352
if (!is_healthy) {
5453
console.debug('Server health check failed, retrying in 5 seconds...')
55-
// Let the periodic alarm drive the next retry — setTimeout is unreliable in service workers
5654
is_reconnecting = false
5755
return
5856
}
@@ -61,39 +59,46 @@ export const connect_websocket = async (): Promise<void> => {
6159
const version = manifest.version
6260
const user_agent = navigator.userAgent
6361

64-
websocket = new WebSocket(
62+
const ws = new WebSocket(
6563
`ws://localhost:${DEFAULT_PORT}?token=${SECURITY_TOKENS.BROWSERS}&version=${version}&user_agent=${encodeURIComponent(user_agent)}`
6664
)
65+
websocket = ws
6766

68-
websocket.onopen = () => {
67+
ws.onopen = () => {
68+
if (websocket !== ws) return
6969
console.log('Connected with the VS Code!')
7070
is_reconnecting = false
7171
last_ping_timestamp = Date.now()
7272
}
7373

74-
websocket.onmessage = async (event) => {
74+
ws.onmessage = async (event) => {
75+
if (websocket !== ws) return
7576
const message = JSON.parse(event.data)
7677
if (message.action == 'ping') {
7778
last_ping_timestamp = Date.now()
78-
if (websocket?.readyState == WebSocket.OPEN) {
79-
websocket.send(JSON.stringify({ action: 'pong' }))
79+
if (ws.readyState == WebSocket.OPEN) {
80+
ws.send(JSON.stringify({ action: 'pong' }))
8081
}
8182
return
8283
}
8384
console.debug(message)
8485
handle_messages(message as WebSocketMessage)
8586
}
8687

87-
websocket.onclose = () => {
88+
ws.onclose = () => {
8889
console.log('Disconnected from VS Code, attempting to reconnect...')
89-
websocket = null
90+
if (websocket === ws) {
91+
websocket = null
92+
}
9093
is_reconnecting = false
9194
// Reconnect attempt will be driven by the next alarm tick
9295
}
9396

94-
websocket.onerror = () => {
97+
ws.onerror = () => {
98+
if (websocket === ws) {
99+
websocket = null
100+
}
95101
is_reconnecting = false
96-
websocket = null
97102
}
98103
} catch {
99104
is_reconnecting = false

0 commit comments

Comments
 (0)