⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
fix(ws): retain active queries and recover prolonged outages
Tin7915236bdbc2
diff --git a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsxindex 8cb6bd00b..ca3065078 100644--- a/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx+++ b/apps/web/src/hooks/use-user-websocket-lifecycle.test.tsx@@ -16,12 +16,14 @@ const { client, auth, navigate } = vi.hoisted(() => ({clear: vi.fn(),getQueryCache: () => ({ getAll: () => [] }),removeQueries: vi.fn(),+ resetQueries: vi.fn(),},navigate: vi.fn(),auth: {userId: "user-a" as string | null,workspaceId: "workspace",pathname: "",+ notify: vi.fn(),},}));vi.mock("@tanstack/react-router", () => ({@@ -32,6 +34,7 @@ vi.mock("@tanstack/react-router", () => ({vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => client }));vi.mock("@/lib/auth-client", () => ({authClient: {+ $store: { notify: auth.notify },useSession: () => ({data: auth.userId? {@@ -167,22 +170,33 @@ describe("user WebSocket lifecycle", () => {unmount();expect(vi.getTimerCount()).toBe(0);});- it("retains the five-retry limit and does not duplicate retries on repeated close events", () => {+ it("keeps retrying through long outages with bounded delays and one timer", () => {const { unmount } = renderHook(useUserWebSocket);- for (let retry = 0; retry < 5; retry++) {+ for (const [retry, delay] of [+ 1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000,+ ].entries()) {act(() => {const current = TestSocket.instances.at(-1);current?.onclose?.();current?.onclose?.();- vi.advanceTimersByTime(1000 * 2 ** retry);+ vi.advanceTimersByTime(delay - 1);});+ expect(TestSocket.instances).toHaveLength(retry + 1);+ expect(vi.getTimerCount()).toBe(1);+ act(() => vi.advanceTimersByTime(1));expect(TestSocket.instances).toHaveLength(retry + 2);}act(() => {- TestSocket.instances.at(-1)?.onclose?.();- vi.advanceTimersByTime(60_000);+ const socket = TestSocket.instances.at(-1)!;+ socket.open();+ socket.onmessage?.({+ data: JSON.stringify({+ type: "WORKSPACE_ACCESS_SYNC",+ workspaceIds: [],+ }),+ });});- expect(TestSocket.instances).toHaveLength(6);+ expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });unmount();expect(vi.getTimerCount()).toBe(0);});@@ -199,6 +213,9 @@ describe("user WebSocket lifecycle", () => {});expect(navigate).not.toHaveBeenCalled();expect(client.removeQueries).toHaveBeenCalledOnce();+ expect(auth.notify).toHaveBeenCalledWith("$listOrg");+ expect(auth.notify).toHaveBeenCalledWith("$activeOrgSignal");+ expect(auth.notify).toHaveBeenCalledWith("$sessionSignal");});it("redirects after a reconnect snapshot reveals a missed workspace revocation", () => {@@ -213,5 +230,7 @@ describe("user WebSocket lifecycle", () => {);expect(navigate).toHaveBeenCalledWith({ to: "/dashboard" });expect(client.removeQueries).toHaveBeenCalledOnce();+ expect(auth.notify).toHaveBeenCalledWith("$listOrg");+ expect(auth.notify).toHaveBeenCalledWith("$activeOrgSignal");});});diff --git a/apps/web/src/hooks/use-user-websocket.ts b/apps/web/src/hooks/use-user-websocket.tsindex a8047ba82..f96817a84 100644--- a/apps/web/src/hooks/use-user-websocket.ts+++ b/apps/web/src/hooks/use-user-websocket.ts@@ -15,7 +15,7 @@ export function getUserWsUrl() {return `${wsBase}/user?windowId=${encodeURIComponent(windowId)}`;}-const MAX_RETRIES = 5;+const MAX_RETRY_DELAY = 30_000;const BASE_DELAY = 1000;const WS_PING_INTERVAL_MS = 30_000;@@ -39,7 +39,7 @@ export function useUserWebSocket() {// A previous session's delayed socket events must not control this session.let disposed = false;let activeSocket: WebSocket | null = null;- let retries = 0;+ let retryDelay = BASE_DELAY;let retryTimeout: ReturnType<typeof setTimeout> | null = null;let pingInterval: ReturnType<typeof setInterval> | null = null;@@ -50,6 +50,16 @@ export function useUserWebSocket() {}}+ function refreshOrganizationState() {+ for (const signal of [+ "$listOrg",+ "$activeOrgSignal",+ "$activeMemberRoleSignal",+ "$sessionSignal",+ ])+ authClient.$store.notify(signal);+ }+function connect() {if (disposed) return;retryTimeout = null;@@ -59,7 +69,7 @@ export function useUserWebSocket() {ws.onopen = () => {if (disposed || activeSocket !== ws) return;- retries = 0;+ retryDelay = BASE_DELAY;clearPing();pingInterval = setInterval(() => {if (ws.readyState === WebSocket.OPEN) {@@ -82,6 +92,7 @@ export function useUserWebSocket() {message.workspaceIds.every((id) => typeof id === "string")) {evictInaccessibleWorkspaceCache(queryClient, message.workspaceIds);+ refreshOrganizationState();const path = pathnameRef.current;const current =/^\/dashboard\/settings\/(workspace|projects)(\/|$)/.test(path)@@ -95,6 +106,7 @@ export function useUserWebSocket() {message.workspaceId) {evictWorkspaceCache(queryClient, message.workspaceId);+ refreshOrganizationState();const path = pathnameRef.current;const current =/^\/dashboard\/settings\/(workspace|projects)(\/|$)/.test(path)@@ -116,11 +128,9 @@ export function useUserWebSocket() {clearPing();activeSocket = null;- if (retries < MAX_RETRIES) {- const delay = BASE_DELAY * 2 ** retries;- retries += 1;- retryTimeout = setTimeout(connect, delay);- }+ const delay = retryDelay;+ retryDelay = Math.min(retryDelay * 2, MAX_RETRY_DELAY);+ retryTimeout = setTimeout(connect, delay);};}diff --git a/apps/web/src/lib/evict-workspace-cache.test.ts b/apps/web/src/lib/evict-workspace-cache.test.tsindex bbc3f573a..3e7e8d6b9 100644--- a/apps/web/src/lib/evict-workspace-cache.test.ts+++ b/apps/web/src/lib/evict-workspace-cache.test.ts@@ -1,4 +1,4 @@-import { QueryClient } from "@tanstack/react-query";+import { QueryClient, QueryObserver } from "@tanstack/react-query";import { expect, it } from "vite-plus/test";import {evictInaccessibleWorkspaceCache,@@ -88,3 +88,38 @@ it("reconciles missed revocations against a reconnect access snapshot", () => {).toBeUndefined();client.clear();});++it("refetches an active board whose pending read has no workspace scope yet", async () => {+ const client = new QueryClient();+ const board = {+ id: "project",+ workspaceId: "active",+ columns: [{ tasks: [{ id: "task", title: "Still visible" }] }],+ };+ let finishOld!: (value: unknown) => void;+ let reads = 0;+ const options = {+ queryKey: ["tasks", "project"],+ staleTime: Infinity,+ retry: false,+ queryFn: () => {+ reads++;+ return reads === 1+ ? new Promise<unknown>((resolve) => {+ finishOld = resolve;+ })+ : Promise.resolve(board);+ },+ };+ const observer = new QueryObserver(client, options);+ const unsubscribe = observer.subscribe(() => {});+ expect(reads).toBe(1);+ evictInaccessibleWorkspaceCache(client, ["active"]);+ finishOld({ workspaceId: "revoked", description: "private" });+ await client.fetchQuery(options);+ expect(reads).toBe(2);+ expect(observer.getCurrentResult().data).toEqual(board);+ expect(client.getQueryData(options.queryKey)).toEqual(board);+ unsubscribe();+ client.clear();+});diff --git a/apps/web/src/lib/evict-workspace-cache.ts b/apps/web/src/lib/evict-workspace-cache.tsindex 0b3d209e7..0ae2336a5 100644--- a/apps/web/src/lib/evict-workspace-cache.ts+++ b/apps/web/src/lib/evict-workspace-cache.ts@@ -18,7 +18,9 @@ function evictPrivateQueries() {const queries = client.getQueryCache().getAll();const ids = new Set<string>(workspaceId ? [workspaceId] : []);- const scopes = new Map<string, string>();+ const scopes = new Map<string, string>(+ Array.from(allowed ?? [], (id) => [id, id]),+ );const visit = (value: unknown,callback: (record: Record<string, unknown>) => void,@@ -138,5 +140,12 @@ function evictPrivateQueries();};void client.cancelQueries({ predicate });- client.removeQueries({ predicate });+ // Keep active observers attached: removing their query can strand a board+ // opened concurrently with the access snapshot. Reset and refetch instead.+ client.removeQueries({+ predicate: (query) => predicate(query) && !query.isActive(),+ });+ void client.resetQueries({+ predicate: (query) => predicate(query) && query.isActive(),+ });}