Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: ws leaking

Gusf73c983d76d5
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
index 298d72296..06e5058d9 100644
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
@@ -145,10 +145,6 @@ export default function RuntimesPage() {
const [confirmLoading, setConfirmLoading] = useState(false);
const confirmAction = useRef<(() => Promise<void>) | null>(null);
- useEffect(() => {
- reload();
- }, [reload]);
-
// Auto-open "New machine" sheet when navigated with ?connect
useEffect(() => {
if (searchParams.has("connect")) {
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
new file mode 100644
index 000000000..dc272a3ff
--- /dev/null
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -0,0 +1,250 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import type { WsMessage } from "@alook/shared"
+
+// --- Mock WebSocket ---
+class MockWebSocket {
+ static instances: MockWebSocket[] = []
+ url: string
+ onopen: (() => void) | null = null
+ onmessage: ((e: { data: string }) => void) | null = null
+ onerror: (() => void) | null = null
+ onclose: (() => void) | null = null
+ closed = false
+ sent: string[] = []
+
+ constructor(url: string) {
+ this.url = url
+ MockWebSocket.instances.push(this)
+ }
+ send(data: string) { this.sent.push(data) }
+ close() { this.closed = true; this.onclose?.() }
+
+ // Helpers for tests
+ simulateOpen() { this.onopen?.() }
+ simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }
+ simulateClose() { this.onclose?.() }
+}
+
+vi.stubGlobal("WebSocket", MockWebSocket)
+
+// Mock fetch for /api/ws/token
+const mockFetch = vi.fn()
+vi.stubGlobal("fetch", mockFetch)
+
+// Mock process.env
+vi.stubEnv("NODE_ENV", "development")
+vi.stubEnv("NEXT_PUBLIC_WS_DO_PORT", "8789")
+
+// --- Minimal React hooks mock ---
+// We simulate React's useRef, useCallback, useEffect to test the hook logic directly
+let effectCleanup: (() => void) | null = null
+let refs: Map<string, { current: unknown }> = new Map()
+let refCounter = 0
+let callbackMemo: Map<string, { fn: Function; deps: unknown[] }> = new Map()
+let callbackCounter = 0
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => {
+ const id = `ref-${refCounter++}`
+ if (!refs.has(id)) {
+ refs.set(id, { current: initial })
+ }
+ return refs.get(id)!
+ },
+ useCallback: (fn: Function, deps: unknown[]) => {
+ const id = `cb-${callbackCounter++}`
+ const existing = callbackMemo.get(id)
+ if (existing && JSON.stringify(existing.deps) === JSON.stringify(deps)) {
+ return existing.fn
+ }
+ callbackMemo.set(id, { fn, deps })
+ return fn
+ },
+ useEffect: (fn: () => (() => void) | void, _deps: unknown[]) => {
+ const cleanup = fn()
+ if (cleanup) effectCleanup = cleanup
+ },
+}))
+
+function setupTokenFetch() {
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ userId: "user-1", token: "tok-123" }),
+ })
+}
+
+function resetMockState() {
+ MockWebSocket.instances = []
+ mockFetch.mockReset()
+ effectCleanup = null
+ refs = new Map()
+ refCounter = 0
+ callbackMemo = new Map()
+ callbackCounter = 0
+}
+
+describe("useUserWs", () => {
+ beforeEach(() => {
+ resetMockState()
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ async function mountHook(onMessage: (msg: WsMessage) => void) {
+ // Re-import to get fresh module with fresh mocks
+ const mod = await import("./use-user-ws")
+ mod.useUserWs(onMessage)
+ // Wait for async connect to complete
+ await vi.runAllTimersAsync()
+ return mod
+ }
+
+ it("connect memo is stable — changing onMessage does NOT create a new connect reference", async () => {
+ setupTokenFetch()
+
+ const cb1 = vi.fn()
+ const cb2 = vi.fn()
+
+ // First mount
+ const mod = await import("./use-user-ws")
+
+ // Simulate first render
+ resetMockState()
+ setupTokenFetch()
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useUserWs(cb1)
+ const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
+ const firstConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ // Simulate second render with different callback
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useUserWs(cb2)
+ const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ // connect should be the same reference since deps are []
+ expect(firstConnect).toBe(secondConnect)
+ })
+
+ it("effect cleanup nullifies wsRef.current and calls .close() — subsequent onclose skips reconnect", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ expect(ws).toBeDefined()
+
+ // Run cleanup (simulates React unmount)
+ effectCleanup?.()
+
+ // The WebSocket should be closed
+ expect(ws.closed).toBe(true)
+
+ // No new connections should be created from the onclose handler
+ const instanceCountBefore = MockWebSocket.instances.length
+ // onclose was already called by .close() → but ownership check should skip reconnect
+ await vi.advanceTimersByTimeAsync(5000)
+
+ expect(MockWebSocket.instances.length).toBe(instanceCountBefore)
+ })
+
+ it("onMessageRef.current is updated — ws.onmessage dispatches to latest callback", async () => {
+ setupTokenFetch()
+
+ const cb1 = vi.fn()
+ await mountHook(cb1)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ // Deliver a message — should go to cb1
+ ws.simulateMessage({ type: "test", data: "hello" })
+ expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" })
+
+ // Now simulate a re-render with a new callback by updating the ref directly
+ // In real React, the hook body runs `onMessageRef.current = onMessage` on each render
+ const onMessageRef = Array.from(refs.values()).find(r =>
+ typeof r.current === "function"
+ )
+ const cb2 = vi.fn()
+ if (onMessageRef) onMessageRef.current = cb2
+
+ ws.simulateMessage({ type: "test", data: "world" })
+ expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" })
+ expect(cb1).toHaveBeenCalledTimes(1) // cb1 not called again
+ })
+
+ it("server-initiated close (ws IS current) still triggers reconnect with backoff", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ const instancesBefore = MockWebSocket.instances.length
+
+ // Simulate server-initiated close (ws is still current, not cleaned up by React)
+ ws.onclose?.()
+
+ // Advance past reconnect delay
+ setupTokenFetch()
+ await vi.advanceTimersByTimeAsync(2000)
+
+ // A new connection should have been attempted
+ expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)
+ })
+
+ it("failed connect (fetch rejects) does not leave orphaned timers or break future reconnects", async () => {
+ // First connect fails
+ mockFetch.mockRejectedValue(new Error("network error"))
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg)
+ await vi.runAllTimersAsync()
+
+ // No WebSocket should have been created
+ expect(MockWebSocket.instances.length).toBe(0)
+
+ // Cleanup should not throw
+ expect(() => effectCleanup?.()).not.toThrow()
+ })
+
+ it("effect cleanup clears pending reconnect timer", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook(onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ // Simulate server-initiated close — this schedules a reconnect timer
+ // But we need to call onclose without triggering close() (which would also null wsRef)
+ // Manually trigger the onclose handler
+ const instancesBefore = MockWebSocket.instances.length
+ ws.onclose?.()
+
+ // Now immediately run cleanup (React unmounts before timer fires)
+ effectCleanup?.()
+
+ // Advance past all timers
+ setupTokenFetch()
+ await vi.advanceTimersByTimeAsync(60_000)
+
+ // No new connection should have been created because the timer was cleared
+ expect(MockWebSocket.instances.length).toBe(instancesBefore)
+ })
+})
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index b1f1b7915..44397fb0b 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -10,6 +10,11 @@ const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_M
export function useUserWs(onMessage: (msg: WsMessage) => void) {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
+ const onMessageRef = useRef(onMessage)
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ // Keep the ref in sync with the latest callback on every render
+ onMessageRef.current = onMessage
const connect = useCallback(async () => {
let url: string
@@ -50,21 +55,35 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
try {
const msg = JSON.parse(e.data)
if (msg.type === "auth.ok") return
- onMessage(msg as WsMessage)
+ onMessageRef.current(msg as WsMessage)
} catch {}
}
ws.onerror = () => {}
ws.onclose = () => {
+ // Ownership check: only reconnect if this WS is still the current one.
+ // If effect cleanup already replaced wsRef.current, this is an orphan — skip.
+ if (ws !== wsRef.current) return
+
const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
- setTimeout(connect, delay + Math.random() * 500)
+ reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)
}
- }, [onMessage])
+ }, [])
useEffect(() => {
connect()
- return () => { wsRef.current?.close() }
+ return () => {
+ // Clear any pending reconnect timer first
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current)
+ reconnectTimerRef.current = null
+ }
+ // Nullify wsRef BEFORE closing so the onclose handler's ownership check fails
+ const ws = wsRef.current
+ wsRef.current = null
+ ws?.close()
+ }
}, [connect])
}
diff --git a/src/web/src/lib/use-ws.test.ts b/src/web/src/lib/use-ws.test.ts
new file mode 100644
index 000000000..0946e5c38
--- /dev/null
+++ b/src/web/src/lib/use-ws.test.ts
@@ -0,0 +1,253 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"
+import type { WsMessage } from "@alook/shared"
+
+// --- Mock WebSocket ---
+class MockWebSocket {
+ static instances: MockWebSocket[] = []
+ url: string
+ onopen: (() => void) | null = null
+ onmessage: ((e: { data: string }) => void) | null = null
+ onerror: (() => void) | null = null
+ onclose: (() => void) | null = null
+ closed = false
+ sent: string[] = []
+
+ constructor(url: string) {
+ this.url = url
+ MockWebSocket.instances.push(this)
+ }
+ send(data: string) { this.sent.push(data) }
+ close() { this.closed = true; this.onclose?.() }
+
+ simulateOpen() { this.onopen?.() }
+ simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }
+ simulateClose() { this.onclose?.() }
+}
+
+vi.stubGlobal("WebSocket", MockWebSocket)
+
+const mockFetch = vi.fn()
+vi.stubGlobal("fetch", mockFetch)
+
+vi.stubEnv("NODE_ENV", "development")
+vi.stubEnv("NEXT_PUBLIC_WS_DO_PORT", "8789")
+
+// --- Minimal React hooks mock ---
+let effectCleanup: (() => void) | null = null
+let refs: Map<string, { current: unknown }> = new Map()
+let refCounter = 0
+let callbackMemo: Map<string, { fn: Function; deps: unknown[] }> = new Map()
+let callbackCounter = 0
+
+vi.mock("react", () => ({
+ useRef: (initial: unknown) => {
+ const id = `ref-${refCounter++}`
+ if (!refs.has(id)) {
+ refs.set(id, { current: initial })
+ }
+ return refs.get(id)!
+ },
+ useCallback: (fn: Function, deps: unknown[]) => {
+ const id = `cb-${callbackCounter++}`
+ const existing = callbackMemo.get(id)
+ if (existing && JSON.stringify(existing.deps) === JSON.stringify(deps)) {
+ return existing.fn
+ }
+ callbackMemo.set(id, { fn, deps })
+ return fn
+ },
+ useEffect: (fn: () => (() => void) | void, _deps: unknown[]) => {
+ const cleanup = fn()
+ if (cleanup) effectCleanup = cleanup
+ },
+}))
+
+function setupTokenFetch() {
+ mockFetch.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ token: "tok-456" }),
+ })
+}
+
+function resetMockState() {
+ MockWebSocket.instances = []
+ mockFetch.mockReset()
+ effectCleanup = null
+ refs = new Map()
+ refCounter = 0
+ callbackMemo = new Map()
+ callbackCounter = 0
+}
+
+describe("useAgentWs", () => {
+ beforeEach(() => {
+ resetMockState()
+ vi.useFakeTimers()
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ async function mountHook(agentId: string, onMessage: (msg: WsMessage) => void) {
+ const mod = await import("./use-ws")
+ mod.useAgentWs(agentId, onMessage)
+ await vi.runAllTimersAsync()
+ return mod
+ }
+
+ it("connect depends on [agentId] — changing callback does NOT create new connect", async () => {
+ setupTokenFetch()
+
+ const mod = await import("./use-ws")
+
+ resetMockState()
+ setupTokenFetch()
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useAgentWs("agent-1", vi.fn())
+ const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
+ const firstConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ // Re-render with different callback, same agentId
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useAgentWs("agent-1", vi.fn())
+ const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ expect(firstConnect).toBe(secondConnect)
+ })
+
+ it("connect creates new reference when agentId changes", async () => {
+ setupTokenFetch()
+
+ const mod = await import("./use-ws")
+
+ resetMockState()
+ setupTokenFetch()
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useAgentWs("agent-1", vi.fn())
+ const firstCallbackId = Array.from(callbackMemo.keys()).find(k => k.startsWith("cb-"))
+ const firstConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ // Re-render with different agentId
+ refCounter = 0
+ callbackCounter = 0
+
+ mod.useAgentWs("agent-2", vi.fn())
+ const secondConnect = callbackMemo.get(firstCallbackId!)?.fn
+
+ // Should be different because agentId changed
+ expect(firstConnect).not.toBe(secondConnect)
+ })
+
+ it("effect cleanup nullifies wsRef and calls close — onclose skips reconnect", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook("agent-1", onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ expect(ws).toBeDefined()
+
+ effectCleanup?.()
+
+ expect(ws.closed).toBe(true)
+
+ const instanceCountBefore = MockWebSocket.instances.length
+ await vi.advanceTimersByTimeAsync(5000)
+ expect(MockWebSocket.instances.length).toBe(instanceCountBefore)
+ })
+
+ it("onMessageRef dispatches to latest callback", async () => {
+ setupTokenFetch()
+
+ const cb1 = vi.fn()
+ await mountHook("agent-1", cb1)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ ws.simulateMessage({ type: "test", data: "hello" })
+ expect(cb1).toHaveBeenCalledWith({ type: "test", data: "hello" })
+
+ const onMessageRef = Array.from(refs.values()).find(r =>
+ typeof r.current === "function"
+ )
+ const cb2 = vi.fn()
+ if (onMessageRef) onMessageRef.current = cb2
+
+ ws.simulateMessage({ type: "test", data: "world" })
+ expect(cb2).toHaveBeenCalledWith({ type: "test", data: "world" })
+ expect(cb1).toHaveBeenCalledTimes(1)
+ })
+
+ it("server-initiated close triggers reconnect with backoff", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook("agent-1", onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ const instancesBefore = MockWebSocket.instances.length
+
+ ws.onclose?.()
+
+ setupTokenFetch()
+ await vi.advanceTimersByTimeAsync(2000)
+
+ expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)
+ })
+
+ it("failed connect does not leave orphaned timers", async () => {
+ mockFetch.mockRejectedValue(new Error("network error"))
+
+ const onMsg = vi.fn()
+ await mountHook("agent-1", onMsg)
+ await vi.runAllTimersAsync()
+
+ expect(MockWebSocket.instances.length).toBe(0)
+ expect(() => effectCleanup?.()).not.toThrow()
+ })
+
+ it("effect cleanup clears pending reconnect timer", async () => {
+ setupTokenFetch()
+
+ const onMsg = vi.fn()
+ await mountHook("agent-1", onMsg)
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+
+ const instancesBefore = MockWebSocket.instances.length
+ ws.onclose?.()
+
+ effectCleanup?.()
+
+ setupTokenFetch()
+ await vi.advanceTimersByTimeAsync(60_000)
+
+ expect(MockWebSocket.instances.length).toBe(instancesBefore)
+ })
+
+ it("connects to correct URL with agentId", async () => {
+ setupTokenFetch()
+
+ await mountHook("my-agent-id", vi.fn())
+ await vi.runAllTimersAsync()
+
+ const ws = MockWebSocket.instances[0]
+ expect(ws).toBeDefined()
+ expect(ws.url).toContain("agentId=my-agent-id")
+ })
+})
diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.ts
index 4e920712d..2b8534304 100644
--- a/src/web/src/lib/use-ws.ts
+++ b/src/web/src/lib/use-ws.ts
@@ -10,6 +10,11 @@ const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_M
export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void) {
const wsRef = useRef<WebSocket | null>(null)
const reconnectDelay = useRef(WS_RECONNECT_INIT)
+ const onMessageRef = useRef(onMessage)
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+
+ // Keep the ref in sync with the latest callback on every render
+ onMessageRef.current = onMessage
const connect = useCallback(async () => {
let url: string
@@ -50,21 +55,35 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
try {
const msg = JSON.parse(e.data)
if (msg.type === "auth.ok") return
- onMessage(msg as WsMessage)
+ onMessageRef.current(msg as WsMessage)
} catch {}
}
ws.onerror = () => {}
ws.onclose = () => {
+ // Ownership check: only reconnect if this WS is still the current one.
+ // If effect cleanup already replaced wsRef.current, this is an orphan — skip.
+ if (ws !== wsRef.current) return
+
const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)
reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)
- setTimeout(connect, delay + Math.random() * 500)
+ reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)
}
- }, [agentId, onMessage])
+ }, [agentId])
useEffect(() => {
connect()
- return () => { wsRef.current?.close() }
+ return () => {
+ // Clear any pending reconnect timer first
+ if (reconnectTimerRef.current !== null) {
+ clearTimeout(reconnectTimerRef.current)
+ reconnectTimerRef.current = null
+ }
+ // Nullify wsRef BEFORE closing so the onclose handler's ownership check fails
+ const ws = wsRef.current
+ wsRef.current = null
+ ws?.close()
+ }
}, [connect])
}