Skip to content

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

Go

perf(issues): open an issue from a list without waiting on its route (MUL-9798) (#11146)

Jiayuan Zhangc9b0445513c1
diff --git a/packages/core/issues/queries.test.ts b/packages/core/issues/queries.test.ts
index aeaef5a78c..83838d19de 100644
--- a/packages/core/issues/queries.test.ts
+++ b/packages/core/issues/queries.test.ts
@@ -20,11 +20,13 @@ import {
PROJECT_GANTT_PAGE_LIMIT,
childrenByParentsOptions,
childIssuesOptions,
+ fetchIssueByRef,
flattenIssueBuckets,
issueIdentifierOptions,
issueKeys,
issueListOptions,
issueTableRowPageOptions,
+ prefetchIssuePage,
projectGanttIssuesOptions,
sidebarIssuesOptions,
sourceContextPreviewOptions,
@@ -751,3 +753,27 @@ describe("sidebarIssuesOptions", () => {
]);
});
});
+
+describe("prefetchIssuePage", () => {
+ it("shares one issue request with a link warming the same issue by its identifier", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
+ const issue = makeIssue(7);
+ const getIssue = vi.fn().mockResolvedValue(issue);
+ setApiInstance({
+ getIssue,
+ listTimeline: vi.fn().mockResolvedValue([]),
+ listTasksByIssue: vi.fn().mockResolvedValue([]),
+ listChildIssues: vi.fn().mockResolvedValue({ issues: [] }),
+ } as unknown as ApiClient);
+
+ await Promise.all([
+ prefetchIssuePage(qc, WS_ID, issue.id, issue.identifier),
+ fetchIssueByRef(qc, WS_ID, issue.identifier),
+ ]);
+
+ expect(getIssue).toHaveBeenCalledTimes(1);
+ expect(getIssue.mock.calls[0]?.[0]).toBe("MUL-7");
+ expect(qc.getQueryData(issueKeys.detail(WS_ID, "MUL-7"))).toBe(issue);
+ expect(qc.getQueryData(issueKeys.detail(WS_ID, issue.id))).toBe(issue);
+ });
+});
diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.ts
index 4575291ab3..ff1674bb35 100644
--- a/packages/core/issues/queries.ts
+++ b/packages/core/issues/queries.ts
@@ -674,13 +674,27 @@ export function issueTimelineOptions(issueId: string) {
});
}
+/**
+ * The issue a link names by UUID or identifier, also cached under its UUID,
+ * the key the issue page reads it by once an identifier URL has resolved
+ * through the identifier-keyed entry (`useCanonicalIssue`).
+ */
+export async function fetchIssueByRef(qc: QueryClient, wsId: string, ref: string): Promise<Issue> {
+ const issue = await qc.fetchQuery(issueDetailOptions(wsId, ref));
+ if (issue.id !== ref) {
+ qc.setQueryData<Issue>(issueKeys.detail(wsId, issue.id), (old) => old ?? issue);
+ }
+ return issue;
+}
+
/**
* 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.
+ * cache instead of waiting on a request chain. All four are fetched in
+ * parallel. With an `identifier`, the issue is fetched under the key an
+ * identifier URL resolves through and mirrored to its UUID, so a link to that
+ * URL warming the same issue shares the request. prefetchQuery honours each
+ * query's staleTime: a warm entry costs nothing.
*/
export async function prefetchIssuePage(
qc: QueryClient,
@@ -689,15 +703,13 @@ export async function prefetchIssuePage(
identifier?: string | null,
): Promise<void> {
await Promise.all([
- qc.prefetchQuery(issueDetailOptions(wsId, issueId)),
+ identifier
+ ? fetchIssueByRef(qc, wsId, identifier).catch(() => undefined)
+ : 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) {
diff --git a/packages/views/docs/components/use-prefetch-doc.ts b/packages/views/docs/components/use-prefetch-doc.ts
index 1917c27428..bf02f73bdd 100644
--- a/packages/views/docs/components/use-prefetch-doc.ts
+++ b/packages/views/docs/components/use-prefetch-doc.ts
@@ -6,38 +6,16 @@ import { useAuthStore } from "@multica/core/auth";
import { useWorkspaceId } from "@multica/core/hooks";
import { useWorkspacePaths } from "@multica/core/paths";
import { useWS } from "@multica/core/realtime";
-import { useNavigation } from "../../navigation";
+import { useWarmRoute } from "../../navigation";
import { findDocSession, liveEditingOff, prefetchDocLive } from "./doc-live-session";
/** A pointer passing over a list is not heading for every row in it. */
const HOVER_INTENT_MS = 80;
-let docPageWarmed = false;
-
-/**
- * Prefetches one doc's route once per session when the browser is idle. On
- * web the doc page's code is shared by every doc but only requested after a
- * doc's route payload arrives, which put a whole round trip in front of the
- * first doc opened; warming it here leaves each open with just its payload.
- * Desktop bundles its routes and has no route prefetch, so this is a no-op.
- */
+/** Loads the doc page's code before the first doc is opened (see `useWarmRoute`). */
export function useWarmDocPage(docId: string | undefined) {
- const { prefetch } = useNavigation();
const p = useWorkspacePaths();
- const href = docId ? p.docDetail(docId) : null;
- useEffect(() => {
- if (!href || !prefetch || docPageWarmed) return;
- const warm = () => {
- docPageWarmed = true;
- prefetch(href);
- };
- if (typeof window.requestIdleCallback === "function") {
- const id = window.requestIdleCallback(warm, { timeout: 3000 });
- return () => window.cancelIdleCallback(id);
- }
- const timer = window.setTimeout(warm, 1500);
- return () => window.clearTimeout(timer);
- }, [href, prefetch]);
+ useWarmRoute("doc", docId ? p.docDetail(docId) : null);
}
/**
diff --git a/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx b/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx
index 4fa8a1f3d2..9e9ff7a3c9 100644
--- a/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx
+++ b/packages/views/inbox/components/use-inbox-issue-prefetch.test.tsx
@@ -11,7 +11,10 @@ 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}` })),
+ getIssue: vi.fn(async (ref: string) => {
+ const id = ref.replace(/^MUL-/, "");
+ return { id, identifier: `MUL-${id}` };
+ }),
listTimeline: vi.fn(async () => []),
listTasksByIssue: vi.fn(async () => []),
listChildIssues: vi.fn(async () => ({ issues: [] })),
@@ -46,13 +49,15 @@ describe("useInboxIssuePrefetch", () => {
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"]);
+ // By identifier, the key a link to the issue warms too, so the two share a request.
+ expect(vi.mocked(api.getIssue).mock.calls.map(([id]) => id)).toEqual(["MUL-a", "MUL-c", "MUL-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.
+ // An identifier URL resolves from cache, and the page reads the issue by UUID.
expect(qc.getQueryData(issueKeys.detail("ws", "MUL-a"))).toEqual({ id: "a", identifier: "MUL-a" });
+ expect(qc.getQueryData(issueKeys.detail("ws", "a"))).toEqual({ id: "a", identifier: "MUL-a" });
});
it("warms a pointed-at row on demand, and never fetches a warm issue twice", async () => {
@@ -61,7 +66,7 @@ describe("useInboxIssuePrefetch", () => {
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.getIssue).mock.calls.map(([id]) => id)).toEqual(["MUL-a", "MUL-e"]);
expect(vi.mocked(api.listTimeline).mock.calls.map(([id]) => id)).toEqual(["a", "e"]);
});
diff --git a/packages/views/issues/components/board-card-peek.test.tsx b/packages/views/issues/components/board-card-peek.test.tsx
index 7084228bba..38d5d84611 100644
--- a/packages/views/issues/components/board-card-peek.test.tsx
+++ b/packages/views/issues/components/board-card-peek.test.tsx
@@ -138,7 +138,7 @@ describe("DraggableBoardCard side peek", () => {
it("still navigates on a plain click", () => {
renderCard();
fireEvent.click(link());
- expect(navigation.push).toHaveBeenCalledWith("/acme/issues/issue-1");
+ expect(navigation.push).toHaveBeenCalledWith("/acme/issues/MUL-1");
expect(peek.toggle).not.toHaveBeenCalled();
});
@@ -167,7 +167,7 @@ describe("DraggableBoardCard side peek", () => {
expect(navigation.push).not.toHaveBeenCalled();
act(() => useIssueOpeningStore.getState().setOpenMode("page"));
fireEvent.click(link());
- expect(navigation.push).toHaveBeenCalledWith("/acme/issues/issue-1");
+ expect(navigation.push).toHaveBeenCalledWith("/acme/issues/MUL-1");
});
it("opens the full page in place on Shift+Click when the preference is peek", () => {
@@ -184,7 +184,7 @@ describe("DraggableBoardCard side peek", () => {
useIssueOpeningStore.getState().setOpenMode("peek");
renderCard({ withPeek: false });
fireEvent.click(link());
- expect(navigation.push).toHaveBeenCalledWith("/acme/issues/issue-1");
+ expect(navigation.push).toHaveBeenCalledWith("/acme/issues/MUL-1");
expect(peek.open).not.toHaveBeenCalled();
});
diff --git a/packages/views/issues/components/board-card.tsx b/packages/views/issues/components/board-card.tsx
index 4da1437ae7..9c0ca2bd8d 100644
--- a/packages/views/issues/components/board-card.tsx
+++ b/packages/views/issues/components/board-card.tsx
@@ -420,7 +420,7 @@ export const DraggableBoardCard = memo(function DraggableBoardCard({
}
>
<AppLink
- href={p.issueDetail(issue.id)}
+ href={p.issueDetail(issue.identifier)}
newTabTitle={issue.identifier}
className={`group block transition-colors ${isDragging ? "pointer-events-none" : ""}`}
{...peekLinkProps}
diff --git a/packages/views/issues/components/gantt-view.tsx b/packages/views/issues/components/gantt-view.tsx
index d2057abb52..426bf7f293 100644
--- a/packages/views/issues/components/gantt-view.tsx
+++ b/packages/views/issues/components/gantt-view.tsx
@@ -369,7 +369,7 @@ function ScheduledRow({
{/* Sticky label cell — it also carries the peeked mark, since its
opaque background covers the row's own. */}
<AppLink
- href={p.issueDetail(issue.id)}
+ href={p.issueDetail(issue.identifier)}
newTabTitle={issue.identifier}
className={cn(
"sticky left-0 z-[1] flex shrink-0 items-center gap-2 border-r bg-background px-3 text-body min-w-0",
@@ -411,7 +411,7 @@ function ScheduledRow({
<TooltipTrigger
render={
<AppLink
- href={p.issueDetail(issue.id)}
+ href={p.issueDetail(issue.identifier)}
newTabTitle={issue.identifier}
{...peekLinkProps}
className={cn(
diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsx
index 3b09ccf764..07807791a9 100644
--- a/packages/views/issues/components/issues-page.test.tsx
+++ b/packages/views/issues/components/issues-page.test.tsx
@@ -45,6 +45,7 @@ vi.mock("@multica/core/paths", async () => {
// Mock @multica/views/navigation (AppLink + useNavigation)
vi.mock("../../navigation", () => ({
+ useWarmRoute: () => undefined,
AppLink: ({ children, href, ...props }: any) => (
<a href={href} {...props}>
{children}
diff --git a/packages/views/issues/components/list-row-peek.test.tsx b/packages/views/issues/components/list-row-peek.test.tsx
index ddf4bc6366..c33279143e 100644
--- a/packages/views/issues/components/list-row-peek.test.tsx
+++ b/packages/views/issues/components/list-row-peek.test.tsx
@@ -104,7 +104,7 @@ describe("ListRow side peek", () => {
expect(navigation.push).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("link"));
- expect(navigation.push).toHaveBeenCalledWith("/acme/issues/issue-1");
+ expect(navigation.push).toHaveBeenCalledWith("/acme/issues/MUL-1");
});
it("opens on a plain click when side preview is preferred", () => {
diff --git a/packages/views/issues/components/list-row.tsx b/packages/views/issues/components/list-row.tsx
index f937d7c2ea..f4871afaae 100644
--- a/packages/views/issues/components/list-row.tsx
+++ b/packages/views/issues/components/list-row.tsx
@@ -138,7 +138,7 @@ function ListRowContent({
/>
</div>
<AppLink
- href={p.issueDetail(issue.id)}
+ href={p.issueDetail(issue.identifier)}
newTabTitle={issue.identifier}
className={`flex flex-1 items-center gap-2 min-w-0 ${isDragging ? "pointer-events-none" : ""}`}
{...peekLinkProps}
diff --git a/packages/views/issues/components/table-view-editing.test.tsx b/packages/views/issues/components/table-view-editing.test.tsx
index de92d66333..bbcf280a12 100644
--- a/packages/views/issues/components/table-view-editing.test.tsx
+++ b/packages/views/issues/components/table-view-editing.test.tsx
@@ -478,7 +478,7 @@ describe("TableView cell editors under data refresh", () => {
expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
expect(peek.toggle).not.toHaveBeenCalled();
fireEvent.click(row, { metaKey: true });
- expect(navigationMocks.openInNewTab).toHaveBeenCalledWith("/test/issues/a", "MUL-a");
+ expect(navigationMocks.openInNewTab).toHaveBeenCalledWith("/test/issues/MUL-a", "MUL-a");
expect(peek.open).toHaveBeenCalledTimes(2);
});
@@ -499,25 +499,25 @@ describe("TableView cell editors under data refresh", () => {
const title = within(row).getByRole("button", { name: "Alpha task" });
await user.click(title);
- expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/MUL-a");
expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
navigationMocks.push.mockClear();
await user.click(row);
- expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/MUL-a");
expect(navigationMocks.openInNewTab).not.toHaveBeenCalled();
navigationMocks.push.mockClear();
fireEvent.click(title, { metaKey: true });
expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
- "/test/issues/a",
+ "/test/issues/MUL-a",
"MUL-a",
);
navigationMocks.openInNewTab.mockClear();
fireEvent.click(row, { metaKey: true, shiftKey: true });
expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
- "/test/issues/a",
+ "/test/issues/MUL-a",
"MUL-a",
{ activate: true },
);
@@ -554,7 +554,7 @@ describe("TableView cell editors under data refresh", () => {
// Dead space on the row still opens a background tab on middle click.
auxClick(row);
expect(navigationMocks.openInNewTab).toHaveBeenCalledWith(
- "/test/issues/a",
+ "/test/issues/MUL-a",
"MUL-a",
);
});
@@ -579,15 +579,15 @@ describe("TableView cell editors under data refresh", () => {
const title = within(row).getByRole("button", { name: "Alpha task" });
await user.click(title);
- expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/a");
+ expect(navigationMocks.push).toHaveBeenCalledWith("/test/issues/MUL-a");
expect(windowOpen).not.toHaveBeenCalled();
fireEvent.click(title, { metaKey: true });
expect(navigationMocks.getShareableUrl).toHaveBeenCalledWith(
- "/test/issues/a",
+ "/test/issues/MUL-a",
);
expect(windowOpen).toHaveBeenCalledWith(
- "https://app.example/test/issues/a",
+ "https://app.example/test/issues/MUL-a",
"_blank",
"noopener,noreferrer",
);
diff --git a/packages/views/issues/components/table-view.tsx b/packages/views/issues/components/table-view.tsx
index a0b95d10bc..bec843abe2 100644
--- a/packages/views/issues/components/table-view.tsx
+++ b/packages/views/issues/components/table-view.tsx
@@ -2233,7 +2233,7 @@ export function TableView({
// middle clicks open tabs. Callbacks without an event (keyboard
// affordances) count as plain clicks.
intentNavigate(
- paths.issueDetail(issue.id),
+ paths.issueDetail(issue.identifier),
event ? resolveClickIntent(event) : "push",
issue.identifier,
);
diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsx
index 590fe1fbd0..510080b08e 100644
--- a/packages/views/issues/surface/issue-surface.test.tsx
+++ b/packages/views/issues/surface/issue-surface.test.tsx
@@ -90,6 +90,7 @@ vi.mock("../../i18n", () => ({
}));
vi.mock("../../navigation", () => ({
+ useWarmRoute: () => undefined,
AppLink: ({ children, href, ...props }: React.ComponentProps<"a">) => (
<a href={href} {...props}>
{children}
diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsx
index c9753ad3f4..24129b5b41 100644
--- a/packages/views/issues/surface/issue-surface.tsx
+++ b/packages/views/issues/surface/issue-surface.tsx
@@ -9,6 +9,7 @@ import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceId } from "@multica/core/hooks";
+import { useWorkspacePaths } from "@multica/core/paths";
import { useModalStore } from "@multica/core/modals";
import { useIsGuest } from "@multica/core/permissions";
import { useQuery } from "@tanstack/react-query";
@@ -46,6 +47,7 @@ import { SwimLaneView } from "../components/swimlane-view";
import { TableView } from "../components/table-view";
import { useT } from "../../i18n";
import { CollectionPageState } from "../../layout/collection-page";
+import { useWarmRoute } from "../../navigation";
import { IssueContextMenuProvider } from "../actions";
import { IssueSurfaceActionsProvider } from "./actions-context";
import { IssuePeekHost } from "../components/issue-peek";
@@ -252,6 +254,7 @@ function IssueSurfaceContent({
// One polling owner for the whole surface; individual cards only select cache data.
useQuery({ ...workspaceWakeupSummariesOptions(workspaceId), refetchInterval: 10_000 });
const { t } = useT("projects");
+ const paths = useWorkspacePaths();
const controller = useIssueSurfaceController({
scope,
modes,
@@ -277,6 +280,8 @@ function IssueSurfaceContent({
: controller.issues,
[clientFilter, controller.issues],
);
+ const firstIssue = issues[0] ?? tableLoadedIssues[0];
+ useWarmRoute("issue", firstIssue ? paths.issueDetail(firstIssue.identifier) : null);
const swimlaneIssues = useMemo(
() =>
clientFilter
diff --git a/packages/views/layout/panels/sidebar-tree.test.tsx b/packages/views/layout/panels/sidebar-tree.test.tsx
index 874dea56d8..f13f93123f 100644
--- a/packages/views/layout/panels/sidebar-tree.test.tsx
+++ b/packages/views/layout/panels/sidebar-tree.test.tsx
@@ -47,6 +47,7 @@ vi.mock("@multica/core/issue-statuses/hooks", () => ({
useIssueStatuses: () => buildIssueStatusCatalog([]),
}));
vi.mock("../../navigation", () => ({
+ useWarmRoute: () => undefined,
AppLink: ({
children,
href,
@@ -79,7 +80,7 @@ const PARAMS: SidebarIssuesRequest = {
},
};
const issues = (count: number): Issue[] =>
- Array.from({ length: count }, (_, i) => ({ id: `issue-${i + 1}`, title: `Issue ${i + 1}`, status: "todo" }) as Issue);
+ Array.from({ length: count }, (_, i) => ({ id: `issue-${i + 1}`, identifier: `MUL-${i + 1}`, title: `Issue ${i + 1}`, status: "todo" }) as Issue);
function renderList({
total = 18,
@@ -131,11 +132,11 @@ describe("SidebarIssueList", () => {
],
});
expect(rows().map((row) => row.getAttribute("href"))).toEqual([
- "/acme/issues/issue-1#comment-comment-1",
- "/acme/issues/issue-2",
- "/acme/issues/issue-3#comment-task-3",
- "/acme/issues/issue-4",
- "/acme/issues/issue-5",
+ "/acme/issues/MUL-1#comment-comment-1",
+ "/acme/issues/MUL-2",
+ "/acme/issues/MUL-3#comment-task-3",
+ "/acme/issues/MUL-4",
+ "/acme/issues/MUL-5",
]);
});
@@ -246,6 +247,6 @@ describe("sidebar title disclosure", () => {
vi.useRealTimers();
}
expect(document.querySelector("[data-slot=tooltip-content]")).toBeNull();
- expect(link).toHaveAttribute("href", "/acme/issues/issue-1");
+ expect(link).toHaveAttribute("href", "/acme/issues/MUL-1");
});
});
diff --git a/packages/views/layout/panels/sidebar-tree.tsx b/packages/views/layout/panels/sidebar-tree.tsx
index d5c433e40c..79571bc35a 100644
--- a/packages/views/layout/panels/sidebar-tree.tsx
+++ b/packages/views/layout/panels/sidebar-tree.tsx
@@ -19,7 +19,7 @@ import { issueUnreadTarget, useIssueUnread } from "@multica/core/issues/unread";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import type { AgentTask, Issue, IssueUnread } from "@multica/core/types";
-import { AppLink } from "../../navigation";
+import { AppLink, useWarmRoute } from "../../navigation";
import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";
import { StatusIcon } from "../../issues/components/status-icon";
import { StatusPicker } from "../../issues/components/pickers/status-picker";
@@ -343,6 +343,7 @@ export function SidebarIssueList({
placeholderData: keepPreviousData,
});
const listed = params ? (query.data?.issues ?? EMPTY_ISSUES) : EMPTY_ISSUES;
+ useWarmRoute("issue", listed[0] ? p.issueDetail(listed[0].identifier) : null);
const total = params ? (query.data?.total ?? 0) : 0;
// The list no longer carries a kept issue; the detail cache follows its
// edits, and dropping it on delete ends the keep.
@@ -408,7 +409,7 @@ export function SidebarIssueList({
<SidebarIssueRow
wsId={wsId}
issue={issue}
- href={p.issueDetail(issue.id)}
+ href={p.issueDetail(issue.identifier)}
active={issue.id === activeIssueId}
locating={locating && issue.id === activeIssueId}
statusColor={statusCatalog.colorOf(issue.status)}
@@ -642,6 +643,7 @@ const SidebarIssueRow = memo(function SidebarIssueRow({
<AppLink
href={unreadIssueHref(href, unread)}
newTabTitle={issue.title}
+ data-issue-id={issue.id}
aria-current={active ? "page" : undefined}
onKeyDown={onKeyDown}
className={ISSUE_ROW_LINK_CLASS}
diff --git a/packages/views/layout/panels/work-panel.tsx b/packages/views/layout/panels/work-panel.tsx
index 490e8ff8ed..cc3e48a2b6 100644
--- a/packages/views/layout/panels/work-panel.tsx
+++ b/packages/views/layout/panels/work-panel.tsx
@@ -150,9 +150,9 @@ export function WorkPanel() {
: link.closest("[data-inbox-card]")
? INBOX_LIST
: (link.closest("[data-sidebar-list]")?.getAttribute("data-sidebar-list") ?? null);
- // Inbox links open the issue at its identifier; the Inbox records, and
- // the issue header compares, the issue's id.
- const segment = (list === INBOX_LIST && link.getAttribute("data-issue-id")) || routeSegment(path, p.issues());
+ // Inbox and tree links open the issue at its identifier; the lists
+ // record, and the issue header compares, the issue's id.
+ const segment = link.getAttribute("data-issue-id") || routeSegment(path, p.issues());
// A click that opens a tab or window, as AppLink resolves it, leaves this
// page and its records where they are. A desktop tab shares this page's
// store, so an issue the Inbox opens there is recorded beside them.
diff --git a/packages/views/layout/panels/work-tree.test.tsx b/packages/views/layout/panels/work-tree.test.tsx
index 09b507e61d..74e196ab27 100644
--- a/packages/views/layout/panels/work-tree.test.tsx
+++ b/packages/views/layout/panels/work-tree.test.tsx
@@ -64,6 +64,7 @@ vi.mock("@multica/core/auth", () => {
};
});
vi.mock("../../navigation", () => ({
+ useWarmRoute: () => undefined,
useIntentNavigate: () => vi.fn(),
useNavigation: () => ({ getShareableUrl: (path: string) => `https://app.example${path}` }),
AppLink: ({
diff --git a/packages/views/layout/route-data-prefetch.test.tsx b/packages/views/layout/route-data-prefetch.test.tsx
index 8cc05fd786..1ffcd146a3 100644
--- a/packages/views/layout/route-data-prefetch.test.tsx
+++ b/packages/views/layout/route-data-prefetch.test.tsx
@@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { WorkspaceSlugProvider } from "@multica/core/paths";
+import { issueKeys } from "@multica/core/issues/queries";
+import type { Issue } from "@multica/core/types";
import { NavigationProvider, AppLink, type NavigationAdapter } from "../navigation";
import { RouteDataPrefetch } from "./route-data-prefetch";
@@ -19,16 +21,24 @@ function adapter(): NavigationAdapter {
let qc: QueryClient;
let prefetched: unknown[][];
+let fetched: unknown[][];
-function renderLinks({ wsId }: { wsId: string | undefined } = { wsId: "ws-1" }) {
+const ISSUE_ID = "0b7f3c2e-5d1a-4c8e-9f6b-2a4d8e1c3b5f";
+const OTHER_ID = "7e2a9d4c-1b3f-4a6e-8c5d-9f0b2e4a6c8d";
+
+function renderLinks({ wsId, guest = false }: { wsId: string | undefined; guest?: boolean } = { wsId: "ws-1" }) {
return render(
<QueryClientProvider client={qc}>
<NavigationProvider value={adapter()}>
<WorkspaceSlugProvider slug="acme">
- <RouteDataPrefetch wsId={wsId} userId="user-1">
+ <RouteDataPrefetch wsId={wsId} userId="user-1" guest={guest}>
<AppLink href="/acme/agents">Agents</AppLink>
<AppLink href="/acme/projects?view=board">Projects</AppLink>
<AppLink href="/acme/settings">Settings</AppLink>
+ <AppLink href="/acme/issues/MUL-7">Issue by identifier</AppLink>
+ <AppLink href={`/acme/issues/${ISSUE_ID}`}>Issue by id</AppLink>
+ <AppLink href={`/acme/issues/${OTHER_ID}`}>Other issue</AppLink>
+ <AppLink href={`/acme/issues/${ISSUE_ID}/deliverables/report.html`}>Deliverable</AppLink>
</RouteDataPrefetch>
</WorkspaceSlugProvider>
</NavigationProvider>
@@ -43,6 +53,13 @@ beforeEach(() => {
vi.spyOn(qc, "prefetchQuery").mockImplementation(async (options) => {
prefetched.push([...(options.queryKey as readonly unknown[])]);
});
+ fetched = [];
+ vi.spyOn(qc, "fetchQuery").mockImplementation(async (options) => {
+ const key = options.queryKey as readonly unknown[];
+ fetched.push([...key]);
+ const ref = key.at(-1);
+ return { id: ref === "MUL-7" ? ISSUE_ID : ref, identifier: "MUL-7" } as Issue;
+ });
});
afterEach(() => {
@@ -94,4 +111,80 @@ describe("RouteDataPrefetch", () => {
expect(prefetched).toHaveLength(0);
});
+
+ it("fetches a hovered issue once the pointer rests, and what its page fills in after", async () => {
+ renderLinks();
+ fireEvent.mouseEnter(screen.getByText("Issue by identifier"));
+ await vi.advanceTimersByTimeAsync(39);
+ expect(fetched).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(1);
+ expect(fetched).toEqual([[...issueKeys.detail("ws-1", "MUL-7")]]);
+ // The page resolves the identifier, then keys everything else by UUID.
+ expect(qc.getQueryData(issueKeys.detail("ws-1", ISSUE_ID))).toMatchObject({ id: ISSUE_ID });
+ expect(prefetched).toHaveLength(0);
+
+ await vi.advanceTimersByTimeAsync(40);
+ expect(keys()).toEqual(
+ expect.arrayContaining([
+ JSON.stringify(issueKeys.timeline(ISSUE_ID)),
+ JSON.stringify(issueKeys.children("ws-1", ISSUE_ID)),
+ ]),
+ );
+ expect(keys()).not.toContain(JSON.stringify(issueKeys.timeline("MUL-7")));
+ });
+
+ it("fetches a focused issue at once", async () => {
+ renderLinks();
+ fireEvent.focus(screen.getByText("Issue by id"));
+
+ expect(fetched).toEqual([[...issueKeys.detail("ws-1", ISSUE_ID)]]);
+ await vi.advanceTimersByTimeAsync(80);
+ expect(keys()).toContain(JSON.stringify(issueKeys.timeline(ISSUE_ID)));
+ });
+
+ it("fetches nothing for issues a sweeping pointer only crosses", async () => {
+ renderLinks();
+ fireEvent.mouseEnter(screen.getByText("Issue by id"));
+ await vi.advanceTimersByTimeAsync(20);
+ fireEvent.mouseEnter(screen.getByText("Other issue"));
+ await vi.advanceTimersByTimeAsync(80);
+
+ expect(fetched).toEqual([[...issueKeys.detail("ws-1", OTHER_ID)]]);
+ expect(keys()).toContain(JSON.stringify(issueKeys.timeline(OTHER_ID)));
+ expect(keys().some((key) => key.includes(ISSUE_ID))).toBe(false);
+ });
+
+ it("drops what has not started when the pointer leaves or moves to another link", async () => {
+ renderLinks();
+ fireEvent.mouseEnter(screen.getByText("Issue by id"));
+ await vi.advanceTimersByTimeAsync(50);
+ fireEvent.mouseLeave(screen.getByText("Issue by id"));
+ fireEvent.mouseEnter(screen.getByText("Other issue"));
+ await vi.advanceTimersByTimeAsync(20);
+ fireEvent.mouseEnter(screen.getByText("Settings"));
+ await vi.advanceTimersByTimeAsync(200);
+
+ // The first issue was rested on long enough to fetch, not to fill in.
+ expect(fetched).toEqual([[...issueKeys.detail("ws-1", ISSUE_ID)]]);
+ expect(prefetched).toHaveLength(0);
+ });
+
+ it("fetches a guest only the issue", async () => {
+ renderLinks({ wsId: "ws-1", guest: true });
+ fireEvent.mouseEnter(screen.getByText("Issue by id"));
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(fetched).toEqual([[...issueKeys.detail("ws-1", ISSUE_ID)]]);
+ expect(keys().some((key) => key.includes(ISSUE_ID))).toBe(false);
+ });
+
+ it("leaves pages under an issue alone", async () => {
+ renderLinks();
+ fireEvent.mouseEnter(screen.getByText("Deliverable"));
+ await vi.advanceTimersByTimeAsync(200);
+
+ expect(fetched).toHaveLength(0);
+ expect(prefetched).toHaveLength(0);
+ });
});
diff --git a/packages/views/layout/route-data-prefetch.tsx b/packages/views/layout/route-data-prefetch.tsx
index 8097f0bcbc..15f3b8b85b 100644
--- a/packages/views/layout/route-data-prefetch.tsx
+++ b/packages/views/layout/route-data-prefetch.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useRef, type ReactNode } from "react";
import { useQueryClient, type QueryClient } from "@tanstack/react-query";
import {
agentActivity30dOptions,
@@ -10,6 +10,7 @@ import {
import { autopilotListOptions } from "@multica/core/autopilots/queries";
import { chatSessionsOptions } from "@multica/core/chat/queries";
import { inboxListOptions } from "@multica/core/inbox/queries";
+import { fetchIssueByRef, prefetchIssuePage } from "@multica/core/issues/queries";
import { useAuthStore } from "@multica/core/auth";
import { useIsGuest } from "@multica/core/permissions";
import { paths, useCurrentWorkspace, useWorkspaceSlug } from "@multica/core/paths";
@@ -73,6 +74,13 @@ const ROUTES = {
type RouteKey = keyof typeof ROUTES;
+// A pointer sweeping across a list of issues is not heading for every row it
+// crosses. A hovered issue is fetched once the pointer has rested on its link
+// for ISSUE_FETCH_INTENT_MS, and what its page fills in after that once it has
+// rested ISSUE_HOVER_INTENT_MS. Focus fetches the issue at once.
+const ISSUE_FETCH_INTENT_MS = 40;
+const ISSUE_HOVER_INTENT_MS = 80;
+
// A guest (MUL-9420) only reaches these pages.
const GUEST_ROUTES: RouteKey[] = ["projects", "inbox"];
@@ -88,9 +96,10 @@ const WARM_ON_IDLE: RouteKey[] = [
];
/**
- * Feeds `AppLink`'s hover/focus prefetch with the destination page's data and
- * warms the common list pages once the workspace is idle. Mount inside the
- * workspace shell, around the navigation that should benefit.
+ * Feeds `AppLink`'s hover/focus prefetch with the destination page's data, an
+ * issue page's included, and warms the common list pages once the workspace
+ * is idle. Mount inside the workspace shell, around the navigation that
+ * should benefit.
*/
export function RouteDataPrefetch({
wsId,
@@ -114,14 +123,51 @@ export function RouteDataPrefetch({
return new Map<string, WarmRoute>(keys.map((key) => [p[key](), ROUTES[key]]));
}, [slug, guest]);
+ const issuePrefix = slug ? `${paths.workspace(slug).issues()}/` : null;
+ const pending = useRef<ReturnType<typeof setTimeout>[]>([]);
+ const cancel = useCallback(() => {
+ for (const timer of pending.current) clearTimeout(timer);
+ pending.current = [];
+ }, []);
+ // Nothing scheduled for one workspace starts in another.
+ useEffect(() => cancel, [cancel, wsId]);
+
const prefetch = useCallback(
- (href: string) => {
+ (href: string, trigger: "hover" | "focus") => {
+ cancel();
if (!wsId) return;
const path = href.split(/[?#]/)[0] ?? href;
+ const segment = issuePrefix && path.startsWith(issuePrefix) ? path.slice(issuePrefix.length) : "";
+ if (segment && !segment.includes("/")) {
+ let ref: string;
+ try {
+ ref = decodeURIComponent(segment);
+ } catch {
+ return;
+ }
+ const later = (run: () => void, ms: number) => {
+ pending.current.push(setTimeout(run, ms));
+ };
+ // A failed warm-up is the page's own first request again.
+ const warm = () => {
+ const issue = fetchIssueByRef(qc, wsId, ref);
+ issue.catch(() => undefined);
+ // A guest's issue page reads the issue alone (MUL-9420).
+ if (guest) return;
+ later(
+ () => issue.then((loaded) => prefetchIssuePage(qc, wsId, loaded.id)).catch(() => undefined),
+ trigger === "hover" ? ISSUE_HOVER_INTENT_MS - ISSUE_FETCH_INTENT_MS : ISSUE_HOVER_INTENT_MS,
+ );
+ };
+ if (trigger === "hover") later(warm, ISSUE_FETCH_INTENT_MS);
+ else warm();
+ return;
+ }
routeByHref.get(path)?.(qc, wsId, userId);
},
- [qc, routeByHref, wsId, userId],
+ [qc, routeByHref, issuePrefix, wsId, userId, guest, cancel],
);
+ const prefetcher = useMemo(() => ({ prefetch, cancel }), [prefetch, cancel]);
useEffect(() => {
if (!wsId) return;
@@ -137,7 +183,7 @@ export function RouteDataPrefetch({
}, [qc, wsId, userId, guest]);
return (
- <RouteDataPrefetchProvider value={prefetch}>
+ <RouteDataPrefetchProvider value={prefetcher}>
{children}
</RouteDataPrefetchProvider>
);
diff --git a/packages/views/navigation/app-link.tsx b/packages/views/navigation/app-link.tsx
index 6c4f5da9d3..084f289971 100644
--- a/packages/views/navigation/app-link.tsx
+++ b/packages/views/navigation/app-link.tsx
@@ -30,6 +30,7 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
onClick,
onAuxClick,
onMouseEnter,
+ onMouseLeave,
onFocus,
target,
newTabTitle,
@@ -128,13 +129,18 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
const handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
prefetch?.(href);
- prefetchData?.(href);
+ prefetchData?.prefetch(href, "hover");
onMouseEnter?.(e);
};
+ const handleMouseLeave = (e: React.MouseEvent<HTMLAnchorElement>) => {
+ prefetchData?.cancel();
+ onMouseLeave?.(e);
+ };
+
const handleFocus = (e: React.FocusEvent<HTMLAnchorElement>) => {
prefetch?.(href);
- prefetchData?.(href);
+ prefetchData?.prefetch(href, "focus");
onFocus?.(e);
};
@@ -148,12 +154,13 @@ export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(
rel={target === "_blank" ? "noopener noreferrer" : undefined}
// Spread props first so that the navigation handlers below cannot be
// silently overridden by a caller passing
- // onClick/onAuxClick/onMouseEnter/onFocus through {...rest}. AppLink
- // owns these four events.
+ // onClick/onAuxClick/onMouseEnter/onMouseLeave/onFocus through
+ // {...rest}. AppLink owns these five events.
{...props}
onClick={handleClick}
onAuxClick={handleAuxClick}
onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
onFocus={handleFocus}
>
{children}
diff --git a/packages/views/navigation/index.ts b/packages/views/navigation/index.ts
index 82ef44e2f4..b5b5a2bf45 100644
--- a/packages/views/navigation/index.ts
+++ b/packages/views/navigation/index.ts
@@ -19,4 +19,5 @@ export { useRowLink, rowLinkInteractiveProps } from "./use-row-link";
export { useIntentNavigate } from "./use-intent-navigate";
export { useBackOrReplace } from "./use-back-or-replace";
export { useHeldUntilArrival } from "./use-held-until-arrival";
+export { useWarmRoute } from "./use-warm-route";
export type { NavigationAdapter } from "./types";
diff --git a/packages/views/navigation/route-data-prefetch.tsx b/packages/views/navigation/route-data-prefetch.tsx
index b5bc885fc8..e8a90f1914 100644
--- a/packages/views/navigation/route-data-prefetch.tsx
+++ b/packages/views/navigation/route-data-prefetch.tsx
@@ -9,7 +9,15 @@ import { createContext, use } from "react";
* inside the workspace shell; links rendered outside one get `null` and skip
* it.
*/
-export type RouteDataPrefetcher = (href: string) => void;
+export interface RouteDataPrefetcher {
+ /**
+ * A link to `href` is pointed at or focused. A warm-up that costs a request
+ * per link may wait for a hovering pointer to rest before it starts.
+ */
+ prefetch(href: string, trigger: "hover" | "focus"): void;
+ /** The pointer left the link: drop what has not started yet. */
+ cancel(): void;
+}
const RouteDataPrefetchContext = createContext<RouteDataPrefetcher | null>(
null,
diff --git a/packages/views/navigation/use-warm-route.test.tsx b/packages/views/navigation/use-warm-route.test.tsx
new file mode 100644
index 0000000000..4828dc0481
--- /dev/null
+++ b/packages/views/navigation/use-warm-route.test.tsx
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+import { NavigationProvider } from "./context";
+import type { NavigationAdapter } from "./types";
+import { useWarmRoute } from "./use-warm-route";
+
+function wrapper(prefetch: NavigationAdapter["prefetch"]) {
+ const adapter: NavigationAdapter = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (p) => p,
+ prefetch,
+ };
+ return function Wrapper({ children }: { children: ReactNode }) {
+ return <NavigationProvider value={adapter}>{children}</NavigationProvider>;
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("useWarmRoute", () => {
+ it("prefetches one page of a kind once the browser is idle, once per session", () => {
+ const prefetch = vi.fn();
+ const first = renderHook(() => useWarmRoute("issue-a", "/acme/issues/MUL-1"), { wrapper: wrapper(prefetch) });
+ expect(prefetch).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(3000);
+ expect(prefetch).toHaveBeenCalledWith("/acme/issues/MUL-1");
+ first.unmount();
+
+ renderHook(() => useWarmRoute("issue-a", "/acme/issues/MUL-2"), { wrapper: wrapper(prefetch) });
+ vi.advanceTimersByTime(3000);
+ expect(prefetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("warms once when several lists of a kind mount together", () => {
+ const prefetch = vi.fn();
+ renderHook(
+ () => {
+ useWarmRoute("issue-d", "/acme/issues/MUL-1");
+ useWarmRoute("issue-d", "/acme/issues/MUL-2");
+ },
+ { wrapper: wrapper(prefetch) },
+ );
+ vi.advanceTimersByTime(3000);
+ expect(prefetch).toHaveBeenCalledTimes(1);
+ expect(prefetch).toHaveBeenCalledWith("/acme/issues/MUL-1");
+ });
+
+ it("keeps waiting while there is no page to warm", () => {
+ const prefetch = vi.fn();
+ const { rerender } = renderHook(({ href }: { href: string | null }) => useWarmRoute("issue-b", href), {
+ wrapper: wrapper(prefetch),
+ initialProps: { href: null as string | null },
+ });
+ vi.advanceTimersByTime(3000);
+ expect(prefetch).not.toHaveBeenCalled();
+
+ rerender({ href: "/acme/issues/MUL-3" });
+ vi.advanceTimersByTime(3000);
+ expect(prefetch).toHaveBeenCalledWith("/acme/issues/MUL-3");
+ });
+
+ it("does nothing without route prefetch (desktop)", () => {
+ renderHook(() => useWarmRoute("issue-c", "/acme/issues/MUL-1"), { wrapper: wrapper(undefined) });
+ expect(() => vi.advanceTimersByTime(3000)).not.toThrow();
+ });
+});
diff --git a/packages/views/navigation/use-warm-route.ts b/packages/views/navigation/use-warm-route.ts
new file mode 100644
index 0000000000..c76edc10d6
--- /dev/null
+++ b/packages/views/navigation/use-warm-route.ts
@@ -0,0 +1,33 @@
+"use client";
+
+import { useEffect } from "react";
+import { useNavigation } from "./context";
+
+const warmed = new Set<string>();
+
+/**
+ * Prefetches one page of a kind (`"doc"`, `"issue"`) once per session when the
+ * browser is idle. On web a detail page's code is shared by every page of its
+ * kind but only requested after one page's route payload arrives, which put a
+ * whole round trip in front of the first one opened; warming one of them here
+ * loads that code early and teaches the router the route's shape. Desktop
+ * bundles its routes and has no route prefetch, so this is a no-op there.
+ */
+export function useWarmRoute(kind: string, href: string | null | undefined) {
+ const { prefetch } = useNavigation();
+ useEffect(() => {
+ if (!href || !prefetch || warmed.has(kind)) return;
+ const warm = () => {
+ // Every list of a kind mounted in one commit scheduled its own warm-up.
+ if (warmed.has(kind)) return;
+ warmed.add(kind);
+ prefetch(href);
+ };
+ if (typeof window.requestIdleCallback === "function") {
+ const id = window.requestIdleCallback(warm, { timeout: 3000 });
+ return () => window.cancelIdleCallback(id);
+ }
+ const timer = window.setTimeout(warm, 1500);
+ return () => window.clearTimeout(timer);
+ }, [kind, href, prefetch]);
+}