Skip to content

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

Go

perf(issues): land deep links on the target without mounting the history (MUL-9538) (#10874)

Jiayuan Zhangf5831e594297
diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsx
index 1027179741..521063d479 100644
--- a/packages/views/issues/components/inline-comment-run.tsx
+++ b/packages/views/issues/components/inline-comment-run.tsx
@@ -24,7 +24,7 @@ import { buildTimeline } from "../../common/task-transcript/build-timeline";
import { buildSteps, groupSteps, isCallStep, isGroupRow, type TraceRow } from "../../common/task-transcript/build-steps";
import { traceEventSummary, traceToolArgSummary } from "../../common/task-transcript/trace-event-presenter";
import { redactSecrets } from "../../common/task-transcript/redact";
-import { runOutputFindKey } from "../utils/timeline-find-units";
+import { runOutputKey } from "../utils/timeline-row-content";
import { ReadonlyContent } from "../../editor";
import { useLocale, useT, useTimeAgo } from "../../i18n";
import { formatDuration } from "../../agents/components/agent-activity-hover-content";
@@ -234,7 +234,7 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal
</div>
<div className={cn(showIdentity && "pl-8")}>
{replyTo}
- {output && <div className="mt-2 text-body" data-find-unit={runOutputFindKey(task.id)}><ReadonlyContent content={redactSecrets(output)} /></div>}
+ {output && <div className="mt-2 text-body" data-find-unit={runOutputKey(task.id)}><ReadonlyContent content={redactSecrets(output)} /></div>}
{needsAction && rawError && <TruncatedTooltip content={rawError} focusable>
<p
className="mt-1.5 line-clamp-4 whitespace-pre-wrap break-words rounded-md border bg-muted/50 px-2.5 py-1.5 font-mono text-caption text-muted-foreground">
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index ee9ea5f598..cedebb06c4 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -19,6 +19,7 @@ import enCommon from "../../locales/en/common.json";
import enIssues from "../../locales/en/issues.json";
import { useIssueSidebarSectionsStore } from "@multica/core/issues/stores/issue-sidebar-sections-store";
import { useSubIssuesCollapseStore } from "@multica/core/issues/stores/sub-issues-collapse-store";
+import { configureShortcutPlatform } from "@multica/core/shortcuts";
vi.mock("./issue-wakeup-header-chip", () => ({
IssueWakeupHeaderChip: ({ onOpen }: { onOpen: () => void }) => (
@@ -1063,6 +1064,9 @@ describe("IssueDetail (shared)", () => {
// Find only answers in a visible page; jsdom lays nothing out.
const rects = vi.spyOn(HTMLElement.prototype, "getClientRects")
.mockReturnValue([new DOMRect(0, 0, 1, 1)] as unknown as DOMRectList);
+ // jsdom's user agent names the host OS, which would make the find chord
+ // Cmd+F on a Mac host.
+ configureShortcutPlatform("linux");
try {
renderIssueDetail();
await screen.findByText("Historical comment 0");
@@ -1079,6 +1083,7 @@ describe("IssueDetail (shared)", () => {
expect(screen.getByTestId("virtuoso-mock")).toBeInTheDocument();
} finally {
rects.mockRestore();
+ configureShortcutPlatform(null);
}
});
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 026fb7b7b7..af99a8672a 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -215,6 +215,7 @@ import { useIssueDetailScrollRestore } from "../hooks/use-issue-detail-scroll-re
import { useIssueTimelineAnchor } from "../hooks/use-issue-timeline-anchor";
import { revealTimelineList, scrollToTimelineComment } from "../utils/scroll-to-timeline-comment";
import { buildTimelineFindUnits, type TimelineFindUnit } from "../utils/timeline-find-units";
+import { estimateTimelineItemHeights, timelineCharsPerLine } from "../utils/timeline-height-estimates";
import { useJumpToLatest } from "../hooks/use-jump-to-latest";
import { useNewCommentsWhileAway } from "../hooks/use-new-comments-while-away";
import { useInPageFind } from "../hooks/use-in-page-find";
@@ -1604,6 +1605,9 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
// Virtuoso prop would never receive the element. Callback ref + state fixes
// that: setState triggers the re-render that hands Virtuoso the element.
const [scrollContainerEl, setScrollContainerEl] = useState<HTMLDivElement | null>(null);
+ // Read once when the container attaches, for the timeline's row height
+ // estimates; 0 while it is not laid out (a hidden desktop tab).
+ const [scrollContainerWidth, setScrollContainerWidth] = useState(0);
// Bottom comment composer. Measured when scrolling a freshly posted comment
// into view so its bottom lands above the composer rather than behind it.
const composerRef = useRef<HTMLDivElement | null>(null);
@@ -1651,6 +1655,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
// The peek has no sidebar, so it must not claim the toggle shortcut.
rightSidebarShortcutTargetRef.current = isPeek ? null : el;
setScrollContainerEl(el);
+ setScrollContainerWidth(el?.clientWidth ?? 0);
restoreScrollRef(el);
},
[isPeek, restoreScrollRef],
@@ -2122,6 +2127,41 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
const handleTimelineHeightChange = useCallback((height: number) => {
if (height > 0) setMeasuredTimelineId(id);
}, [id]);
+ // Row heights estimated from content, so Virtuoso's first layout of a long
+ // history is roughly right: a deep link then lands on its target by mounting
+ // only the rows around it (see estimateTimelineItemHeights). Virtuoso reads
+ // estimates only until it has measured a row, so they stop being computed
+ // once the list has a height.
+ const timelineMeasured = measuredTimelineId === id;
+ const timelineHeightEstimates = useMemo(() => {
+ if (timelineMeasured || scrollContainerWidth <= 0) return undefined;
+ const activityCounts = new Map<string, number>();
+ for (const item of items) if (item.kind === "activity-group") activityCounts.set(item.id, item.entries.length);
+ return estimateTimelineItemHeights(
+ items,
+ timelineView.threadReplies,
+ commentRuns,
+ { expandedResolved, collapsed: new Set(collapsedThreadIds) },
+ {
+ charsPerLine: timelineCharsPerLine(scrollContainerWidth),
+ // Mirrors renderItem: only the trailing block opens by default, and it
+ // shows its latest entries until the reader asks for older ones.
+ activityLines: (itemId) => {
+ const expanded = expandedActivityIds.has(itemId) || (!collapsedActivityIds.has(itemId) && itemId === lastActivityGroupId);
+ if (!expanded) return 0;
+ const count = activityCounts.get(itemId) ?? 0;
+ return itemId === lastActivityGroupId && !showOlderActivityIds.has(itemId)
+ ? Math.min(count, LAST_ACTIVITY_BLOCK_VISIBLE_LIMIT) : count;
+ },
+ },
+ );
+ }, [timelineMeasured, scrollContainerWidth, items, timelineView.threadReplies, commentRuns, expandedResolved,
+ collapsedThreadIds, expandedActivityIds, collapsedActivityIds, showOlderActivityIds, lastActivityGroupId]);
+ // Whether Virtuoso can place a row by index. Without estimates it needs one
+ // measured row first: the timeline is scrolled into view to get it. With
+ // estimates it already can, and that detour would mount the top of the
+ // history before a deep link jumps away from it.
+ const timelineSized = timelineMeasured || timelineHeightEstimates !== undefined;
// Whether Virtuoso's rendered rows (overscan included) stop short of the
// last one; rows past them are only estimated. Settled from Virtuoso's own
// range report, not `items.length`: a comment appended at the bottom is
@@ -2169,7 +2209,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
}
const index = items.findIndex((item) => item.id === rootId);
if (index < 0) { completeAnchorRestore(); return; }
- if (measuredTimelineId !== id) {
+ if (!timelineSized) {
const list = virtualTimelineRef.current;
return list ? revealTimelineList(container, list) : undefined;
}
@@ -2178,7 +2218,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
commentId: commentLandingTarget(readingAnchor.commentId, rootId, timelineView.threadReplies.get(rootId) ?? EMPTY_REPLIES),
offset: readingAnchor.offset, onComplete: completeAnchorRestore,
});
- }, [readingAnchor, scrollContainerEl, issueLoading, timelineLoading, commentTasksLoading, replyToRoot, commentRuns, items, measuredTimelineId, id, timelineView.threadReplies, completeAnchorRestore]);
+ }, [readingAnchor, scrollContainerEl, issueLoading, timelineLoading, commentTasksLoading, replyToRoot, commentRuns, items, timelineSized, timelineView.threadReplies, completeAnchorRestore]);
// Scroll a freshly posted comment into view, aligned so its bottom sits just
// above the sticky composer (never behind it). A reply lives inside its root
// CommentCard, so the containing top-level row is the scroll target.
@@ -2631,8 +2671,9 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
const container = scrollContainerEl;
if (!container) return;
if (targetIdx < 0) return;
- if (measuredTimelineId !== id) {
- // Virtuoso measures nothing while the list is below the viewport.
+ if (!timelineSized) {
+ // Virtuoso measures nothing while the list is below the viewport, and
+ // without height estimates it cannot place the target until it does.
const list = virtualTimelineRef.current;
return list ? revealTimelineList(container, list) : undefined;
}
@@ -2664,7 +2705,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
interruptedLandingRef.current = highlightCommentId;
}
};
- }, [highlightCommentId, highlightTargetId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, measuredTimelineId, timelineLoading, commentTasksLoading, flashJumpTarget]);
+ }, [highlightCommentId, highlightTargetId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, timelineSized, timelineLoading, commentTasksLoading, flashJumpTarget]);
// Land on the comment in-page find stepped to, the way a deep link lands.
useEffect(() => {
@@ -4352,6 +4393,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
customScrollParent={scrollContainerEl}
data={items}
initialScrollTop={readingAnchor ? undefined : restoredScrollTop}
+ heightEstimates={timelineHeightEstimates}
increaseViewportBy={{ top: 800, bottom: 800 }}
totalListHeightChanged={handleTimelineHeightChange}
rangeChanged={handleTimelineRangeChanged}
diff --git a/packages/views/issues/hooks/use-in-page-find.test.ts b/packages/views/issues/hooks/use-in-page-find.test.ts
index 3519bbd33a..2db516b2fd 100644
--- a/packages/views/issues/hooks/use-in-page-find.test.ts
+++ b/packages/views/issues/hooks/use-in-page-find.test.ts
@@ -195,4 +195,29 @@ describe("useInPageFind with virtual content", () => {
expect(result.current.activeIndex).toBe(2);
expect(reveal).toHaveBeenCalledTimes(1);
});
+
+ it("mounts an unmounted first match once typing pauses, not per keystroke", async () => {
+ const units = [{ key: "unmounted", text: "only here: needle" }];
+ const getUnits = () => units;
+ const reveal = vi.fn(() => () => {});
+ const { result } = renderHook(() =>
+ useInPageFind({
+ container,
+ contentKey: 0,
+ virtual: { root: () => virtualRoot, units: getUnits, reveal },
+ }),
+ );
+
+ act(() => result.current.openFind());
+ for (const query of ["ne", "nee", "need", "needl", "needle"]) {
+ act(() => result.current.setQuery(query));
+ await flushFrames(1);
+ }
+ await flushFrames();
+ expect(result.current.matchCount).toBe(1);
+ expect(reveal).not.toHaveBeenCalled();
+
+ await act(() => new Promise<void>((resolve) => setTimeout(resolve, 200)));
+ expect(reveal).toHaveBeenCalledTimes(1);
+ });
});
diff --git a/packages/views/issues/hooks/use-in-page-find.ts b/packages/views/issues/hooks/use-in-page-find.ts
index 40cec13996..5a25b31a95 100644
--- a/packages/views/issues/hooks/use-in-page-find.ts
+++ b/packages/views/issues/hooks/use-in-page-find.ts
@@ -16,6 +16,10 @@ import { isImeComposing } from "@multica/core/utils";
// contenteditable title/description editors without fighting ProseMirror.
const HIGHLIGHT_NAME = "multica-find";
+// While the query is being typed, the first match moves with every keystroke.
+// Mounting each one's comment would mount and drop timeline rows per
+// keystroke, so an unmounted match is brought in once typing pauses.
+const TYPING_REVEAL_DELAY_MS = 150;
const ACTIVE_HIGHLIGHT_NAME = "multica-find-active";
/** Marks the root of a searchable body inside the virtual region. */
@@ -197,6 +201,8 @@ export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options
// DOM ranges of the units that are mounted, by unit index.
const mountedRef = useRef(new Map<number, Range[]>());
const cancelRevealRef = useRef<(() => void) | null>(null);
+ // The next activation follows a query change rather than prev/next.
+ const restartedByQueryRef = useRef(false);
const activeIndexRef = useRef(activeIndex);
activeIndexRef.current = activeIndex;
const supported = highlightApiSupported();
@@ -244,7 +250,7 @@ export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options
// is not in the DOM. Called both when the user navigates and after a
// recompute, so the active tint always tracks live ranges.
const activate = useCallback(
- (index: number, scroll: boolean) => {
+ (index: number, scroll: boolean, { deferReveal = false } = {}) => {
const match = index >= 0 ? matchesRef.current[index] : undefined;
let range: Range | undefined;
let unitElement: HTMLElement | null = null;
@@ -280,17 +286,25 @@ export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options
const unit = unitsRef.current[match.unit];
const reveal = virtualRef.current?.reveal;
if (!unit || !reveal) return;
- const pending = { cancel: () => {}, settled: false };
- pending.cancel = reveal(unit, () => {
- pending.settled = true;
- if (cancelRevealRef.current === pending.cancel) cancelRevealRef.current = null;
- if (activeIndexRef.current !== index) return;
- recomputeRef.current({ resetActive: false });
- const ranges = mountedRef.current.get(match.unit);
- const landed = ranges?.[Math.min(match.occurrence, ranges.length - 1)];
- if (landed) scrollRectIntoView(containerRef.current, rangeRect(landed));
- });
- if (!pending.settled) cancelRevealRef.current = pending.cancel;
+ const start = () => {
+ const pending = { cancel: () => {}, settled: false };
+ pending.cancel = reveal(unit, () => {
+ pending.settled = true;
+ if (cancelRevealRef.current === pending.cancel) cancelRevealRef.current = null;
+ if (activeIndexRef.current !== index) return;
+ recomputeRef.current({ resetActive: false });
+ const ranges = mountedRef.current.get(match.unit);
+ const landed = ranges?.[Math.min(match.occurrence, ranges.length - 1)];
+ if (landed) scrollRectIntoView(containerRef.current, rangeRect(landed));
+ });
+ cancelRevealRef.current = pending.settled ? null : pending.cancel;
+ };
+ if (!deferReveal) {
+ start();
+ return;
+ }
+ const timer = window.setTimeout(start, TYPING_REVEAL_DELAY_MS);
+ cancelRevealRef.current = () => window.clearTimeout(timer);
},
[supported, cancelReveal],
);
@@ -339,6 +353,7 @@ export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options
}
if (resetActive) {
// The activation effect scrolls to it.
+ restartedByQueryRef.current = true;
setActiveIndex(0);
setRestart((n) => n + 1);
return;
@@ -397,7 +412,9 @@ export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options
// for content-driven changes.)
useEffect(() => {
if (!open) return;
- activate(activeIndex, true);
+ const deferReveal = restartedByQueryRef.current;
+ restartedByQueryRef.current = false;
+ activate(activeIndex, true, { deferReveal });
}, [activeIndex, restart, open, activate]);
// Global Cmd/Ctrl+F. The listener is scoped to the mounted issue detail; on
diff --git a/packages/views/issues/utils/timeline-find-units.test.ts b/packages/views/issues/utils/timeline-find-units.test.ts
index 9ed14e02cb..0d7519c090 100644
--- a/packages/views/issues/utils/timeline-find-units.test.ts
+++ b/packages/views/issues/utils/timeline-find-units.test.ts
@@ -2,7 +2,8 @@
import { describe, expect, it } from "vitest";
import type { AgentTask, TimelineEntry } from "@multica/core/types";
import type { CommentRun } from "../components/comment-runs";
-import { buildTimelineFindUnits, type TimelineFindItem, type TimelineFolds } from "./timeline-find-units";
+import { buildTimelineFindUnits } from "./timeline-find-units";
+import type { TimelineFolds, TimelineRowItem } from "./timeline-row-content";
function task(id: string, overrides: Partial<AgentTask> = {}): AgentTask {
return { id, agent_id: "agent", runtime_id: "runtime", issue_id: "issue", status: "completed", priority: 0,
@@ -31,7 +32,7 @@ describe("buildTimelineFindUnits", () => {
const runs = new Map([[root.id, [answered, silent]]]);
it("lists every comment and run output the timeline shows, in reading order", () => {
- const items: TimelineFindItem[] = [
+ const items: TimelineRowItem[] = [
{ kind: "comment", id: root.id, entry: root },
{ kind: "activity-group", id: "activity" },
{ kind: "run", id: standalone.task.id, run: standalone },
@@ -60,7 +61,7 @@ describe("buildTimelineFindUnits", () => {
// A reply that resolved the thread folds the other replies behind a bar.
const resolution = { ...reply, resolved_at: at(9) };
const folded = new Map([[root.id, [resolution, answer]]]);
- const thread: TimelineFindItem[] = [{ kind: "comment", id: root.id, entry: root }];
+ const thread: TimelineRowItem[] = [{ kind: "comment", id: root.id, entry: root }];
expect(keys(buildTimelineFindUnits(thread, folded, new Map(), OPEN))).toEqual(["root", "reply"]);
expect(keys(buildTimelineFindUnits(thread, folded, new Map(),
{ ...OPEN, expandedResolved: new Set([root.id]) }))).toEqual(["root", "reply", "answer"]);
diff --git a/packages/views/issues/utils/timeline-find-units.ts b/packages/views/issues/utils/timeline-find-units.ts
index d4573a2ab9..0481cabb17 100644
--- a/packages/views/issues/utils/timeline-find-units.ts
+++ b/packages/views/issues/utils/timeline-find-units.ts
@@ -1,14 +1,7 @@
import type { TimelineEntry } from "@multica/core/types";
-import { isDeletedComment } from "@multica/core/issues/comment-deletion";
-import { redactSecrets } from "../../common/task-transcript/redact";
-import {
- commentRunOutput,
- isRunFailureNotice,
- orderVisibleThreadRows,
- type CommentRun,
-} from "../components/comment-runs";
-import { deriveThreadResolution } from "../components/thread-utils";
+import type { CommentRun } from "../components/comment-runs";
import { markdownSearchText } from "./markdown-search-text";
+import { timelineRowContent, type TimelineFolds, type TimelineRowItem } from "./timeline-row-content";
/**
* One searchable body in the issue timeline: a comment's Markdown, or the
@@ -25,22 +18,6 @@ export interface TimelineFindUnit {
text: string;
}
-/** The fields of a timeline row this needs; issue-detail's rows satisfy it. */
-export type TimelineFindItem =
- | { kind: "run"; id: string; run: CommentRun; entry?: TimelineEntry }
- | { kind: "comment" | "resolved-bar"; id: string; entry: TimelineEntry }
- | { kind: "activity-group"; id: string };
-
-/** What the reader has folded: resolved threads they opened, threads they collapsed. */
-export interface TimelineFolds {
- expandedResolved: ReadonlySet<string>;
- collapsed: ReadonlySet<string>;
-}
-
-export function runOutputFindKey(taskId: string): string {
- return `run:${taskId}`;
-}
-
/**
* Every comment and run output the timeline shows, in reading order, whether
* or not its row is mounted. In-page find counts these instead of rendering
@@ -49,58 +26,19 @@ export function runOutputFindKey(taskId: string): string {
* did. Activity lines, names and timestamps are not searched.
*/
export function buildTimelineFindUnits(
- items: readonly TimelineFindItem[],
+ items: readonly TimelineRowItem[],
threadReplies: ReadonlyMap<string, readonly TimelineEntry[]>,
commentRuns: ReadonlyMap<string, readonly CommentRun[]>,
folds: TimelineFolds,
): TimelineFindUnit[] {
const units: TimelineFindUnit[] = [];
- const add = (key: string, itemId: string, anchorId: string, markdown: string | null | undefined) => {
- if (!markdown) return;
- const text = markdownSearchText(markdown).toLowerCase();
- if (text.trim()) units.push({ key, itemId, anchorId, text });
- };
- const addRunOutput = (run: CommentRun, itemId: string, anchorId: string) => {
- // A run that replied renders the reply instead of its output.
- const output = run.hasReply ? null : commentRunOutput(run.task);
- if (output) add(runOutputFindKey(run.task.id), itemId, anchorId, redactSecrets(output));
- };
- // A thread card (CommentCard): its root's body, then its open rows.
- const addThread = (itemId: string, root: TimelineEntry) => {
- if (folds.collapsed.has(root.id)) return;
- const replies = [...(threadReplies.get(root.id) ?? [])];
- const runs = commentRuns.get(root.id) ?? [];
- // A failure notice heading its thread shows as the run's block instead.
- const notice = runs.some((run) => run.hasReply && run.commentId === root.id && isRunFailureNotice(root, run.task));
- if (!isDeletedComment(root) && !notice) add(root.id, itemId, itemId, root.content);
- const resolution = deriveThreadResolution(root, replies);
- const foldedTo = resolution.kind === "reply" && !folds.expandedResolved.has(root.id) ? resolution.resolutionId : null;
- for (const row of orderVisibleThreadRows(root, replies, runs, foldedTo)) {
- if (!("run" in row)) {
- if (!isDeletedComment(row)) add(row.id, itemId, row.id, row.content);
- continue;
- }
- const reply = row.reply && !isDeletedComment(row.reply) && !isRunFailureNotice(row.reply, row.run.task)
- ? row.reply : undefined;
- if (reply) add(reply.id, itemId, reply.id, reply.content);
- else addRunOutput(row.run, itemId, row.run.task.id);
- }
- };
-
for (const item of items) {
- if (item.kind === "comment") addThread(item.id, item.entry);
- if (item.kind !== "run") continue;
- const reply = item.entry;
- if (!reply) {
- addRunOutput(item.run, item.id, item.id);
- continue;
+ const content = timelineRowContent(item, threadReplies, commentRuns, folds);
+ if (content.shape !== "thread" && content.shape !== "run") continue;
+ for (const body of content.bodies) {
+ const text = markdownSearchText(body.markdown).toLowerCase();
+ if (text.trim()) units.push({ key: body.key, itemId: item.id, anchorId: body.anchorId, text });
}
- // Folded behind its resolution bar.
- if (reply.resolved_at && !folds.expandedResolved.has(reply.id)) continue;
- // A notice nobody replied to shows as the run's block, without output.
- if (isRunFailureNotice(reply, item.run.task)
- && !(threadReplies.get(reply.id) ?? []).some((entry) => !isDeletedComment(entry))) continue;
- addThread(item.id, reply);
}
return units;
}
diff --git a/packages/views/issues/utils/timeline-height-estimates.test.ts b/packages/views/issues/utils/timeline-height-estimates.test.ts
new file mode 100644
index 0000000000..3a3f2f6015
--- /dev/null
+++ b/packages/views/issues/utils/timeline-height-estimates.test.ts
@@ -0,0 +1,83 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { AgentTask, TimelineEntry } from "@multica/core/types";
+import type { CommentRun } from "../components/comment-runs";
+import {
+ estimateMarkdownHeight,
+ estimateTimelineItemHeights,
+ timelineCharsPerLine,
+} from "./timeline-height-estimates";
+import type { TimelineFolds, TimelineRowItem } from "./timeline-row-content";
+
+function comment(id: string, content: string, overrides: Partial<TimelineEntry> = {}): TimelineEntry {
+ return { id, type: "comment", actor_type: "member", actor_id: "user", created_at: "2026-09-07T00:00:00Z", content, ...overrides };
+}
+const OPEN: TimelineFolds = { expandedResolved: new Set(), collapsed: new Set() };
+const options = { charsPerLine: 80, activityLines: () => 0 };
+
+describe("estimateMarkdownHeight", () => {
+ it("wraps prose at the column width", () => {
+ const short = estimateMarkdownHeight("a".repeat(80), 80);
+ expect(estimateMarkdownHeight("a".repeat(240), 80)).toBeGreaterThan(2.5 * short - 13);
+ expect(estimateMarkdownHeight("a".repeat(240), 160)).toBeLessThan(estimateMarkdownHeight("a".repeat(240), 80));
+ });
+
+ it("counts code, table and heading lines without wrapping them as prose", () => {
+ const code = estimateMarkdownHeight(["```ts", ...Array(10).fill("x".repeat(200)), "```"].join("\n"), 80);
+ const prose = estimateMarkdownHeight(Array(10).fill("x".repeat(200)).join("\n"), 80);
+ expect(code).toBeLessThan(prose);
+ // The delimiter row is not a row.
+ expect(estimateMarkdownHeight("| a | b |\n| --- | --- |\n| 1 | 2 |", 80))
+ .toBe(estimateMarkdownHeight("| a | b |\n| 1 | 2 |", 80));
+ });
+});
+
+describe("estimateTimelineItemHeights", () => {
+ const long = Array(40).fill("A long agent reply paragraph that wraps over a couple of lines at most widths.").join("\n\n");
+ const root = comment("root", "Question");
+ const reply = comment("reply", long, { parent_id: root.id, created_at: "2026-09-07T00:01:00Z" });
+ const replies = new Map([[root.id, [reply]]]);
+
+ it("sizes a thread by its content and an activity line as a line", () => {
+ const items: TimelineRowItem[] = [
+ { kind: "activity-group", id: "activity" },
+ { kind: "comment", id: root.id, entry: root },
+ ];
+ const [activity, thread] = estimateTimelineItemHeights(items, replies, new Map(), OPEN, options);
+ expect(activity).toBeLessThan(50);
+ expect(thread).toBeGreaterThan(40 * 30);
+ });
+
+ it("grows an open activity block with its lines", () => {
+ const items: TimelineRowItem[] = [{ kind: "activity-group", id: "activity" }];
+ const [collapsed] = estimateTimelineItemHeights(items, new Map(), new Map(), OPEN, options);
+ const [open] = estimateTimelineItemHeights(items, new Map(), new Map(), OPEN, { ...options, activityLines: () => 5 });
+ expect(open).toBeGreaterThan(collapsed! + 100);
+ });
+
+ it("sizes a folded thread by what stays on screen", () => {
+ const thread: TimelineRowItem[] = [{ kind: "comment", id: root.id, entry: root }];
+ const [collapsed] = estimateTimelineItemHeights(thread, replies, new Map(), { ...OPEN, collapsed: new Set([root.id]) }, options);
+ const [bar] = estimateTimelineItemHeights([{ kind: "resolved-bar", id: root.id, entry: root }], replies, new Map(), OPEN, options);
+ expect(collapsed).toBeLessThan(100);
+ expect(bar).toBeLessThan(100);
+ });
+
+ it("adds a run's output to its block", () => {
+ const task = { id: "run", status: "completed", result: { comment: long } } as unknown as AgentTask;
+ const run: CommentRun = { task, hasReply: false };
+ const [withOutput] = estimateTimelineItemHeights([{ kind: "run", id: "run", run }], new Map(), new Map(), OPEN, options);
+ const [plain] = estimateTimelineItemHeights([{ kind: "run", id: "run", run: { ...run, task: { ...task, result: null } } }],
+ new Map(), new Map(), OPEN, options);
+ expect(plain).toBeLessThan(100);
+ expect(withOutput).toBeGreaterThan(plain! + 40 * 30);
+ });
+});
+
+describe("timelineCharsPerLine", () => {
+ it("follows the column width up to the reading column's cap", () => {
+ expect(timelineCharsPerLine(756)).toBeGreaterThan(timelineCharsPerLine(416));
+ expect(timelineCharsPerLine(4000)).toBe(timelineCharsPerLine(3000));
+ expect(timelineCharsPerLine(0)).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/views/issues/utils/timeline-height-estimates.ts b/packages/views/issues/utils/timeline-height-estimates.ts
new file mode 100644
index 0000000000..187c543635
--- /dev/null
+++ b/packages/views/issues/utils/timeline-height-estimates.ts
@@ -0,0 +1,122 @@
+import type { TimelineEntry } from "@multica/core/types";
+import type { CommentRun } from "../components/comment-runs";
+import { timelineRowContent, type TimelineFolds, type TimelineRowItem } from "./timeline-row-content";
+
+/**
+ * Estimated rendered height of each timeline row, for Virtuoso's
+ * `heightEstimates` (MUL-9538).
+ *
+ * Without them Virtuoso sizes every unmeasured row like the first one it
+ * measures — on an issue page usually a 30px activity line, while a thread is
+ * thousands of pixels. Opening a notification deep in a long issue then
+ * jumps to "row 32 × 30px", fills the viewport with the dozens of threads it
+ * believes fit there, measures them, and only then finds the target: one main
+ * thread task that mounted most of the history. Estimates from content put
+ * the jump near the target, so only its neighbourhood mounts.
+ *
+ * Constants were fitted against rendered comments (14px body text, 22.75px
+ * lines plus paragraph spacing): within about ±10% for prose, lists, tables
+ * and code. Being off only costs extra render passes, never correctness:
+ * measured heights replace estimates as rows render.
+ */
+
+const LINE = 26;
+const CODE_LINE = 21;
+const FENCE = 16;
+const TABLE_ROW = 41;
+const HEADING = 34;
+const BLOCK_GAP = 12;
+/** Average glyph width of body text, for turning the column width into characters per line. */
+const CHAR_WIDTH = 7.5;
+/** The reading column's horizontal chrome: card padding and the comment's indent. */
+const COLUMN_INSET = 98;
+/** Body width at which the reading column stops growing. */
+const MAX_BODY_WIDTH = 800;
+
+const ACTIVITY_LINE = 30;
+const ACTIVITY_ENTRY = 28;
+const RESOLVED_BAR = 56;
+const COLLAPSED_THREAD = 70;
+const THREAD_FRAME = 30;
+const THREAD_ROW = 75;
+const RUN_BLOCK = 70;
+
+/** Characters per rendered line for a timeline in a scroll container `width` px wide. */
+export function timelineCharsPerLine(width: number): number {
+ return Math.max(30, Math.round(Math.min(width - COLUMN_INSET, MAX_BODY_WIDTH) / CHAR_WIDTH));
+}
+
+const cache = new Map<string, number>();
+const MAX_CACHED = 4_000;
+
+/** Rendered height of a Markdown body, from its lines. Cached per content and width. */
+export function estimateMarkdownHeight(markdown: string, charsPerLine: number): number {
+ const key = `${charsPerLine}:${markdown}`;
+ const cached = cache.get(key);
+ if (cached !== undefined) return cached;
+ let height = 0;
+ let inFence = false;
+ let blockStart = true;
+ for (const line of markdown.split("\n")) {
+ const text = line.trim();
+ if (/^(`{3,}|~{3,})/.test(text)) {
+ inFence = !inFence;
+ height += FENCE;
+ continue;
+ }
+ if (inFence) {
+ height += CODE_LINE;
+ continue;
+ }
+ if (!text) {
+ blockStart = true;
+ continue;
+ }
+ if (blockStart) height += BLOCK_GAP;
+ blockStart = false;
+ if (text.startsWith("|")) {
+ if (!/^\|?\s*:?-+/.test(text)) height += TABLE_ROW;
+ } else if (text.startsWith("#")) {
+ height += HEADING;
+ } else {
+ height += Math.max(1, Math.ceil(text.length / charsPerLine)) * LINE;
+ }
+ }
+ cache.set(key, height);
+ if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value!);
+ return height;
+}
+
+export function estimateTimelineItemHeights(
+ items: readonly TimelineRowItem[],
+ threadReplies: ReadonlyMap<string, readonly TimelineEntry[]>,
+ commentRuns: ReadonlyMap<string, readonly CommentRun[]>,
+ folds: TimelineFolds,
+ options: {
+ charsPerLine: number;
+ /** Lines an activity block shows; 0 when it is folded to its count. */
+ activityLines: (itemId: string) => number;
+ },
+): number[] {
+ return items.map((item) => {
+ const content = timelineRowContent(item, threadReplies, commentRuns, folds);
+ switch (content.shape) {
+ case "activity":
+ return ACTIVITY_LINE + options.activityLines(item.id) * ACTIVITY_ENTRY;
+ case "resolved-bar":
+ return RESOLVED_BAR;
+ case "collapsed-thread":
+ return COLLAPSED_THREAD;
+ case "thread":
+ return content.bodies.reduce(
+ (sum, body) => sum + THREAD_ROW + estimateMarkdownHeight(body.markdown, options.charsPerLine),
+ THREAD_FRAME,
+ );
+ case "run":
+ return content.bodies.reduce(
+ (sum, body) => sum + estimateMarkdownHeight(body.markdown, options.charsPerLine),
+ RUN_BLOCK,
+ );
+ }
+ });
+}
diff --git a/packages/views/issues/utils/timeline-row-content.ts b/packages/views/issues/utils/timeline-row-content.ts
new file mode 100644
index 0000000000..a335bc3efc
--- /dev/null
+++ b/packages/views/issues/utils/timeline-row-content.ts
@@ -0,0 +1,109 @@
+import type { TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
+import { redactSecrets } from "../../common/task-transcript/redact";
+import {
+ commentRunOutput,
+ isRunFailureNotice,
+ orderVisibleThreadRows,
+ type CommentRun,
+} from "../components/comment-runs";
+import { deriveThreadResolution } from "../components/thread-utils";
+
+/** The fields of a timeline row this needs; issue-detail's rows satisfy it. */
+export type TimelineRowItem =
+ | { kind: "run"; id: string; run: CommentRun; entry?: TimelineEntry }
+ | { kind: "comment"; id: string; entry: TimelineEntry }
+ | { kind: "resolved-bar"; id: string; entry: TimelineEntry }
+ | { kind: "activity-group"; id: string };
+
+/** What the reader has folded: resolved threads they opened, threads they collapsed. */
+export interface TimelineFolds {
+ expandedResolved: ReadonlySet<string>;
+ collapsed: ReadonlySet<string>;
+}
+
+/** A Markdown body a row renders: a comment, or the output of a run that posted none. */
+export interface TimelineRowBody {
+ /** The comment id, or {@link runOutputKey} for a run's output. */
+ key: string;
+ /** `comment-<anchorId>` brings the body into the DOM, as a deep link does. */
+ anchorId: string;
+ markdown: string;
+}
+
+/**
+ * What a timeline row shows, from data, for work that must not mount it:
+ * in-page find's index and the list's height estimates. It mirrors what
+ * renders, so a folded or collapsed thread contributes only what stays on
+ * screen.
+ */
+export type TimelineRowContent =
+ | { shape: "activity" }
+ | { shape: "resolved-bar" }
+ | { shape: "collapsed-thread" }
+ | { shape: "thread"; bodies: TimelineRowBody[] }
+ | { shape: "run"; bodies: TimelineRowBody[] };
+
+export function runOutputKey(taskId: string): string {
+ return `run:${taskId}`;
+}
+
+function runOutputBody(run: CommentRun, anchorId: string): TimelineRowBody[] {
+ // A run that replied renders the reply instead of its output.
+ const output = run.hasReply ? null : commentRunOutput(run.task);
+ return output ? [{ key: runOutputKey(run.task.id), anchorId, markdown: redactSecrets(output) }] : [];
+}
+
+// A thread card (CommentCard): its root's body, then its open rows.
+function threadContent(
+ itemId: string,
+ root: TimelineEntry,
+ threadReplies: ReadonlyMap<string, readonly TimelineEntry[]>,
+ commentRuns: ReadonlyMap<string, readonly CommentRun[]>,
+ folds: TimelineFolds,
+): TimelineRowContent {
+ if (folds.collapsed.has(root.id)) return { shape: "collapsed-thread" };
+ const bodies: TimelineRowBody[] = [];
+ const add = (key: string, anchorId: string, markdown: string | null | undefined) => {
+ if (markdown) bodies.push({ key, anchorId, markdown });
+ };
+ const replies = [...(threadReplies.get(root.id) ?? [])];
+ const runs = commentRuns.get(root.id) ?? [];
+ // A failure notice heading its thread shows as the run's block instead.
+ const notice = runs.some((run) => run.hasReply && run.commentId === root.id && isRunFailureNotice(root, run.task));
+ if (!isDeletedComment(root) && !notice) add(root.id, itemId, root.content);
+ const resolution = deriveThreadResolution(root, replies);
+ const foldedTo = resolution.kind === "reply" && !folds.expandedResolved.has(root.id) ? resolution.resolutionId : null;
+ for (const row of orderVisibleThreadRows(root, replies, runs, foldedTo)) {
+ if (!("run" in row)) {
+ if (!isDeletedComment(row)) add(row.id, row.id, row.content);
+ continue;
+ }
+ const reply = row.reply && !isDeletedComment(row.reply) && !isRunFailureNotice(row.reply, row.run.task)
+ ? row.reply : undefined;
+ if (reply) add(reply.id, reply.id, reply.content);
+ else bodies.push(...runOutputBody(row.run, row.run.task.id));
+ }
+ return { shape: "thread", bodies };
+}
+
+export function timelineRowContent(
+ item: TimelineRowItem,
+ threadReplies: ReadonlyMap<string, readonly TimelineEntry[]>,
+ commentRuns: ReadonlyMap<string, readonly CommentRun[]>,
+ folds: TimelineFolds,
+): TimelineRowContent {
+ if (item.kind === "activity-group") return { shape: "activity" };
+ if (item.kind === "resolved-bar") return { shape: "resolved-bar" };
+ if (item.kind === "comment") return threadContent(item.id, item.entry, threadReplies, commentRuns, folds);
+ const reply = item.entry;
+ if (!reply) return { shape: "run", bodies: runOutputBody(item.run, item.id) };
+ // Folded behind its resolution bar.
+ if (reply.resolved_at && !folds.expandedResolved.has(reply.id)) return { shape: "resolved-bar" };
+ // A notice nobody replied to shows as the run's block, without output.
+ if (isRunFailureNotice(reply, item.run.task)
+ && !(threadReplies.get(reply.id) ?? []).some((entry) => !isDeletedComment(entry))) {
+ return { shape: "run", bodies: [] };
+ }
+ return threadContent(item.id, reply, threadReplies, commentRuns, folds);
+}