Skip to content

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

Go

perf(issue-detail): memoize timeline render to mitigate Inbox long-timeline freeze (#2025)

Bohan Jiangd0c66f3173cc
diff --git a/packages/views/editor/readonly-content.test.tsx b/packages/views/editor/readonly-content.test.tsx
index 566f68885c..4ed94090e8 100644
--- a/packages/views/editor/readonly-content.test.tsx
+++ b/packages/views/editor/readonly-content.test.tsx
@@ -60,6 +60,20 @@ afterEach(() => {
vi.restoreAllMocks();
});
+describe("ReadonlyContent memoization", () => {
+ // Long-timeline issues (Inbox + IssueDetail with thousands of comments)
+ // freeze the tab when each comment re-runs the full react-markdown pipeline
+ // on every parent re-render. Wrapping the component in React.memo is the
+ // mitigation; this test guards against a future revert that would silently
+ // reintroduce the perf regression.
+ it("is wrapped in React.memo", () => {
+ const memoTypeSymbol = Symbol.for("react.memo");
+ expect((ReadonlyContent as unknown as { $$typeof: symbol }).$$typeof).toBe(
+ memoTypeSymbol,
+ );
+ });
+});
+
describe("ReadonlyContent math rendering", () => {
it("renders inline and block LaTeX with KaTeX markup", () => {
const { container } = render(
diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsx
index 1a28592aeb..2e7815ef73 100644
--- a/packages/views/editor/readonly-content.tsx
+++ b/packages/views/editor/readonly-content.tsx
@@ -16,7 +16,7 @@
* - Rendering mentions with the same IssueMentionCard component and .mention class
*/
-import { isValidElement, useEffect, useId, useMemo, useRef, useState } from "react";
+import { isValidElement, memo, useEffect, useId, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import ReactMarkdown, {
defaultUrlTransform,
@@ -573,7 +573,14 @@ interface ReadonlyContentProps {
className?: string;
}
-export function ReadonlyContent({ content, className }: ReadonlyContentProps) {
+// Memoized so a long timeline of comments (Inbox + IssueDetail) does not
+// re-run the full react-markdown + rehype-* + lowlight pipeline on every
+// parent re-render. Props are `content` and `className` (both strings), so
+// React.memo's default shallow comparison is value-equality here.
+export const ReadonlyContent = memo(function ReadonlyContent({
+ content,
+ className,
+}: ReadonlyContentProps) {
const processed = useMemo(() => preprocessMarkdown(content), [content]);
const wrapperRef = useRef<HTMLDivElement>(null);
const hover = useLinkHover(wrapperRef);
@@ -591,4 +598,4 @@ export function ReadonlyContent({ content, className }: ReadonlyContentProps) {
<LinkHoverCard {...hover} />
</div>
);
-}
+});
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 8e086caa80..5a1dfc83d7 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useRef, useState } from "react";
+import { memo, useCallback, useRef, useState } from "react";
import { ChevronRight, Copy, Download, FileText, MoreHorizontal, Pencil, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
@@ -348,7 +348,7 @@ function CommentRow({
// CommentCard — One Card per thread (parent + all replies flat inside)
// ---------------------------------------------------------------------------
-function CommentCard({
+function CommentCardImpl({
issueId,
entry,
allReplies,
@@ -606,4 +606,11 @@ function CommentCard({
);
}
+// Memoized so a long timeline (e.g. Inbox-embedded IssueDetail with thousands
+// of comments) does not re-render every card on each parent state update or
+// WS-driven cache refresh. Default shallow comparison is sufficient: the
+// timeline grouping is useMemo'd in issue-detail.tsx (stable Map ref), and
+// every callback is stabilized via useCallback in use-issue-timeline.ts.
+const CommentCard = memo(CommentCardImpl);
+
export { CommentCard, type CommentCardProps };
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 3ef4df4d76..eac22faf02 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useEffect, useCallback, useRef } from "react";
+import { useState, useEffect, useCallback, useMemo, useRef } from "react";
import { useDefaultLayout, usePanelRef } from "react-resizable-panels";
import { AppLink } from "../../navigation";
import { useNavigation } from "../../navigation";
@@ -244,6 +244,59 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
editComment, deleteComment, toggleReaction: handleToggleReaction,
} = useIssueTimeline(id, user?.id);
+ // Memoized timeline grouping. The same Map / groups references are reused
+ // across re-renders that don't change `timeline`, so React.memo on
+ // CommentCard can skip re-rendering when the only thing that moved was
+ // unrelated parent state (e.g. composer draft, sidebar toggle).
+ const timelineView = useMemo(() => {
+ const topLevel = timeline.filter((e) => e.type === "activity" || !e.parent_id);
+ const repliesByParent = new Map<string, TimelineEntry[]>();
+ for (const e of timeline) {
+ if (e.type === "comment" && e.parent_id) {
+ const list = repliesByParent.get(e.parent_id) ?? [];
+ list.push(e);
+ repliesByParent.set(e.parent_id, list);
+ }
+ }
+
+ // Coalesce: same actor + same action within 2 min → keep last only
+ const COALESCE_MS = 2 * 60 * 1000;
+ const coalesced: TimelineEntry[] = [];
+ for (const entry of topLevel) {
+ if (entry.type === "activity") {
+ const prev = coalesced[coalesced.length - 1];
+ if (
+ prev?.type === "activity" &&
+ prev.action === entry.action &&
+ prev.actor_type === entry.actor_type &&
+ prev.actor_id === entry.actor_id &&
+ Math.abs(new Date(entry.created_at).getTime() - new Date(prev.created_at).getTime()) <= COALESCE_MS
+ ) {
+ coalesced[coalesced.length - 1] = entry;
+ continue;
+ }
+ }
+ coalesced.push(entry);
+ }
+
+ // Group consecutive activities together so the connector line works
+ const groups: { type: "activities" | "comment"; entries: TimelineEntry[] }[] = [];
+ for (const entry of coalesced) {
+ if (entry.type === "activity") {
+ const last = groups[groups.length - 1];
+ if (last?.type === "activities") {
+ last.entries.push(entry);
+ } else {
+ groups.push({ type: "activities", entries: [entry] });
+ }
+ } else {
+ groups.push({ type: "comment", entries: [entry] });
+ }
+ }
+
+ return { repliesByParent, groups };
+ }, [timeline]);
+
const {
reactions: issueReactions,
toggleReaction: handleToggleIssueReaction,
@@ -895,121 +948,73 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
{/* Timeline entries */}
<div className="mt-4 flex flex-col gap-3">
- {(() => {
- const topLevel = timeline.filter((e) => e.type === "activity" || !e.parent_id);
- const repliesByParent = new Map<string, TimelineEntry[]>();
- for (const e of timeline) {
- if (e.type === "comment" && e.parent_id) {
- const list = repliesByParent.get(e.parent_id) ?? [];
- list.push(e);
- repliesByParent.set(e.parent_id, list);
- }
- }
-
- // Coalesce: same actor + same action within 2 min → keep last only
- const COALESCE_MS = 2 * 60 * 1000;
- const coalesced: TimelineEntry[] = [];
- for (const entry of topLevel) {
- if (entry.type === "activity") {
- const prev = coalesced[coalesced.length - 1];
- if (
- prev?.type === "activity" &&
- prev.action === entry.action &&
- prev.actor_type === entry.actor_type &&
- prev.actor_id === entry.actor_id &&
- Math.abs(new Date(entry.created_at).getTime() - new Date(prev.created_at).getTime()) <= COALESCE_MS
- ) {
- // Replace previous with this one (keep the later result)
- coalesced[coalesced.length - 1] = entry;
- continue;
- }
- }
- coalesced.push(entry);
- }
-
- // Group consecutive activities together so the connector line works
- const groups: { type: "activities" | "comment"; entries: TimelineEntry[] }[] = [];
- for (const entry of coalesced) {
- if (entry.type === "activity") {
- const last = groups[groups.length - 1];
- if (last?.type === "activities") {
- last.entries.push(entry);
- } else {
- groups.push({ type: "activities", entries: [entry] });
- }
- } else {
- groups.push({ type: "comment", entries: [entry] });
- }
+ {timelineView.groups.map((group) => {
+ if (group.type === "comment") {
+ const entry = group.entries[0]!;
+ return (
+ <div key={entry.id} id={`comment-${entry.id}`}>
+ <CommentCard
+ issueId={id}
+ entry={entry}
+ allReplies={timelineView.repliesByParent}
+ currentUserId={user?.id}
+ canModerate={canModerateComments}
+ onReply={submitReply}
+ onEdit={editComment}
+ onDelete={deleteComment}
+ onToggleReaction={handleToggleReaction}
+ highlightedCommentId={highlightedId}
+ />
+ </div>
+ );
}
- return groups.map((group) => {
- if (group.type === "comment") {
- const entry = group.entries[0]!;
- return (
- <div key={entry.id} id={`comment-${entry.id}`}>
- <CommentCard
- issueId={id}
- entry={entry}
- allReplies={repliesByParent}
- currentUserId={user?.id}
- canModerate={canModerateComments}
- onReply={submitReply}
- onEdit={editComment}
- onDelete={deleteComment}
- onToggleReaction={handleToggleReaction}
- highlightedCommentId={highlightedId}
- />
- </div>
- );
- }
-
- return (
- <div key={group.entries[0]!.id} className="px-4 flex flex-col gap-3">
- {group.entries.map((entry, _idx) => {
- const details = (entry.details ?? {}) as Record<string, string>;
- const isStatusChange = entry.action === "status_changed";
- const isPriorityChange = entry.action === "priority_changed";
- const isDueDateChange = entry.action === "due_date_changed";
+ return (
+ <div key={group.entries[0]!.id} className="px-4 flex flex-col gap-3">
+ {group.entries.map((entry, _idx) => {
+ const details = (entry.details ?? {}) as Record<string, string>;
+ const isStatusChange = entry.action === "status_changed";
+ const isPriorityChange = entry.action === "priority_changed";
+ const isDueDateChange = entry.action === "due_date_changed";
- let leadIcon: React.ReactNode;
- if (isStatusChange && details.to) {
- leadIcon = <StatusIcon status={details.to as IssueStatus} className="h-4 w-4 shrink-0" />;
- } else if (isPriorityChange && details.to) {
- leadIcon = <PriorityIcon priority={details.to as IssuePriority} className="h-4 w-4 shrink-0" />;
- } else if (isDueDateChange) {
- leadIcon = <Calendar className="h-4 w-4 shrink-0 text-muted-foreground" />;
- } else {
- leadIcon = <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={16} />;
- }
+ let leadIcon: React.ReactNode;
+ if (isStatusChange && details.to) {
+ leadIcon = <StatusIcon status={details.to as IssueStatus} className="h-4 w-4 shrink-0" />;
+ } else if (isPriorityChange && details.to) {
+ leadIcon = <PriorityIcon priority={details.to as IssuePriority} className="h-4 w-4 shrink-0" />;
+ } else if (isDueDateChange) {
+ leadIcon = <Calendar className="h-4 w-4 shrink-0 text-muted-foreground" />;
+ } else {
+ leadIcon = <ActorAvatar actorType={entry.actor_type} actorId={entry.actor_id} size={16} />;
+ }
- return (
- <div key={entry.id} className="flex items-center text-xs text-muted-foreground">
- <div className="mr-2 flex w-4 shrink-0 justify-center">
- {leadIcon}
- </div>
- <div className="flex min-w-0 flex-1 items-center gap-1">
- <span className="shrink-0 font-medium">{getActorName(entry.actor_type, entry.actor_id)}</span>
- <span className="truncate">{formatActivity(entry, getActorName)}</span>
- <Tooltip>
- <TooltipTrigger
- render={
- <span className="ml-auto shrink-0 cursor-default">
- {timeAgo(entry.created_at)}
- </span>
- }
- />
- <TooltipContent side="top">
- {new Date(entry.created_at).toLocaleString()}
- </TooltipContent>
- </Tooltip>
- </div>
+ return (
+ <div key={entry.id} className="flex items-center text-xs text-muted-foreground">
+ <div className="mr-2 flex w-4 shrink-0 justify-center">
+ {leadIcon}
</div>
- );
- })}
- </div>
- );
- });
- })()}
+ <div className="flex min-w-0 flex-1 items-center gap-1">
+ <span className="shrink-0 font-medium">{getActorName(entry.actor_type, entry.actor_id)}</span>
+ <span className="truncate">{formatActivity(entry, getActorName)}</span>
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <span className="ml-auto shrink-0 cursor-default">
+ {timeAgo(entry.created_at)}
+ </span>
+ }
+ />
+ <TooltipContent side="top">
+ {new Date(entry.created_at).toLocaleString()}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ );
+ })}
</div>
{/* Bottom comment input — no avatar, full width */}
diff --git a/packages/views/issues/hooks/use-issue-timeline.test.tsx b/packages/views/issues/hooks/use-issue-timeline.test.tsx
new file mode 100644
index 0000000000..95e7403d85
--- /dev/null
+++ b/packages/views/issues/hooks/use-issue-timeline.test.tsx
@@ -0,0 +1,109 @@
+import { describe, it, expect, vi } from "vitest";
+import { renderHook } from "@testing-library/react";
+
+// Mock @multica/core/issues/mutations to mimic TanStack Query v5's contract:
+// useMutation returns a fresh result wrapper on every render, but the
+// `mutate` / `mutateAsync` functions inside it are stable across renders.
+// This is exactly the shape that previously fooled the original deps lists
+// in useIssueTimeline — guarding against a regression here means future code
+// can't accidentally pull the whole mutation result into a useCallback dep.
+const stableHandles = vi.hoisted(() => ({
+ createMutateAsync: vi.fn(async () => ({})),
+ updateMutateAsync: vi.fn(async () => ({})),
+ deleteMutateAsync: vi.fn(async () => ({})),
+ toggleMutate: vi.fn(),
+}));
+
+vi.mock("@multica/core/issues/mutations", () => ({
+ useCreateComment: () => ({
+ mutateAsync: stableHandles.createMutateAsync,
+ mutate: vi.fn(),
+ isPending: false,
+ }),
+ useUpdateComment: () => ({
+ mutateAsync: stableHandles.updateMutateAsync,
+ mutate: vi.fn(),
+ isPending: false,
+ }),
+ useDeleteComment: () => ({
+ mutateAsync: stableHandles.deleteMutateAsync,
+ mutate: vi.fn(),
+ isPending: false,
+ }),
+ useToggleCommentReaction: () => ({
+ mutateAsync: vi.fn(),
+ mutate: stableHandles.toggleMutate,
+ isPending: false,
+ }),
+}));
+
+vi.mock("@multica/core/issues/queries", () => ({
+ issueTimelineOptions: (id: string) => ({
+ queryKey: ["issues", id, "timeline"],
+ queryFn: () => [],
+ }),
+ issueKeys: {
+ timeline: (id: string) => ["issues", id, "timeline"],
+ },
+}));
+
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>(
+ "@tanstack/react-query",
+ );
+ return {
+ ...actual,
+ useQuery: () => ({ data: [], isLoading: false }),
+ useQueryClient: () => ({
+ invalidateQueries: vi.fn(),
+ setQueryData: vi.fn(),
+ cancelQueries: vi.fn(),
+ getQueryData: vi.fn(),
+ }),
+ useMutationState: () => [],
+ };
+});
+
+vi.mock("@multica/core/realtime", () => ({
+ useWSEvent: vi.fn(),
+ useWSReconnect: vi.fn(),
+}));
+
+vi.mock("sonner", () => ({
+ toast: { error: vi.fn(), success: vi.fn() },
+}));
+
+import { useIssueTimeline } from "./use-issue-timeline";
+
+describe("useIssueTimeline callback stability", () => {
+ // CommentCard is wrapped in React.memo (perf fix for long timelines, see
+ // multica#1968). The memo only pays off if the callbacks passed down keep
+ // the same identity across unrelated parent re-renders. TanStack Query v5
+ // returns a *new* mutation result wrapper on every render, so a useCallback
+ // listing the whole mutation object as a dep flips its identity every time
+ // — that is the exact regression this test guards against.
+ it("submitReply / editComment / deleteComment / toggleReaction keep identity across unrelated re-renders", () => {
+ const { result, rerender } = renderHook(() => useIssueTimeline("issue-1", "user-1"));
+
+ const first = {
+ submitComment: result.current.submitComment,
+ submitReply: result.current.submitReply,
+ editComment: result.current.editComment,
+ deleteComment: result.current.deleteComment,
+ toggleReaction: result.current.toggleReaction,
+ };
+
+ rerender();
+ rerender();
+
+ expect(result.current.submitReply).toBe(first.submitReply);
+ expect(result.current.editComment).toBe(first.editComment);
+ expect(result.current.deleteComment).toBe(first.deleteComment);
+ expect(result.current.toggleReaction).toBe(first.toggleReaction);
+ // submitComment intentionally also depends on `submitting` — it's only
+ // wired into <CommentInput>, not CommentCard, so its identity isn't a
+ // memo-stability concern. Still, with no submission in flight it should
+ // be stable too.
+ expect(result.current.submitComment).toBe(first.submitComment);
+ });
+});
diff --git a/packages/views/issues/hooks/use-issue-timeline.ts b/packages/views/issues/hooks/use-issue-timeline.ts
index 2ecd040120..eea9bbe0e7 100644
--- a/packages/views/issues/hooks/use-issue-timeline.ts
+++ b/packages/views/issues/hooks/use-issue-timeline.ts
@@ -1,6 +1,6 @@
"use client";
-import { useState, useCallback, useMemo } from "react";
+import { useEffect, useRef, useState, useCallback, useMemo } from "react";
import { useQuery, useQueryClient, useMutationState } from "@tanstack/react-query";
import type { Comment, TimelineEntry, Reaction } from "@multica/core/types";
import type {
@@ -45,10 +45,15 @@ export function useIssueTimeline(issueId: string, userId?: string) {
);
const [submitting, setSubmitting] = useState(false);
- const createCommentMutation = useCreateComment(issueId);
- const updateCommentMutation = useUpdateComment(issueId);
- const deleteCommentMutation = useDeleteComment(issueId);
- const toggleReactionMutation = useToggleCommentReaction(issueId);
+ // TanStack Query v5 returns a fresh result wrapper from useMutation on
+ // every render, but the mutate / mutateAsync functions inside are stable
+ // across renders. Pull just the stable handles so the useCallback
+ // identities below do not flip on every parent re-render — listing the
+ // whole mutation object would defeat React.memo on CommentCard.
+ const { mutateAsync: createComment } = useCreateComment(issueId);
+ const { mutateAsync: updateComment } = useUpdateComment(issueId);
+ const { mutateAsync: deleteCommentAsync } = useDeleteComment(issueId);
+ const { mutate: toggleCommentReaction } = useToggleCommentReaction(issueId);
// Reconnect recovery
useWSReconnect(
@@ -213,24 +218,21 @@ export function useIssueTimeline(issueId: string, userId?: string) {
if (!content.trim() || submitting || !userId) return;
setSubmitting(true);
try {
- await createCommentMutation.mutateAsync({
- content,
- attachmentIds,
- });
+ await createComment({ content, attachmentIds });
} catch {
toast.error("Failed to send comment");
} finally {
setSubmitting(false);
}
},
- [userId, submitting, createCommentMutation],
+ [userId, submitting, createComment],
);
const submitReply = useCallback(
async (parentId: string, content: string, attachmentIds?: string[]) => {
if (!content.trim() || !userId) return;
try {
- await createCommentMutation.mutateAsync({
+ await createComment({
content,
type: "comment",
parentId,
@@ -240,29 +242,29 @@ export function useIssueTimeline(issueId: string, userId?: string) {
toast.error("Failed to send reply");
}
},
- [userId, createCommentMutation],
+ [userId, createComment],
);
const editComment = useCallback(
async (commentId: string, content: string) => {
try {
- await updateCommentMutation.mutateAsync({ commentId, content });
+ await updateComment({ commentId, content });
} catch {
toast.error("Failed to update comment");
}
},
- [updateCommentMutation],
+ [updateComment],
);
const deleteComment = useCallback(
async (commentId: string) => {
try {
- await deleteCommentMutation.mutateAsync(commentId);
+ await deleteCommentAsync(commentId);
} catch {
toast.error("Failed to delete comment");
}
},
- [deleteCommentMutation],
+ [deleteCommentAsync],
);
// --- Optimistic UI derivation for comment reactions ---
@@ -320,20 +322,29 @@ export function useIssueTimeline(issueId: string, userId?: string) {
});
}, [timeline, pendingReactionVars, userId]);
+ // Read timeline through a ref so toggleReaction's identity does not change
+ // on every WS event. Without this, every memoized CommentCard down-tree
+ // would re-render on each timeline mutation, defeating the React.memo cost
+ // savings on long timelines (see Inbox-freeze fix).
+ const timelineRef = useRef(timeline);
+ useEffect(() => {
+ timelineRef.current = timeline;
+ }, [timeline]);
+
const toggleReaction = useCallback(
async (commentId: string, emoji: string) => {
if (!userId) return;
// Read from server timeline (not optimistic) to find the real reaction
- const entry = timeline.find((e) => e.id === commentId);
+ const entry = timelineRef.current.find((e) => e.id === commentId);
const existing: Reaction | undefined = (entry?.reactions ?? []).find(
(r) =>
r.emoji === emoji &&
r.actor_type === "member" &&
r.actor_id === userId,
);
- toggleReactionMutation.mutate({ commentId, emoji, existing });
+ toggleCommentReaction({ commentId, emoji, existing });
},
- [userId, timeline, toggleReactionMutation],
+ [userId, toggleCommentReaction],
);
return {