Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8758 BOYF-670 fix(core): recover pending invitations on focus and reconnect (#10115)
沙雕的小鱼儿 boyfeiyubf768883a8bf
diff --git a/packages/core/realtime/use-realtime-sync-invitations.test.tsx b/packages/core/realtime/use-realtime-sync-invitations.test.tsxindex 689c0e4362..d3783ebb5d 100644--- a/packages/core/realtime/use-realtime-sync-invitations.test.tsx+++ b/packages/core/realtime/use-realtime-sync-invitations.test.tsx@@ -27,11 +27,10 @@ afterEach(() => {vi.restoreAllMocks();});-// Global QueryClient defaults are staleTime: Infinity + no focus refetch, so-// the pending-invitations list only moves when something invalidates it. The-// invitation:accepted / invitation:declined handlers must include it: the+// Realtime invalidation must refresh even a fresh pending-invitations list.+// The invitation:accepted / invitation:declined handlers must include it: the// accepting client may have concluded the invite from another surface, and-// its own stale sidebar row otherwise survives until restart.+// its list must update without waiting for a later focus/online fallback.it.each(["invitation:accepted", "invitation:declined"] as const)("refreshes the pending-invitations list on %s when the actor is the current user",async (event) => {@@ -137,8 +136,8 @@ it.each(["invitation:accepted", "invitation:declined"] as const)(});renderHook(() => useRealtimeSync(ws, stores), { wrapper: Wrapper });try {- // Cache hit + staleTime: Infinity: the list mounts fresh and never- // fetches, so any call after the event means a (wrong) invalidation.+ // The cache is fresh: any call after this non-actor event means a+ // (wrong) invalidation rather than normal focus/online recovery.await waitFor(() => expect(page.result.current.data).toEqual([]));expect(listMyInvitations).not.toHaveBeenCalled();diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex d4fc13aa07..2002d6c651 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -2,7 +2,7 @@* @vitest-environment jsdom*/import { QueryClient, QueryClientProvider, QueryObserver, type InvalidateQueryFilters, type QueryKey } from "@tanstack/react-query";-import { cleanup, renderHook, waitFor } from "@testing-library/react";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";import type { ReactNode } from "react";import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";import type { WSClient } from "../api/ws-client";@@ -12,7 +12,7 @@ import { issueKeys } from "../issues/queries";import { chatKeys } from "../chat/queries";import { runtimeKeys } from "../runtimes/queries";import { agentTasksKeys, workspaceWorkingAgentsKeys } from "../agents/queries";-import { workspaceKeys } from "../workspace/queries";+import { myInvitationListOptions, workspaceKeys } from "../workspace/queries";import { issueStatusKeys } from "../issue-statuses/queries";import { issueWorkflowKeys } from "../issue-workflows/queries";import { issueViewKeys } from "../issue-views/queries";@@ -23,7 +23,7 @@ import {} from "../workspace/pending-delete";import { setApiInstance } from "../api";import type { ApiClient } from "../api/client";-import type { AgentTask, IssueTableQuerySpec } from "../types";+import type { AgentTask, Invitation, IssueTableQuerySpec } from "../types";import { getCurrentWsId } from "../platform/workspace-storage";import { forgetLocalSearchIndex } from "../search-index/instance";import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";@@ -134,12 +134,12 @@ describe("useRealtimeSync — ws instance change", () => {// and view preferences] + 6 per-issue prefixes + the workspace// working-agents projection + 5 per-chat prefixes + 1 workspaceKeys.list()// + 1 cross-workspace inbox unread summary + 1 issue unread marks + 1- // subscribed issue ids = 36 calls).+ // subscribed issue ids + 1 account invitation list = 37 calls).//// Awaited rather than counted synchronously: the inbox unread summary// refresh cancels any in-flight request before invalidating (see// onInboxSummaryInvalidate), so that one lands after the synchronous ones.- await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(36));+ await waitFor(() => expect(invalidateSpy).toHaveBeenCalledTimes(37));});it("does not re-invalidate when rerendered with the same ws instance", () => {@@ -173,6 +173,7 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(["chat", "ws-1"]);expect(calls).toContainEqual(["labels", "ws-1"]);expect(calls).toContainEqual(["workspaces", "ws-1", "invitations"]);+ expect(calls).toContainEqual(workspaceKeys.myInvitations());// A catalog edit made while this client was disconnected is otherwise// invisible for the query's whole 5-minute staleTime.expect(calls).toContainEqual(issueStatusKeys.all("ws-1"));@@ -412,6 +413,54 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(chatKeys.pendingTaskAll());});+ it.each(["ws-1", null])(+ "refreshes fresh account invitations on WebSocket reconnect with current workspace %s",+ async (wsId) => {+ vi.mocked(getCurrentWsId).mockReturnValue(wsId);+ const invitation: Invitation = {+ id: "concluded-invitation",+ workspace_id: "ws-2",+ inviter_id: "u2",+ invitee_email: "[email protected]",+ invitee_user_id: "u1",+ role: "member",+ status: "pending",+ created_at: "",+ updated_at: "",+ expires_at: "",+ };+ let rows = [invitation];+ const listMyInvitations = vi.fn(async () => rows);+ setApiInstance({ listMyInvitations } as unknown as ApiClient);+ const observer = new QueryObserver(qc, myInvitationListOptions());+ const unsubscribe = observer.subscribe(() => {});+ const ws = createMockWs();+ const hook = renderHook(() => useRealtimeSync(ws, stores), {+ wrapper: createWrapper(qc),+ });++ try {+ await waitFor(() => expect(observer.getCurrentResult().data).toEqual(rows));+ expect(listMyInvitations).toHaveBeenCalledTimes(1);+ expect(observer.getCurrentResult().isStale).toBe(false);++ rows = [{ ...invitation, id: "new-pending-invitation" }];+ const reconnect = vi.mocked(ws.onReconnect).mock.calls[0]?.[0];+ expect(reconnect).toBeDefined();+ // Only the socket reconnects: no focus, visibility, or online event.+ await act(async () => { reconnect!(); });++ await waitFor(() => expect(observer.getCurrentResult().data).toEqual(rows));+ expect(listMyInvitations).toHaveBeenCalledTimes(2);+ } finally {+ hook.unmount();+ unsubscribe();+ qc.clear();+ vi.mocked(getCurrentWsId).mockReturnValue("ws-1");+ }+ },+ );+it("invalidates one issue attachment cache after detached channel media binds", () => {const ws = createMockWs();renderHook(() => useRealtimeSync(ws, stores), {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex d0a732a027..687f02a7a9 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -646,7 +646,7 @@ export async function handleInboxNew(}/**- * Invalidates all workspace-scoped queries. Used after reconnect and when a+ * Invalidates workspace and account caches. Used after reconnect and when a* new WSClient instance is detected (workspace switch) to recover events* missed while disconnected.*/@@ -686,6 +686,9 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {// Cross-workspace, so outside the wsId guard: a reconnect may have missed// inbox events from any workspace, so re-pull the switcher-dot summary.void onInboxSummaryInvalidate(qc);+ // Account invitations can change while only the socket is disconnected,+ // with no browser focus or online event to trigger the fallback refetch.+ qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });// Per-issue caches are keyed without wsId, so the issueKeys.all(wsId)// prefix above does not reach them. They rely entirely on WS events for// freshness (staleTime: Infinity), so events missed while disconnected@@ -1490,11 +1493,10 @@ export function useRealtimeSync(// The workspace broadcast reaches every online member, so the admin lists// refresh unconditionally. The account-level pending list is gated on the// acting user: only the invitee who concluded the invite (possibly from- // another surface or device) needs their stale pending row dropped —- // staleTime is Infinity, so nothing refetches it on its own. Without the- // gate every accept/decline fanout refetches the list once per online- // member. The actor rides the frame envelope (ws-client hands it to the- // handler as its second argument), not the event payload.+ // another surface or device) needs an immediate refresh even while its+ // cached list is fresh. Without the gate every accept/decline fanout+ // refetches the list once per online member. The actor arrives in the frame+ // envelope (the handler's second argument), not the event payload.const unsubInvitationAccepted = ws.on("invitation:accepted",(_payload, actorId) => {diff --git a/packages/core/workspace/invitation-recovery.test.tsx b/packages/core/workspace/invitation-recovery.test.tsxnew file mode 100644index 0000000000..16d2e3e7e1--- /dev/null+++ b/packages/core/workspace/invitation-recovery.test.tsx@@ -0,0 +1,131 @@+// @vitest-environment jsdom+import { createElement, type ReactNode } from "react";+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider, useQuery } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setApiInstance, type ApiClient } from "../api";+import { createQueryClient } from "../query-client";+import type { Invitation } from "../types";+import { myInvitationListOptions, workspaceListOptions } from "./queries";++const clients: ReturnType<typeof createQueryClient>[] = [];+let now: number;++beforeEach(() => {+ now = Date.UTC(2026, 10, 8);+ vi.spyOn(Date, "now").mockImplementation(() => now);+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");+});++afterEach(() => {+ cleanup();+ for (const client of clients.splice(0)) client.clear();+ window.dispatchEvent(new Event("online"));+ vi.restoreAllMocks();+});++function invitation(id: string): Invitation {+ return {+ id,+ workspace_id: `workspace-${id}`,+ inviter_id: "inviter",+ invitee_email: "[email protected]",+ invitee_user_id: "current-user",+ role: "member",+ status: "pending",+ created_at: "",+ updated_at: "",+ expires_at: "",+ };+}++async function mountList() {+ let rows = [invitation("old")];+ const listMyInvitations = vi.fn(async () => rows);+ const listWorkspaces = vi.fn(async () => []);+ setApiInstance({ listMyInvitations, listWorkspaces } as unknown as ApiClient);+ const client = createQueryClient();+ clients.push(client);+ const hook = renderHook(+ () => ({+ invitations: useQuery(myInvitationListOptions()),+ workspaces: useQuery(workspaceListOptions()),+ }),+ {+ wrapper: ({ children }: { children: ReactNode }) =>+ createElement(QueryClientProvider, { client }, children),+ },+ );+ await waitFor(() => {+ expect(hook.result.current.invitations.data).toEqual(rows);+ expect(hook.result.current.workspaces.isSuccess).toBe(true);+ });+ return {+ hook,+ listMyInvitations,+ listWorkspaces,+ changeRemote: () => { rows = [invitation("new")]; },+ };+}++async function recover(event: "visibilitychange" | "online") {+ await act(async () => {+ if (event === "online") window.dispatchEvent(new Event("offline"));+ window.dispatchEvent(new Event(event));+ // QueryClient forwards the browser event asynchronously through its managers.+ await new Promise((resolve) => setTimeout(resolve, 20));+ });+}++describe("account invitation recovery", () => {+ it("keeps fresh reads across repeated visibility and network recovery", async () => {+ const list = await mountList();+ list.changeRemote();+ now += 29_000;+ for (let i = 0; i < 3; i++) {+ await recover("visibilitychange");+ await recover("online");+ }+ expect(list.listMyInvitations).toHaveBeenCalledTimes(1);+ expect(list.hook.result.current.invitations.data?.[0]?.id).toBe("old");+ });++ it.each(["visibilitychange", "online"] as const)(+ "reconciles a successfully cached list on an eligible %s without refreshing workspace data",+ async (event) => {+ const list = await mountList();+ list.changeRemote();+ now += 31_000;+ expect(list.listMyInvitations).toHaveBeenCalledTimes(1);+ await recover(event);+ await waitFor(() =>+ expect(list.hook.result.current.invitations.data?.[0]?.id).toBe("new"),+ );+ expect(list.listMyInvitations).toHaveBeenCalledTimes(2);+ expect(list.listWorkspaces).toHaveBeenCalledTimes(1);+ await recover("visibilitychange");+ await recover("online");+ expect(list.listMyInvitations).toHaveBeenCalledTimes(2);+ },+ );++ it("retries a transient recovery read, then reconciles on the next online event", async () => {+ const list = await mountList();+ list.changeRemote();+ now += 31_000;+ list.listMyInvitations+ .mockRejectedValueOnce(new Error("temporary read failure"))+ .mockRejectedValueOnce(new Error("temporary read failure"));+ await recover("visibilitychange");+ await waitFor(() => expect(list.hook.result.current.invitations.isError).toBe(true), {+ timeout: 3_000,+ });+ expect(list.listMyInvitations).toHaveBeenCalledTimes(3);+ await recover("online");+ await waitFor(() =>+ expect(list.hook.result.current.invitations.data?.[0]?.id).toBe("new"),+ );+ expect(list.hook.result.current.invitations.isSuccess).toBe(true);+ expect(list.listMyInvitations).toHaveBeenCalledTimes(4);+ });+});diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex b539f89ec9..4c7de686c6 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -205,6 +205,9 @@ export function myInvitationListOptions() {return queryOptions({queryKey: workspaceKeys.myInvitations(),queryFn: () => api.listMyInvitations(),+ // Recover missed realtime events without refetching on every tab switch.+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,});}