Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): harden WS broadcast and reconnect after CLI register
Genere51369c9ab46
diff --git a/src/web/src/app/api/conversations/[id]/messages/route.test.ts b/src/web/src/app/api/conversations/[id]/messages/route.test.tsindex 909501f35..f1b95a553 100644--- a/src/web/src/app/api/conversations/[id]/messages/route.test.ts+++ b/src/web/src/app/api/conversations/[id]/messages/route.test.ts@@ -12,19 +12,24 @@ const mockTaskToResponse = vi.fn((t: any) => ({ id: t.id, status: t.status }));vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),}));-vi.mock("@alook/shared", () => ({- createDb: vi.fn(() => ({})),- queries: {- conversation: {- getConversation: (...args: any[]) => mockGetConversation(...args),- updateConversationTitle: (...args: any[]) => mockUpdateConversationTitle(...args),- },- message: {- listMessages: (...args: any[]) => mockListMessages(...args),- createMessage: (...args: any[]) => mockCreateMessage(...args),+vi.mock("@alook/shared", () => {+ const noop = () => {};+ const log = { debug: noop, info: noop, warn: noop, error: noop, child: () => log };+ return {+ createDb: vi.fn(() => ({})),+ createLogger: () => log,+ queries: {+ conversation: {+ getConversation: (...args: any[]) => mockGetConversation(...args),+ updateConversationTitle: (...args: any[]) => mockUpdateConversationTitle(...args),+ },+ message: {+ listMessages: (...args: any[]) => mockListMessages(...args),+ createMessage: (...args: any[]) => mockCreateMessage(...args),+ },},- },-}));+ };+});vi.mock("@/lib/middleware/auth", () => ({withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex 948edbfef..62e9279b7 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -1,10 +1,12 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { createDb, queries, ActivateTokenRequestSchema } from "@alook/shared";+import { createDb, queries, ActivateTokenRequestSchema, createLogger } from "@alook/shared";import { writeJSON } from "@/lib/middleware/helpers";import { runtimeToResponse } from "@/lib/api/responses";import { broadcastToUser } from "@/lib/broadcast";+const log = createLogger({ service: "machine-tokens/activate" });+export async function POST(req: NextRequest) {let raw: unknown;try {@@ -61,12 +63,20 @@ export async function POST(req: NextRequest) {await queries.machineToken.activateMachineToken(db, mt.id);// Notify the web UI- broadcastToUser(mt.userId, {- type: "runtime.registered",- daemonId,- hostname,- workspaceId: mt.workspaceId,- }).catch(() => {});+ try {+ await broadcastToUser(mt.userId, {+ type: "runtime.registered",+ daemonId,+ hostname,+ workspaceId: mt.workspaceId,+ });+ } catch (err) {+ log.warn("broadcast after activation failed", {+ userId: mt.userId,+ daemonId,+ err: err instanceof Error ? err.message : String(err),+ });+ }return writeJSON({daemon_id: daemonId,diff --git a/src/web/src/lib/broadcast.ts b/src/web/src/lib/broadcast.tsindex 5a20d5b45..11efd0f8a 100644--- a/src/web/src/lib/broadcast.ts+++ b/src/web/src/lib/broadcast.ts@@ -1,6 +1,8 @@import { getCloudflareContext } from "@opennextjs/cloudflare"import type { WsMessage } from "@alook/shared"-import { DEV_WS_DO_URL } from "@alook/shared"+import { DEV_WS_DO_URL, createLogger } from "@alook/shared"++const log = createLogger({ service: "broadcast" })export async function broadcastToUser(userId: string, message: WsMessage) {const body = JSON.stringify(message)@@ -16,11 +18,14 @@ export async function broadcastToUser(userId: string, message: WsMessage) {body,})} catch {- await fetch(`${DEV_WS_DO_URL}${url}`, {+ const res = await fetch(`${DEV_WS_DO_URL}${url}`, {method: "POST",headers: { "Content-Type": "application/json" },body,})+ if (!res.ok) {+ log.warn("broadcast fallback failed", { userId, status: res.status, type: message.type })+ }}}@@ -36,10 +41,13 @@ export async function broadcastToAgent(agentId: string, message: WsMessage) {body,})} catch {- await fetch(`${DEV_WS_DO_URL}${url}`, {+ const res = await fetch(`${DEV_WS_DO_URL}${url}`, {method: "POST",headers: { "Content-Type": "application/json" },body,})+ if (!res.ok) {+ log.warn("broadcast fallback failed", { agentId, status: res.status, type: message.type })+ }}}diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex dc272a3ff..cd4e69579 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -206,19 +206,29 @@ describe("useUserWs", () => {expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)})- it("failed connect (fetch rejects) does not leave orphaned timers or break future reconnects", async () => {- // First connect fails+ it("failed connect (fetch rejects) retries with backoff and cleanup prevents further reconnects", async () => {+ // All connects will failmockFetch.mockRejectedValue(new Error("network error"))const onMsg = vi.fn()- await mountHook(onMsg)- await vi.runAllTimersAsync()+ // Mount without runAllTimersAsync to avoid infinite reconnect loop+ const mod = await import("./use-user-ws")+ mod.useUserWs(onMsg)+ // Let initial connect resolve (microtask) + advance past one reconnect+ await vi.advanceTimersByTimeAsync(2000)- // No WebSocket should have been created+ // No WebSocket should have been created (fetch keeps failing)expect(MockWebSocket.instances.length).toBe(0)+ // Fetch was retried at least once via the reconnect timer+ expect(mockFetch.mock.calls.length).toBeGreaterThan(1)- // Cleanup should not throw+ // Cleanup should clear the pending reconnect timer and not throwexpect(() => effectCleanup?.()).not.toThrow()++ // After cleanup, no further reconnect attempts should happen+ const callsAfterCleanup = mockFetch.mock.calls.length+ await vi.advanceTimersByTimeAsync(60_000)+ expect(mockFetch.mock.calls.length).toBe(callsAfterCleanup)})it("effect cleanup clears pending reconnect timer", async () => {diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 7528af8f0..ff7e8719d 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -16,22 +16,28 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {// Keep the ref in sync with the latest callback on every renderonMessageRef.current = onMessage+ const scheduleReconnect = useCallback((connect: () => void) => {+ const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)+ reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)+ reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)+ }, [])+const connect = useCallback(async () => {- // Unified flow for dev and prod:- // 1. Fetch /api/ws/token over HTTP (cookie-authenticated Next.js route).- // 2. Open WebSocket with ?userId= and authenticate via {type:"auth",token}.- // The custom OpenNext wrapper (src/web/custom-worker.ts) forwards /api/ws/*- // upgrade requests directly to the ws-do worker in prod; in dev we connect- // to the ws-do worker on localhost directly.let userId: stringlet authToken: stringtry {const res = await fetch("/api/ws/token")- if (!res.ok) return+ if (!res.ok) {+ console.warn("[ws] token fetch failed:", res.status)+ scheduleReconnect(connect)+ return+ }const body = await res.json() as { userId: string; token: string }userId = body.userIdauthToken = body.token- } catch {+ } catch (err) {+ console.warn("[ws] token fetch error:", err)+ scheduleReconnect(connect)return}@@ -42,7 +48,9 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {let ws: WebSockettry {ws = new WebSocket(url)- } catch {+ } catch (err) {+ console.warn("[ws] WebSocket creation failed:", err)+ scheduleReconnect(connect)return}wsRef.current = ws@@ -66,12 +74,9 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {// 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)- reconnectTimerRef.current = setTimeout(connect, delay + Math.random() * 500)+ scheduleReconnect(connect)}- }, [])+ }, [scheduleReconnect])useEffect(() => {connect()