Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

perf(inbox): warm a notification's issue before it is opened (MUL-9538) (#10893)

Jiayuan Zhang9aadf3701c00
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index 1fef79eece..4575291ab3 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -674,6 +674,32 @@ export function issueTimelineOptions(issueId: string) {
});
}
+/**
+ * Warm what the issue page holds its first paint and a comment landing on: the
+ * issue, its timeline, its runs and its sub-issues, so opening it renders from
+ * cache instead of waiting on a request chain. All four are keyed by UUID and
+ * fetched in parallel; `identifier` mirrors the issue under the key an
+ * identifier URL resolves through (`useCanonicalIssue`), so that hop is cached
+ * too. prefetchQuery honours each query's staleTime: a warm entry costs nothing.
+ */
+export async function prefetchIssuePage(
+ qc: QueryClient,
+ wsId: string,
+ issueId: string,
+ identifier?: string | null,
+): Promise<void> {
+ await Promise.all([
+ qc.prefetchQuery(issueDetailOptions(wsId, issueId)),
+ qc.prefetchQuery(issueTimelineOptions(issueId)),
+ qc.prefetchQuery(issueTasksOptions(issueId)),
+ qc.prefetchQuery(childIssuesOptions(wsId, issueId)),
+ ]);
+ const issue = qc.getQueryData<Issue>(issueKeys.detail(wsId, issueId));
+ if (identifier && issue) {
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, identifier), (old) => old ?? issue);
+ }
+}
+
export function issueCommentThreadOptions(issueId: string, commentId: string) {
return queryOptions({
queryKey: issueKeys.commentThread(issueId, commentId),
diff --git a/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx b/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx
new file mode 100644
index 0000000000..4fa8a1f3d2
--- /dev/null
+++ b/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx
@@ -0,0 +1,74 @@
+import { act, renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { api } from "@multica/core/api";
+import { issueKeys } from "@multica/core/issues/queries";
+import type { InboxItem } from "@multica/core/types";
+import { useInboxIssuePrefetch } from "./use-inbox-issue-prefetch";
+
+const prefetchRoute = vi.fn();
+vi.mock("../../navigation", () => ({ useNavigation: () => ({ prefetch: prefetchRoute }) }));
+vi.mock("@multica/core/api", () => ({
+ api: {
+ getIssue: vi.fn(async (id: string) => ({ id, identifier: `MUL-${id}` })),
+ listTimeline: vi.fn(async () => []),
+ listTasksByIssue: vi.fn(async () => []),
+ listChildIssues: vi.fn(async () => ({ issues: [] })),
+ },
+ ApiError: class extends Error {},
+}));
+
+function row(id: string, read = false): InboxItem {
+ return { id: `n-${id}`, issue_id: id, issue_identifier: `MUL-${id}`, read } as InboxItem;
+}
+
+function setup(rows: InboxItem[]) {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
+ const hook = renderHook(({ items }) => useInboxIssuePrefetch("ws", items, (item) => `/ws/issues/${item.issue_identifier}`), {
+ wrapper, initialProps: { items: rows },
+ });
+ return { qc, hook };
+}
+
+describe("useInboxIssuePrefetch", () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ it("warms the first unread notifications' issues once the list is idle", async () => {
+ const { qc } = setup([row("a"), row("b", true), row("c"), row("d"), row("e")]);
+ expect(api.getIssue).not.toHaveBeenCalled();
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+
+ // Read rows are skipped; three unread issues are warmed, the fourth is left for hover.
+ expect(vi.mocked(api.getIssue).mock.calls.map(([id]) => id)).toEqual(["a", "c", "d"]);
+ expect(vi.mocked(api.listTimeline).mock.calls.map(([id]) => id)).toEqual(["a", "c", "d"]);
+ expect(vi.mocked(api.listTasksByIssue).mock.calls.map(([id]) => id)).toEqual(["a", "c", "d"]);
+ expect(vi.mocked(api.listChildIssues).mock.calls.map(([id]) => id)).toEqual(["a", "c", "d"]);
+ expect(prefetchRoute.mock.calls.map(([href]) => href)).toEqual(["/ws/issues/MUL-a", "/ws/issues/MUL-c", "/ws/issues/MUL-d"]);
+ // An identifier URL resolves from cache too.
+ expect(qc.getQueryData(issueKeys.detail("ws", "MUL-a"))).toEqual({ id: "a", identifier: "MUL-a" });
+ });
+
+ it("warms a pointed-at row on demand, and never fetches a warm issue twice", async () => {
+ const { hook } = setup([row("a")]);
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ await act(async () => { await hook.result.current(row("e", true)); });
+ await act(async () => { await hook.result.current(row("a")); });
+
+ expect(vi.mocked(api.getIssue).mock.calls.map(([id]) => id)).toEqual(["a", "e"]);
+ expect(vi.mocked(api.listTimeline).mock.calls.map(([id]) => id)).toEqual(["a", "e"]);
+ });
+
+ it("does not restart when realtime replaces the same rows", async () => {
+ const { hook } = setup([row("a")]);
+ hook.rerender({ items: [row("a")] });
+ await act(async () => { await vi.advanceTimersByTimeAsync(1000); });
+ expect(api.getIssue).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/views/inbox/components/use-inbox-issue-prefetch.ts b/packages/views/inbox/components/use-inbox-issue-prefetch.ts
new file mode 100644
index 0000000000..87a9073e99
--- /dev/null
+++ b/packages/views/inbox/components/use-inbox-issue-prefetch.ts
@@ -0,0 +1,71 @@
+"use client";
+
+import { useCallback, useEffect, useMemo } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { prefetchIssuePage } from "@multica/core/issues/queries";
+import type { InboxItem } from "@multica/core/types";
+import { useNavigation } from "../../navigation";
+
+/** Unread notifications whose issue is warmed once the list is idle. */
+export const INBOX_IDLE_PREFETCH_LIMIT = 3;
+
+/**
+ * Opening a notification should render from cache, not wait on the issue's
+ * request chain. The first few unread rows are warmed one issue at a time when
+ * the browser is idle; any other row is warmed when it is pointed at or
+ * focused. Returns the per-row warm-up for those events.
+ */
+export function useInboxIssuePrefetch(
+ wsId: string,
+ rows: readonly InboxItem[],
+ hrefOf: (item: InboxItem) => string,
+) {
+ const qc = useQueryClient();
+ const { prefetch: prefetchRoute } = useNavigation();
+
+ const prefetchRow = useCallback(
+ (item: InboxItem) => {
+ if (!wsId || !item.issue_id) return Promise.resolve();
+ return prefetchIssuePage(qc, wsId, item.issue_id, item.issue_identifier).catch(() => {
+ // A failed warm-up is the page's own first request again, retried there.
+ });
+ },
+ [qc, wsId],
+ );
+
+ const idleTargets = useMemo(
+ () => rows.filter((item) => item.issue_id && item.read !== true).slice(0, INBOX_IDLE_PREFETCH_LIMIT),
+ [rows],
+ );
+ // Effect identity follows the issues, not the row objects, which realtime
+ // patches replace on every inbox event.
+ const idleKey = idleTargets.map((item) => item.issue_id).join(",");
+
+ useEffect(() => {
+ if (!idleKey) return;
+ let cancelled = false;
+ const run = async () => {
+ // One issue at a time: each fans out into four requests.
+ for (const item of idleTargets) {
+ if (cancelled) return;
+ prefetchRoute?.(hrefOf(item));
+ await prefetchRow(item);
+ }
+ };
+ if (typeof window.requestIdleCallback === "function") {
+ const id = window.requestIdleCallback(() => void run(), { timeout: 500 });
+ return () => {
+ cancelled = true;
+ window.cancelIdleCallback(id);
+ };
+ }
+ const timer = window.setTimeout(() => void run(), 300);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(timer);
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed by the issues to warm
+ }, [idleKey, wsId]);
+
+ return prefetchRow;
+}
diff --git a/packages/views/layout/panels/inbox-section.tsx b/packages/views/layout/panels/inbox-section.tsx
index 14efa835ee..7dc6066d32 100644
--- a/packages/views/layout/panels/inbox-section.tsx
+++ b/packages/views/layout/panels/inbox-section.tsx
@@ -50,6 +50,7 @@ import { InboxSnoozeMenu } from "../../inbox/components/inbox-snooze-menu";
import { useInboxSnooze } from "../../inbox/components/use-inbox-snooze";
import { useBuiltinViewNavigation } from "../../issue-views/builtin-views";
import { useFilteredInboxRows } from "../../inbox/components/use-filtered-inbox-rows";
+import { useInboxIssuePrefetch } from "../../inbox/components/use-inbox-issue-prefetch";
import { useTimeAgo } from "../../inbox/components/inbox-list-item";
import { useInboxUnsubscribable, useUnsubscribeArchive } from "../../inbox/components/use-unsubscribe-archive";
import {
@@ -168,6 +169,7 @@ export function InboxSection({
const key = inboxRowKey(item);
if (key === openRowKey) leave(key, nextInboxRow(all, key));
};
+ const prefetchRow = useInboxIssuePrefetch(wsId, collapsed ? [] : displayed, (item) => inboxRowHref(p, item));
// What arrived on each issue while it was snoozed, for the rows back from one.
const updatesWhileSnoozed = useMemo(() => {
const counts = new Map<string, number>();
@@ -186,6 +188,7 @@ export function InboxSection({
item={item}
measure={measure}
href={inboxRowHref(p, item)}
+ onPrefetch={() => void prefetchRow(item)}
active={
(!!item.issue_id && item.issue_id === activeIssueId) ||
(!!openKey && (item.issue_id ?? item.id) === openKey)
@@ -508,6 +511,7 @@ function InboxRow({
item,
measure,
href,
+ onPrefetch,
active,
compact,
kept,
@@ -521,6 +525,8 @@ function InboxRow({
/** Set when the row is one of a virtualized list's window. */
measure?: RowMeasure;
href: string;
+ /** Warms the issue this row opens, so the click renders from cache. */
+ onPrefetch: () => void;
active: boolean;
/** One line (status, title, agents, dot or time) instead of the actor line under the title. */
compact: boolean;
@@ -618,6 +624,8 @@ function InboxRow({
data-inbox-row
data-read={unread ? "false" : "true"}
className="group/inbox relative"
+ onPointerEnter={onPrefetch}
+ onFocus={onPrefetch}
>
<HoverCard
open={cardOpen && !snoozeOpen}