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): keep cold community handshake non-blocking (#758)
Gener49661cc03510
diff --git a/src/web/src/hooks/community/community-ws/connection-status.test.ts b/src/web/src/hooks/community/community-ws/connection-status.test.tsindex df2f60e24..cbe76a046 100644--- a/src/web/src/hooks/community/community-ws/connection-status.test.ts+++ b/src/web/src/hooks/community/community-ws/connection-status.test.ts@@ -1,7 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import {COMMUNITY_WS_FAILED_AFTER_MS,- COMMUNITY_WS_RECONNECTING_GRACE_MS,createCommunityWsConnectionStatusController,} from "./connection-status"@@ -19,30 +18,30 @@ describe("community websocket connection status", () => {return { controller, publish, reconnectTransport }}- it("hides a short initial handshake and clears both thresholds on auth", () => {+ it("keeps slow and repeatedly failing initial connection attempts non-blocking", () => {const { controller, publish } = setup()controller.handlePhase("reconnecting")expect(publish).toHaveBeenLastCalledWith("connected")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS - 1)+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS * 2)expect(publish).not.toHaveBeenCalledWith("reconnecting")+ expect(publish).not.toHaveBeenCalledWith("failed")- controller.handlePhase("authenticated")- vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)- expect(publish).toHaveBeenLastCalledWith("connected")+ controller.handlePhase("suspended")+ controller.handlePhase("reconnecting")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS * 2)+ expect(publish.mock.calls.every(([status]) => status === "connected")).toBe(true)expect(publish).not.toHaveBeenCalledWith("failed")})- it("publishes reconnecting after grace and failed after one continuous outage", () => {+ it("records the first authentication without treating its handshake as an outage", () => {const { controller, publish } = setup()controller.handlePhase("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)- expect(publish).toHaveBeenLastCalledWith("reconnecting")-- controller.handlePhase("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - COMMUNITY_WS_RECONNECTING_GRACE_MS)- expect(publish).toHaveBeenLastCalledWith("failed")- expect(publish.mock.calls.filter(([status]) => status === "failed")).toHaveLength(1)+ controller.handlePhase("authenticated")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)+ expect(publish).toHaveBeenLastCalledWith("connected")+ expect(publish).not.toHaveBeenCalledWith("reconnecting")+ expect(publish).not.toHaveBeenCalledWith("failed")})it("publishes reconnecting immediately after a previously authenticated socket drops", () => {@@ -88,19 +87,27 @@ describe("community websocket connection status", () => {it("suspends hidden outages and starts fresh thresholds when visible again", () => {const { controller, publish } = setup()controller.handlePhase("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)+ controller.handlePhase("authenticated")+ publish.mockClear()++ controller.handlePhase("reconnecting")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - 1)controller.handlePhase("suspended")vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)expect(publish).toHaveBeenLastCalledWith("connected")+ expect(publish).not.toHaveBeenCalledWith("failed")controller.handlePhase("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)expect(publish).toHaveBeenLastCalledWith("reconnecting")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)+ expect(publish).toHaveBeenLastCalledWith("failed")})it("manual retry leaves failed immediately, calls one transport retry, and rearms failure", () => {const { controller, publish, reconnectTransport } = setup()controller.handlePhase("reconnecting")+ controller.handlePhase("authenticated")+ controller.handlePhase("reconnecting")vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)expect(publish).toHaveBeenLastCalledWith("failed")@@ -114,6 +121,17 @@ describe("community websocket connection status", () => {expect(reconnectTransport).toHaveBeenCalledOnce()})+ it("keeps a pre-auth manual transport retry non-blocking", () => {+ const { controller, publish, reconnectTransport } = setup()+ controller.handlePhase("reconnecting")++ controller.reconnectNow()+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)++ expect(publish.mock.calls.every(([status]) => status === "connected")).toBe(true)+ expect(reconnectTransport).toHaveBeenCalledOnce()+ })+it("dispose clears timers and ignores callbacks or retries", () => {const { controller, publish, reconnectTransport } = setup()controller.handlePhase("reconnecting")diff --git a/src/web/src/hooks/community/community-ws/connection-status.ts b/src/web/src/hooks/community/community-ws/connection-status.tsindex 832392938..35ee799ad 100644--- a/src/web/src/hooks/community/community-ws/connection-status.ts+++ b/src/web/src/hooks/community/community-ws/connection-status.ts@@ -1,7 +1,6 @@import type { UserWsConnectionPhase } from "@/lib/use-user-ws"import type { CommunityWsConnectionStatus } from "@/stores/community/ws"-export const COMMUNITY_WS_RECONNECTING_GRACE_MS = 1_500export const COMMUNITY_WS_FAILED_AFTER_MS = 30_000export type CommunityWsConnectionStatusController = {@@ -17,16 +16,13 @@ export function createCommunityWsConnectionStatusController({publish: (status: CommunityWsConnectionStatus) => voidreconnectTransport: () => void}): CommunityWsConnectionStatusController {- let reconnectingTimer: ReturnType<typeof setTimeout> | null = nulllet failedTimer: ReturnType<typeof setTimeout> | null = nulllet outageActive = falselet hasAuthenticated = falselet disposed = falseconst clearTimers = () => {- if (reconnectingTimer !== null) clearTimeout(reconnectingTimer)if (failedTimer !== null) clearTimeout(failedTimer)- reconnectingTimer = nullfailedTimer = null}@@ -52,26 +48,24 @@ export function createCommunityWsConnectionStatusController({publish("connected")return}- if (outageActive) return- outageActive = true- if (hasAuthenticated) {- publish("reconnecting")- } else {+ if (!hasAuthenticated) {+ outageActive = false+ clearTimers()publish("connected")- reconnectingTimer = setTimeout(() => {- reconnectingTimer = null- if (!disposed && outageActive) publish("reconnecting")- }, COMMUNITY_WS_RECONNECTING_GRACE_MS)+ return}+ if (outageActive) return+ outageActive = true+ publish("reconnecting")armFailedTimer()}const reconnectNow = () => {if (disposed) return- outageActive = trueclearTimers()- publish("reconnecting")- armFailedTimer()+ outageActive = hasAuthenticated+ publish(hasAuthenticated ? "reconnecting" : "connected")+ if (hasAuthenticated) armFailedTimer()reconnectTransport()}diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex 3ca1263b2..666bb8d8a 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -20,7 +20,6 @@ import {} from "./community-ws/test-harness"import {COMMUNITY_WS_FAILED_AFTER_MS,- COMMUNITY_WS_RECONNECTING_GRACE_MS,} from "./community-ws/connection-status"beforeEach(resetCommunityWsHarness)@@ -124,7 +123,7 @@ describe("useCommunityWs — public helper contracts", () => {})describe("useCommunityWs — connection status publication", () => {- it("publishes the grace, failed, authenticated, and manual retry states from the root", async () => {+ it("keeps cold start non-blocking and publishes only authenticated replacement outages", async () => {vi.useFakeTimers()const { useCommunityWsStore } = await import("@/stores/community/ws")await mountHook()@@ -132,9 +131,15 @@ describe("useCommunityWs — connection status publication", () => {capturedConnectionStateChange!("reconnecting")expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS * 2)+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")++ capturedConnectionStateChange!("authenticated")+ expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")++ capturedConnectionStateChange!("reconnecting")expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - COMMUNITY_WS_RECONNECTING_GRACE_MS)+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)expect(useCommunityWsStore.getState().connectionStatus).toBe("failed")useCommunityWsStore.getState().reconnectNow()@@ -143,26 +148,26 @@ describe("useCommunityWs — connection status publication", () => {capturedConnectionStateChange!("authenticated")expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")-- capturedConnectionStateChange!("reconnecting")- expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")})- it("suspends threshold timers and re-arms on the next visible reconnect", async () => {+ it("suspends an authenticated outage timer and re-arms on the next visible replacement", async () => {vi.useFakeTimers()const { useCommunityWsStore } = await import("@/stores/community/ws")await mountHook()flushEffects()capturedConnectionStateChange!("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)+ capturedConnectionStateChange!("authenticated")+ capturedConnectionStateChange!("reconnecting")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS - 1)capturedConnectionStateChange!("suspended")vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)expect(useCommunityWsStore.getState().connectionStatus).toBe("connected")capturedConnectionStateChange!("reconnecting")- vi.advanceTimersByTime(COMMUNITY_WS_RECONNECTING_GRACE_MS)expect(useCommunityWsStore.getState().connectionStatus).toBe("reconnecting")+ vi.advanceTimersByTime(COMMUNITY_WS_FAILED_AFTER_MS)+ expect(useCommunityWsStore.getState().connectionStatus).toBe("failed")})it("keeps resume validation quiet until transport failure and clears recovery once", async () => {diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex 90fab095f..8c6576713 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -492,6 +492,31 @@ describe("useUserWs", () => {expect(onConnectionStateChange).toHaveBeenLastCalledWith("suspended")})+ it("ignores stale lifecycle events after a replacement authenticates", async () => {+ setupTokenFetch()+ const onConnectionStateChange = vi.fn()+ await mountHook(vi.fn(), {+ onConnectionStateChange,+ requestDaemonStatusOnAuth: false,+ })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })+ first.simulateClose()++ setupTokenFetch()+ await vi.advanceTimersByTimeAsync(2_000)+ const replacement = MockWebSocket.instances.at(-1)!+ replacement.simulateOpen()+ replacement.simulateMessage({ type: "auth.ok" })+ onConnectionStateChange.mockClear()++ first.simulateClose()+ first.simulateMessage({ type: "auth.ok" })++ expect(onConnectionStateChange).not.toHaveBeenCalled()+ })+it("publishes suspended without fetching during a hidden cold start and resumes once visible", async () => {setupTokenFetch()mockDocument.visibilityState = "hidden"diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex 1b631e8e8..f4ecf6a1a 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -1,9 +1,85 @@-import type { WebSocketRoute } from "@playwright/test"+import type { Page, WebSocketRoute } from "@playwright/test"import { test, expect } from "./_fixtures/community-fixture"-import { composerEditable, gotoAfterUserWsAuth } from "./_fixtures/actions"+import {+ composerEditable,+ gotoAfterUserWsAuth,+} from "./_fixtures/actions"import { seedChannel, seedServer } from "./_fixtures/seed"import { tid } from "./_fixtures/testids"+const USER_WS_AUTH_CONSUMED_ATTRIBUTE = "data-e2e-user-ws-auth-consumed"++async function installUserWsAuthConsumedBarrier(page: Page) {+ await page.addInitScript(({ attribute }) => {+ const NativeWebSocket = window.WebSocket+ window.WebSocket = class extends NativeWebSocket {+ constructor(...args: ConstructorParameters<typeof WebSocket>) {+ super(...args)+ if (!new URL(this.url).pathname.endsWith("/user")) return+ this.addEventListener("message", (event) => {+ if (typeof event.data !== "string") return+ try {+ const message = JSON.parse(event.data) as { type?: string }+ if (message.type !== "auth.ok") return+ // The next task runs after the current message event has finished+ // dispatching to the application's WebSocket listener.+ setTimeout(() => {+ document.documentElement.setAttribute(attribute, "true")+ }, 0)+ } catch {}+ })+ }+ }+ }, { attribute: USER_WS_AUTH_CONSUMED_ATTRIBUTE })+}++test("slow auth and an initial retry never block a cold Community page", async ({ asUser }) => {+ test.setTimeout(90_000)+ const serverId = await seedServer("alice", `Reconnect cold start ${Date.now()}`)+ const channelId = await seedChannel("alice", serverId, "reconnect-cold-start")+ const alice = await asUser("alice")+ let tokenRequests = 0+ let releaseTokens!: () => void+ let holdTokens = true+ const tokenGate = new Promise<void>((resolve) => {+ releaseTokens = resolve+ })+ let socketAttempts = 0++ await alice.page.route("**/api/ws/token", async (route) => {+ tokenRequests += 1+ if (holdTokens) await tokenGate+ await route.continue()+ })+ await alice.page.routeWebSocket((url) => url.pathname.endsWith("/user"), (ws) => {+ socketAttempts += 1+ void ws.close({ code: 1012, reason: "cold start auth retry" })+ })+ await alice.page.setViewportSize({ width: 390, height: 844 })++ try {+ await alice.page.goto(`/c/channels/${serverId}/${channelId}`)+ const composer = composerEditable(alice.page)+ const overlay = alice.page.getByTestId(tid.wsReconnectOverlay)+ await expect(composer).toBeVisible({ timeout: 30_000 })+ await expect.poll(() => tokenRequests).toBeGreaterThan(0)+ await alice.page.waitForTimeout(1_600)+ await expect(overlay).toHaveCount(0)+ await composer.fill("Cold start stays usable")+ await expect(composer).toContainText("Cold start stays usable")++ holdTokens = false+ releaseTokens()+ await expect.poll(() => socketAttempts, { timeout: 20_000 }).toBeGreaterThan(1)+ await alice.page.waitForTimeout(1_600)+ await expect(overlay).toHaveCount(0)+ await expect(composer).toContainText("Cold start stays usable")+ } finally {+ holdTokens = false+ releaseTokens()+ }+})+test("real WebSocket outage blocks the whole community surface and Retry restores it", async ({ asUser }, testInfo) => {test.setTimeout(120_000)const serverId = await seedServer("alice", `Reconnect overlay ${Date.now()}`)@@ -141,6 +217,7 @@ test("an active onboarding form yields focus priority during outage, then resume})try {+ await installUserWsAuthConsumedBarrier(page)await page.goto("/sign-in")await page.getByRole("textbox", { name: "Email" }).fill(`guide-reconnect-${process.pid}-${Date.now()}@example.com`,@@ -150,6 +227,11 @@ test("an active onboarding form yields focus priority during outage, then resumeconst onboarding = page.getByRole("dialog")await expect(onboarding).toBeVisible()await expect(onboarding.getByRole("heading", { name: "Which harness do you already use?" })).toBeVisible()+ await expect(page.locator("html")).toHaveAttribute(+ USER_WS_AUTH_CONSUMED_ATTRIBUTE,+ "true",+ { timeout: 20_000 },+ )blockUserWs = trueexpect(userWs).not.toBeNull()diff --git a/src/web/src/test/e2e-ui/_fixtures/actions.ts b/src/web/src/test/e2e-ui/_fixtures/actions.tsindex b141e327c..496de66b8 100644--- a/src/web/src/test/e2e-ui/_fixtures/actions.ts+++ b/src/web/src/test/e2e-ui/_fixtures/actions.ts@@ -3,28 +3,10 @@ import { tid } from "./testids"const HOVER_FINE_QUERY = "(hover: hover) and (pointer: fine)"-export async function installInputCapability(- page: Page,- hoverCapable: boolean,-): Promise<void> {- await page.addInitScript(({ query, matches }) => {- const nativeMatchMedia = window.matchMedia.bind(window)- window.matchMedia = (candidate: string) => candidate === query- ? {- matches,- media: candidate,- onchange: null,- addListener: () => {},- removeListener: () => {},- addEventListener: () => {},- removeEventListener: () => {},- dispatchEvent: () => false,- } as MediaQueryList- : nativeMatchMedia(candidate)- }, { query: HOVER_FINE_QUERY, matches: hoverCapable })-}--export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void> {+export function observeUserWsAuth(page: Page): {+ authenticated: Promise<void>+ cleanup: () => void+} {const frameHandlers = new Map<WebSocket, (event: { payload: string | Buffer }) => void>()let cleanup = () => {}const authenticated = new Promise<void>((resolve, reject) => {@@ -48,11 +30,37 @@ export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void}page.on("websocket", onWebSocket)})+ return { authenticated, cleanup: () => cleanup() }+}++export async function installInputCapability(+ page: Page,+ hoverCapable: boolean,+): Promise<void> {+ await page.addInitScript(({ query, matches }) => {+ const nativeMatchMedia = window.matchMedia.bind(window)+ window.matchMedia = (candidate: string) => candidate === query+ ? {+ matches,+ media: candidate,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => false,+ } as MediaQueryList+ : nativeMatchMedia(candidate)+ }, { query: HOVER_FINE_QUERY, matches: hoverCapable })+}++export async function gotoAfterUserWsAuth(page: Page, url: string): Promise<void> {+ const auth = observeUserWsAuth(page)try {- await Promise.all([page.goto(url, { waitUntil: "commit" }), authenticated])+ await Promise.all([page.goto(url, { waitUntil: "commit" }), auth.authenticated])} finally {- cleanup()+ auth.cleanup()}}