Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7890 perf(inbox): fetch the unread summary only while the page is visible (#9085)
Ray Walker3f657e29cf6c
diff --git a/packages/core/inbox/queries.ts b/packages/core/inbox/queries.tsindex 8f58a74fe4..290389b6c8 100644--- a/packages/core/inbox/queries.ts+++ b/packages/core/inbox/queries.ts@@ -4,6 +4,7 @@ import { EMPTY_INBOX_FILTERS, type ArchivedInboxFilters } from "./filter-store";import { infiniteQueryOptions, queryOptions, useQuery } from "@tanstack/react-query";import { api } from "../api";import type { InboxItem, InboxWorkspaceUnread } from "../types";+import { focusManager } from "@tanstack/react-query";export const inboxKeys = {all: (wsId: string) => ["inbox", wsId] as const,@@ -90,14 +91,40 @@ export function patchArchivedInboxCaches(qc: QueryClient, wsId: string, patch: (* Cross-workspace unread inbox summary. One cache entry shared across all* workspaces — the data is account-level, so switching workspaces does not* refetch it; only the derived "is this for another workspace" view changes.+ *+ * Visibility gating is the default, including for direct observers such as+ * the search palette. `refetchOnWindowFocus` re-reads an invalidated summary+ * once when the page is shown again; with `staleTime: Infinity` a page that+ * missed no event is not stale and makes no request. The dock badge overrides+ * `enabled` through `inboxUnreadSummaryEnabled` to stay live while hidden.*/export function inboxUnreadSummaryOptions() {return queryOptions({queryKey: inboxKeys.unreadSummary(),queryFn: () => api.getInboxUnreadSummary(),+ enabled: () => focusManager.isFocused(),+ refetchOnWindowFocus: true,});}+/**+ * `enabled` for an observer of the unread summary: fetch only while the page+ * is on screen. Every open tab is its own client and receives every inbox+ * event, so each event cost one summary request per open tab, and each request+ * recomputes the newest item per issue over the user's whole active inbox. A+ * hidden tab renders nothing that reads the summary, and with no enabled+ * observer left an invalidation marks the query without refetching it.+ *+ * `whileHidden` is for a reader that stays on screen while the page is hidden:+ * the desktop dock badge of a minimized window.+ */+export function inboxUnreadSummaryEnabled(+ wsId: string | null | undefined,+ { whileHidden = false }: { whileHidden?: boolean } = {},+) {+ return () => !!wsId && (whileHidden || focusManager.isFocused());+}+/*** Whether any workspace OTHER than `currentWsId` has unread inbox items.* Drives the workspace-switcher dot: the active workspace's own unread is@@ -149,10 +176,13 @@ export function unreadCountForWorkspace(* endpoint applies the same newest-per-issue rule `deduplicateInboxItems`* applies client-side, so this number matches the list the user sees.*/-export function useInboxUnreadCount(wsId: string | null | undefined): number {+export function useInboxUnreadCount(+ wsId: string | null | undefined,+ options?: { whileHidden?: boolean },+): number {const { data } = useQuery({...inboxUnreadSummaryOptions(),- enabled: !!wsId,+ enabled: inboxUnreadSummaryEnabled(wsId, options),select: (summary: InboxWorkspaceUnread[]) =>unreadCountForWorkspace(summary, wsId),});diff --git a/packages/core/inbox/unread-summary-visibility.test.tsx b/packages/core/inbox/unread-summary-visibility.test.tsxnew file mode 100644index 0000000000..69f31f423f--- /dev/null+++ b/packages/core/inbox/unread-summary-visibility.test.tsx@@ -0,0 +1,145 @@+/** @vitest-environment jsdom */+import { act, cleanup, renderHook, waitFor } from "@testing-library/react";+import { QueryClientProvider, focusManager, useQuery } from "@tanstack/react-query";+import type { ReactNode } from "react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { setApiInstance } from "../api";+import type { ApiClient } from "../api/client";+import { createQueryClient } from "../query-client";+import type { InboxWorkspaceUnread } from "../types";+import { inboxUnreadSummaryOptions, useInboxUnreadCount } from "./queries";+import { onInboxSummaryInvalidate } from "./ws-updaters";++/**+ * Every open tab is its own client and receives every inbox event. Before this+ * gate each event cost one summary request per open tab, hidden ones included,+ * and each request recomputes the newest item per issue over the user's whole+ * active inbox.+ */++const WS = "ws-1";+let unread = 1;+const getInboxUnreadSummary = vi.fn(+ async (): Promise<InboxWorkspaceUnread[]> => [{ workspace_id: WS, count: unread }],+);++beforeEach(() => {+ unread = 1;+ getInboxUnreadSummary.mockClear();+ setApiInstance({ getInboxUnreadSummary } as unknown as ApiClient);+});++afterEach(() => {+ cleanup();+ focusManager.setFocused(undefined);+});++function setup() {+ const qc = createQueryClient();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const view = renderHook(() => useInboxUnreadCount(WS), { wrapper });+ return { qc, view };+}++async function setPageVisible(visible: boolean) {+ await act(async () => {+ focusManager.setFocused(visible);+ });+}++async function inboxEvent(qc: ReturnType<typeof createQueryClient>) {+ unread += 1;+ await act(async () => {+ await onInboxSummaryInvalidate(qc);+ });+}++it("refetches on every inbox event while the page is visible", async () => {+ const { qc, view } = setup();+ await waitFor(() => expect(view.result.current).toBe(1));++ await inboxEvent(qc);+ await waitFor(() => expect(view.result.current).toBe(2));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);+});++it("a hidden page defers every inbox event to one request when it is shown", async () => {+ const { qc, view } = setup();+ await waitFor(() => expect(view.result.current).toBe(1));+ await setPageVisible(false);++ await inboxEvent(qc);+ await inboxEvent(qc);+ await inboxEvent(qc);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);++ await setPageVisible(true);+ await waitFor(() => expect(view.result.current).toBe(4));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);+});++it("a page shown again after no inbox event makes no request", async () => {+ const { view } = setup();+ await waitFor(() => expect(view.result.current).toBe(1));++ await setPageVisible(false);+ await setPageVisible(true);++ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+});++it("a default summary observer defers hidden events alongside the sidebar reader", async () => {+ const qc = createQueryClient();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const view = renderHook(() => ({+ sidebar: useInboxUnreadCount(WS),+ summary: useQuery(inboxUnreadSummaryOptions()).data,+ }), { wrapper });+ await waitFor(() => expect(view.result.current.sidebar).toBe(1));+ await setPageVisible(false);++ await inboxEvent(qc);+ await inboxEvent(qc);+ await inboxEvent(qc);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);++ await setPageVisible(true);+ await waitFor(() => expect(view.result.current.sidebar).toBe(4));+ expect(view.result.current.summary).toEqual([{ workspace_id: WS, count: 4 }]);+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);+});++it("a page opened hidden fetches the summary when it is first shown", async () => {+ await setPageVisible(false);+ const { view } = setup();+ expect(getInboxUnreadSummary).not.toHaveBeenCalled();++ await setPageVisible(true);+ await waitFor(() => expect(view.result.current).toBe(1));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+});++it("whileHidden keeps the summary live on a hidden page, as the dock badge needs", async () => {+ // Desktop mounts both: the sidebar's gated reader and the dock badge.+ const qc = createQueryClient();+ const wrapper = ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={qc}>{children}</QueryClientProvider>+ );+ const view = renderHook(+ () => ({+ sidebar: useInboxUnreadCount(WS),+ dock: useInboxUnreadCount(WS, { whileHidden: true }),+ }),+ { wrapper },+ );+ await waitFor(() => expect(view.result.current.dock).toBe(1));+ await setPageVisible(false);++ await inboxEvent(qc);+ await waitFor(() => expect(view.result.current.dock).toBe(2));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);+});diff --git a/packages/core/inbox/ws-updaters.ts b/packages/core/inbox/ws-updaters.tsindex 4236e775e5..6c6cccd7da 100644--- a/packages/core/inbox/ws-updaters.ts+++ b/packages/core/inbox/ws-updaters.ts@@ -124,8 +124,8 @@ export function onInboxIssueStatusChanged(// summary rather than these lists, so the summary is refreshed here too. It// has to happen inside this updater and not at the call site: deletion is an// `issue:*` event, so no `inbox:*` handler runs to pick it up, and the summary-// query is `staleTime: Infinity` with no refetch on focus — nothing else would-// ever correct it, leaving the badge stuck above an empty inbox (MUL-6967).+// query is `staleTime: Infinity`, re-read only once invalidated — nothing else+// would ever correct it, leaving the badge stuck above an empty inbox (MUL-6967).export async function onInboxIssueDeleted(qc: QueryClient,wsId: string,diff --git a/packages/views/layout/app-sidebar.test.tsx b/packages/views/layout/app-sidebar.test.tsxindex f3ac633b45..c4d308c3d9 100644--- a/packages/views/layout/app-sidebar.test.tsx+++ b/packages/views/layout/app-sidebar.test.tsx@@ -166,6 +166,7 @@ vi.mock("@multica/core/api", async (importOriginal) => {});vi.mock("@multica/core/inbox/queries", () => ({inboxUnreadSummaryOptions: () => ({ queryKey: ["inbox", "unread-summary"] }),+ inboxUnreadSummaryEnabled: (wsId: string | null) => () => !!wsId,// The nav badge and the switcher dot read the SAME cross-workspace summary,// so the fixture that drives one drives the other.useInboxUnreadCount: (currentWsId: string | null) =>diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex b1fc58bb79..c5d8963f2c 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -68,7 +68,7 @@ import { useCurrentWorkspace, useWorkspacePaths, paths } from "@multica/core/patimport { workspaceListOptions, myInvitationListOptions, workspaceKeys } from "@multica/core/workspace/queries";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";-import { inboxUnreadSummaryOptions, useInboxUnreadCount, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";+import { inboxUnreadSummaryEnabled, inboxUnreadSummaryOptions, useInboxUnreadCount, hasOtherWorkspaceUnread, unreadWorkspaceIds } from "@multica/core/inbox/queries";import { chatSessionsOptions } from "@multica/core/chat/queries";import { countUnreadChatMessages } from "@multica/core/chat/unread";import { useChatStore } from "@multica/core/chat";@@ -495,7 +495,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }// the endpoint resolves through the workspace-member middleware.const { data: unreadSummary = EMPTY_INBOX_SUMMARY } = useQuery({...inboxUnreadSummaryOptions(),- enabled: !!wsId,+ enabled: inboxUnreadSummaryEnabled(wsId),});const otherWorkspaceUnread = React.useMemo(() => hasOtherWorkspaceUnread(unreadSummary, wsId),diff --git a/packages/views/platform/use-desktop-unread-badge.ts b/packages/views/platform/use-desktop-unread-badge.tsindex 91801390e9..1852b71b5b 100644--- a/packages/views/platform/use-desktop-unread-badge.ts+++ b/packages/views/platform/use-desktop-unread-badge.ts@@ -13,10 +13,11 @@ function getDesktopAPI(): BadgeCapableAPI | undefined {/*** Mirror the inbox unread count onto the OS dock/taskbar badge. No-op on web* (no `desktopAPI`) and on the login screen (no workspace ⇒ count defaults- * to 0, which clears any stale badge from a previous session).+ * to 0, which clears any stale badge from a previous session). The badge is+ * on screen while the window is minimized, so it keeps the summary live then.*/export function useDesktopUnreadBadge(wsId: string | null | undefined): void {- const count = useInboxUnreadCount(wsId);+ const count = useInboxUnreadCount(wsId, { whileHidden: true });useEffect(() => {getDesktopAPI()?.setUnreadBadge?.(count);}, [count]);diff --git a/packages/views/search/search-command.visibility.test.tsx b/packages/views/search/search-command.visibility.test.tsxnew file mode 100644index 0000000000..3e732e5131--- /dev/null+++ b/packages/views/search/search-command.visibility.test.tsx@@ -0,0 +1,91 @@+import { act, cleanup, render, screen, waitFor } from "@testing-library/react";+import { QueryClientProvider, focusManager } from "@tanstack/react-query";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { I18nProvider } from "@multica/core/i18n/react";+import { buildIssueStatusCatalog } from "@multica/core/issue-statuses/queries";+import { useInboxUnreadCount } from "@multica/core/inbox/queries";+import { onInboxSummaryInvalidate } from "@multica/core/inbox/ws-updaters";+import { createQueryClient } from "@multica/core/query-client";+import { SearchCommand } from "./search-command";+import { useSearchStore } from "./search-store";+import enSearch from "../locales/en/search.json";+import enLayout from "../locales/en/layout.json";+import enProjects from "../locales/en/projects.json";++const { getInboxUnreadSummary } = vi.hoisted(() => ({+ getInboxUnreadSummary: vi.fn(),+}));++vi.mock("@multica/core/api", () => ({+ api: {+ getBaseUrl: () => "http://localhost",+ getInboxUnreadSummary,+ listWorkspaces: async () => [],+ listMembers: async () => [],+ },+}));++vi.mock("@multica/core", () => ({ useWorkspaceId: () => "ws-1" }));+vi.mock("@multica/core/issue-statuses/hooks", () => ({+ useIssueStatuses: () => buildIssueStatusCatalog([]),+}));+vi.mock("@multica/core/paths", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@multica/core/paths")>();+ return { ...actual, useWorkspacePaths: () => actual.paths.workspace("ws-test") };+});+vi.mock("../navigation/context", () => {+ const adapter = () => ({+ push: vi.fn(),+ pathname: "/ws-test/issues",+ getShareableUrl: (path: string) => path,+ });+ return { useNavigation: adapter, useOptionalNavigation: adapter };+});+vi.mock("@multica/ui/components/common/theme-provider", () => ({+ useTheme: () => ({ theme: "system", setTheme: vi.fn() }),+}));++function SidebarCount() {+ const count = useInboxUnreadCount("ws-1");+ return <output aria-label="Inbox unread count">{count}</output>;+}++beforeEach(() => {+ getInboxUnreadSummary.mockReset().mockResolvedValue([{ workspace_id: "ws-1", count: 1 }]);+ useSearchStore.setState({ open: false });+ focusManager.setFocused(true);+});++afterEach(() => {+ cleanup();+ focusManager.setFocused(undefined);+});++it("a closed, mounted search palette defers hidden inbox events alongside the sidebar", async () => {+ const qc = createQueryClient();+ const view = render(+ <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={{ en: { search: enSearch, layout: enLayout, projects: enProjects } }}>+ <SidebarCount />+ <SearchCommand />+ </I18nProvider>+ </QueryClientProvider>,+ );+ await waitFor(() => expect(screen.getByLabelText("Inbox unread count")).toHaveTextContent("1"));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();++ await act(async () => { focusManager.setFocused(false); });+ getInboxUnreadSummary.mockResolvedValue([{ workspace_id: "ws-1", count: 4 }]);+ await act(async () => {+ for (let i = 0; i < 3; i++) await onInboxSummaryInvalidate(qc);+ });+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(1);++ await act(async () => { focusManager.setFocused(true); });+ await waitFor(() => expect(screen.getByLabelText("Inbox unread count")).toHaveTextContent("4"));+ expect(getInboxUnreadSummary).toHaveBeenCalledTimes(2);++ view.unmount();+ qc.clear();+});