Skip to content

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

Go

perf(issues): find in a long issue without rendering its history (MUL-9538) (#10860)

Jiayuan Zhangcf3709212613
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 30ba716605..34243c1d7a 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -60,7 +60,7 @@ import { CommentsFoldBar } from "./resolved-thread-bar";
import { deriveThreadResolution } from "./thread-utils";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { InlineCommentRun, PlacedInlineCommentRun, useInlineCommentRunState, type InlineCommentRunState } from "./inline-comment-run";
-import { EMPTY_COMMENT_RUNS, isRunFailureNotice, orderThreadWithRuns, type CommentRun, type ThreadRunSlot } from "./comment-runs";
+import { EMPTY_COMMENT_RUNS, isRunFailureNotice, orderVisibleThreadRows, type CommentRun, type ThreadRunSlot } from "./comment-runs";
import { descriptionPreview } from "./description-preview";
import { useCommentAnnotations } from "./use-comment-annotations";
import { useAttachmentVersions } from "./deliverables/attachment-versions";
@@ -1016,7 +1016,7 @@ function CommentRow({
<>
<div tabIndex={currentUserId ? 0 : undefined} role="group"
aria-label={t(($) => $.reply.annotations.source_label, { name: entry.actor_name || getActorName(entry.actor_type, entry.actor_id) })}
- data-comment-content={entry.id} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body leading-relaxed text-foreground">
+ data-comment-content={entry.id} data-find-unit={entry.id} className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 text-body leading-relaxed text-foreground">
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-12 pr-4 max-md:pl-3 max-md:pr-3" />
@@ -1342,15 +1342,9 @@ function CommentCardImpl({
const foldedReplies = replyResolutionId
? visibleReplies.filter((r) => r.id !== replyResolutionId)
: visibleReplies;
- const resolutionReply = replyResolutionId
- ? allNestedReplies.find((r) => r.id === replyResolutionId) ?? null
- : null;
// Replies and run slots in the order they happened (MUL-7628). Folded, the
// resolution stays visible along with any run that has not replied yet.
- const threadRows = replyFolded
- ? orderThreadWithRuns(entry, resolutionReply ? [resolutionReply] : [], runs.filter((run) => !run.hasReply
- && (run.anchorCommentId === entry.id || run.anchorCommentId === replyResolutionId)))
- : orderThreadWithRuns(entry, allNestedReplies, runs);
+ const threadRows = orderVisibleThreadRows(entry, allNestedReplies, runs, replyFolded ? replyResolutionId : null);
// Long threads mount replies on demand: many rows, or few rows carrying a
// lot of Markdown (MUL-9409). Short threads render inline, but through the
@@ -1632,7 +1626,7 @@ function CommentCardImpl({
<>
<div tabIndex={currentUserId ? 0 : undefined} role="group"
aria-label={t(($) => $.reply.annotations.source_label, { name: entry.actor_name || getActorName(entry.actor_type, entry.actor_id) })}
- data-comment-content={entry.id} className="pl-8 max-md:pl-0 text-body leading-relaxed text-foreground">
+ data-comment-content={entry.id} data-find-unit={entry.id} className="pl-8 max-md:pl-0 text-body leading-relaxed text-foreground">
<ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} />
</div>
<AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8 max-md:pl-0" />
diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.ts
index 36e5ddc508..2c71ee0ca7 100644
--- a/packages/views/issues/components/comment-runs.ts
+++ b/packages/views/issues/components/comment-runs.ts
@@ -263,6 +263,23 @@ export function orderTimelineWithRuns(
});
}
+/**
+ * The rows an open thread shows. Folded behind the reply that resolved it
+ * (`foldedTo`), only that reply stays, with any run still working on the root
+ * or on it; otherwise every reply and run, in reading order.
+ */
+export function orderVisibleThreadRows(
+ root: TimelineEntry,
+ replies: readonly TimelineEntry[],
+ runs: readonly CommentRun[],
+ foldedTo: string | null,
+): (TimelineEntry | ThreadRunSlot)[] {
+ if (!foldedTo) return orderThreadWithRuns(root, replies, runs);
+ const resolution = replies.find((reply) => reply.id === foldedTo);
+ return orderThreadWithRuns(root, resolution ? [resolution] : [], runs.filter((run) => !run.hasReply
+ && (run.anchorCommentId === root.id || run.anchorCommentId === foldedTo)));
+}
+
/** A run's slot in a thread. */
export interface ThreadRunSlot {
run: CommentRun;
diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsx
index 1a650225fb..1027179741 100644
--- a/packages/views/issues/components/inline-comment-run.tsx
+++ b/packages/views/issues/components/inline-comment-run.tsx
@@ -24,6 +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 { ReadonlyContent } from "../../editor";
import { useLocale, useT, useTimeAgo } from "../../i18n";
import { formatDuration } from "../../agents/components/agent-activity-hover-content";
@@ -233,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"><ReadonlyContent content={redactSecrets(output)} /></div>}
+ {output && <div className="mt-2 text-body" data-find-unit={runOutputFindKey(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 a016e59471..bc545a37e7 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1036,6 +1036,37 @@ describe("IssueDetail (shared)", () => {
await waitFor(() => expect(scrollIntoViewIndexSpy.mock.calls.length).toBeGreaterThan(jumps));
});
+ it("finds text in comments the timeline has not mounted, without mounting the history (MUL-9538)", async () => {
+ mockVirtualWindow.enabled = true;
+ const history = Array.from({ length: 40 }, (_, index) => ({
+ ...mockTimeline[0]!, id: `history-${index}`, parent_id: null, source_task_id: undefined,
+ content: index === 30 ? "The **needle** is in this one" : `Historical comment ${index}`,
+ created_at: new Date(Date.UTC(2026, 0, 1, 0, index)).toISOString(),
+ }));
+ mockApiObj.listTimeline.mockResolvedValue(history);
+ mockApiObj.listTasksByIssue.mockResolvedValue([]);
+ // 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);
+ try {
+ renderIssueDetail();
+ await screen.findByText("Historical comment 0");
+
+ fireEvent.keyDown(document, { key: "f", code: "KeyF", ctrlKey: true });
+ fireEvent.change(await screen.findByRole("textbox", { name: "Find in issue..." }), { target: { value: "needle" } });
+
+ // Counted from the comment's Markdown while it is not mounted.
+ await waitFor(() => expect(screen.getByRole("search")).toHaveTextContent("1/1"));
+ // Landing on it mounts that comment, not the history before it.
+ await waitFor(() => expect(scrollIntoViewIndexSpy).toHaveBeenCalledWith(expect.objectContaining({ index: 30 })));
+ await waitFor(() => expect(document.getElementById("comment-history-30")).not.toBeNull());
+ expect(document.querySelectorAll('[id^="comment-history-"]').length).toBeLessThanOrEqual(8);
+ expect(screen.getByTestId("virtuoso-mock")).toBeInTheDocument();
+ } finally {
+ rects.mockRestore();
+ }
+ });
+
it("opens source-context creation from both a root comment and a reply", async () => {
mockApiObj.listTimeline.mockResolvedValue([
{ ...mockTimeline[0], id: "source-root", parent_id: null },
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index ec7f21a2ab..bba03b2761 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -214,6 +214,7 @@ import { useT } from "../../i18n";
import { useIssueDetailScrollRestore } from "../hooks/use-issue-detail-scroll-restore";
import { useIssueTimelineAnchor } from "../hooks/use-issue-timeline-anchor";
import { scrollToTimelineComment } from "../utils/scroll-to-timeline-comment";
+import { buildTimelineFindUnits, type TimelineFindUnit } from "../utils/timeline-find-units";
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";
@@ -659,6 +660,8 @@ function JumpToLatestButton({
);
}
+const EMPTY_COLLAPSED_IDS: string[] = [];
+
// Flat per-item shape consumed by <Virtuoso>. Virtuoso needs a flat array
// where each entry is one rendered row; we keep the grouping logic from
// `timelineView.groups` (consecutive same-actor activities still collapse
@@ -1972,14 +1975,33 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
[timelineView.groups, expandedResolved],
);
- // In-page find (Cmd/Ctrl+F). `items.length` is the content signal that
- // triggers a match recompute when comments are added/removed; text edits
- // are caught by the hook's own MutationObserver. Opening find forces the
- // timeline to render flat below so every comment is in the DOM to match.
+ // In-page find (Cmd/Ctrl+F). The timeline stays virtualized while the bar is
+ // open: comments are counted from their Markdown, and stepping to one that
+ // is not mounted lands on it the way a deep link does (MUL-9538). Rendering
+ // the whole history to search its DOM blocked the page for seconds.
+ const virtuosoRef = useRef<VirtuosoHandle>(null);
+ const virtualTimelineRef = useRef<HTMLDivElement>(null);
+ const collapsedThreadIds = useCommentCollapseStore((s) => s.collapsedByIssue[id] ?? EMPTY_COLLAPSED_IDS);
+ const findUnits = useMemo(() => {
+ let built: TimelineFindUnit[] | null = null;
+ const folds = { expandedResolved, collapsed: new Set(collapsedThreadIds) };
+ return () => (built ??= buildTimelineFindUnits(items, timelineView.threadReplies, commentRuns, folds));
+ }, [items, timelineView.threadReplies, commentRuns, expandedResolved, collapsedThreadIds]);
+ const [findReveal, setFindReveal] = useState<{ unit: TimelineFindUnit; done: () => void } | null>(null);
+ const revealFindUnit = useCallback((unit: TimelineFindUnit, done: () => void) => {
+ const request = { unit, done };
+ setFindReveal(request);
+ return () => setFindReveal((current) => (current === request ? null : current));
+ }, []);
const find = useInPageFind({
container: scrollContainerEl,
contentKey: items.length,
enabled: !!issue,
+ virtual: {
+ root: () => virtualTimelineRef.current,
+ units: findUnits,
+ reveal: revealFindUnit,
+ },
});
// Close the bar (and drop highlights) when navigating to another issue —
// the web route reuses this component instead of remounting.
@@ -2082,11 +2104,6 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
[items, timelineView.threadReplies],
);
- // When in-page find renders the timeline flat, there is no
- // Virtuoso instance — minimap jumps drive the scroll container directly.
- const isFlatTimeline = find.open;
- const virtuosoRef = useRef<VirtuosoHandle>(null);
- const virtualTimelineRef = useRef<HTMLDivElement>(null);
const [measuredTimelineId, setMeasuredTimelineId] = useState<string | null>(null);
const handleTimelineHeightChange = useCallback((height: number) => {
if (height > 0) setMeasuredTimelineId(id);
@@ -2107,7 +2124,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
// a screen away.
const jumpToLatest = useJumpToLatest(scrollContainerEl, {
nearTopOnly: isMobile,
- tailPending: !isFlatTimeline && timelineTail.issueId === id && timelineTail.pending,
+ tailPending: timelineTail.issueId === id && timelineTail.pending,
});
// Keyed to `away`, not `visible`: mobile hides the button past the top of
// the page, but the reader has not reached the new comments there.
@@ -2139,31 +2156,27 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
}
const index = items.findIndex((item) => item.id === rootId);
if (index < 0) { completeAnchorRestore(); return; }
- if (!isFlatTimeline && measuredTimelineId !== id) {
+ if (measuredTimelineId !== id) {
const list = virtualTimelineRef.current;
if (list) container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;
return;
}
return scrollToTimelineComment({
- container, virtualizer: isFlatTimeline ? null : virtuosoRef.current, index,
+ container, virtualizer: virtuosoRef.current, index,
commentId: commentLandingTarget(readingAnchor.commentId, rootId, timelineView.threadReplies.get(rootId) ?? EMPTY_REPLIES),
offset: readingAnchor.offset, onComplete: completeAnchorRestore,
});
- }, [readingAnchor, scrollContainerEl, issueLoading, timelineLoading, commentTasksLoading, replyToRoot, commentRuns, items, isFlatTimeline, measuredTimelineId, id, timelineView.threadReplies, completeAnchorRestore]);
+ }, [readingAnchor, scrollContainerEl, issueLoading, timelineLoading, commentTasksLoading, replyToRoot, commentRuns, items, measuredTimelineId, id, 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. Flat and
- // virtualized timelines need separate scroll drivers, so they split into two
- // effects below — kept apart because only the flat one depends on
- // `scrollContainerEl`, and adding that dep to the virtualized effect would
- // let a container re-measure cancel its in-flight scroll mid-flight.
-
- // Virtualized mode: Virtuoso owns the scroll. The first jump materializes the
- // row at its estimated height; once measured, the repeat aligns using the
- // real height. The extra `offset` lifts the row's bottom clear of the sticky
- // composer.
+ // CommentCard, so the containing top-level row is the scroll target.
+ // Virtuoso owns the scroll. The first jump materializes the row at its
+ // estimated height; once measured, the repeat aligns using the real height.
+ // The extra `offset` lifts the row's bottom clear of the sticky composer.
+ // `scrollContainerEl` stays out of the deps: a container re-measure would
+ // cancel the scroll mid-flight.
useEffect(() => {
- if (!pendingPostedCommentId || isFlatTimeline) return;
+ if (!pendingPostedCommentId) return;
const rootId = replyToRoot.get(pendingPostedCommentId) ?? pendingPostedCommentId;
const index = items.findIndex((item) => item.id === rootId);
if (index < 0) return;
@@ -2183,40 +2196,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
cancelAnimationFrame(frame);
if (timer !== undefined) window.clearTimeout(timer);
};
- }, [pendingPostedCommentId, items, replyToRoot, isFlatTimeline]);
-
- // Flat mode (find bar) has no Virtuoso, so drive scrollTop by
- // hand: align the row's bottom to the composer's top edge. The comment's
- // async layout (markdown, code highlight, images) keeps shifting its height,
- // so re-align each frame until it settles (within 1px) or ~0.5s elapses — the
- // same rAF stabilization the deep-link landing uses.
- useEffect(() => {
- if (!pendingPostedCommentId || !isFlatTimeline) return;
- const rootId = replyToRoot.get(pendingPostedCommentId) ?? pendingPostedCommentId;
- if (items.findIndex((item) => item.id === rootId) < 0) return;
- let rafId = 0;
- let frames = 0;
- let last = -1;
- const alignBottom = () => {
- const el = document.getElementById(`comment-${rootId}`);
- const container = scrollContainerEl;
- if (el && container) {
- const c = container.getBoundingClientRect();
- const e = el.getBoundingClientRect();
- const composerHeight = composerRef.current?.getBoundingClientRect().height ?? 0;
- const target = Math.max(0, container.scrollTop + (e.bottom - c.bottom) + composerHeight);
- container.scrollTop = target;
- if (Math.abs(target - last) > 1 && ++frames < 30) {
- last = target;
- rafId = requestAnimationFrame(alignBottom);
- return;
- }
- }
- setPendingPostedCommentId(null);
- };
- rafId = requestAnimationFrame(alignBottom);
- return () => cancelAnimationFrame(rafId);
- }, [pendingPostedCommentId, items, replyToRoot, isFlatTimeline, scrollContainerEl]);
+ }, [pendingPostedCommentId, items, replyToRoot]);
const jumpFlashTimerRef = useRef<number | null>(null);
useEffect(
() => () => {
@@ -2232,8 +2212,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
if (jumpFlashTimerRef.current !== null) window.clearTimeout(jumpFlashTimerRef.current);
jumpFlashTimerRef.current = window.setTimeout(() => setHighlightedId(null), duration);
}, []);
- // Jump to a mounted comment: any row in flat mode, or a reply inside a
- // rendered thread. Drive the container's scrollTop directly — never native
+ // Jump to a mounted comment, such as a reply inside a rendered thread. Drive the container's scrollTop directly — never native
// scrollIntoView, which also scrolls the desktop shell (#3929).
const jumpToComment = useCallback(
(commentId: string) => {
@@ -2249,16 +2228,14 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
);
const jumpToThread = useCallback(
(threadId: string) => {
- // Flat mode mounts every row, so the anchor is always in the DOM.
- if (isFlatTimeline) return jumpToComment(threadId);
- // Virtualized mode: the target row may not be mounted, so scroll by
- // index and let Virtuoso mount it. Offset leaves a small top gap.
+ // The target row may not be mounted, so scroll by index and let
+ // Virtuoso mount it. Offset leaves a small top gap.
const index = items.findIndex((it) => it.id === threadId);
if (index < 0) return;
virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
flashJumpTarget(threadId);
},
- [isFlatTimeline, items, jumpToComment, flashJumpTarget],
+ [items, flashJumpTarget],
);
// Minimap jump to a reply. A reply's anchor exists only while its thread is
// open, so first undo whatever hides it — the reader's own collapse, a root
@@ -2281,10 +2258,10 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
toggleResolvedExpand(rootId, true);
}
}
- if (!isFlatTimeline) virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
+ virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
setPendingReplyJump({ replyId, rootId });
},
- [id, items, replyToRoot, expandedResolved, timelineView.threadReplies, toggleResolvedExpand, isFlatTimeline],
+ [id, items, replyToRoot, expandedResolved, timelineView.threadReplies, toggleResolvedExpand],
);
// Land the pending reply once its row is in the DOM. The expansion commits
// on the next render and Virtuoso mounts the thread a frame or two later, so
@@ -2380,10 +2357,10 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
) {
toggleResolvedExpand(root.id, true);
}
- if (!isFlatTimeline) virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
+ virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
setPendingRunJump({ taskId, rootId: rootItem.id, flashId: run.hasReply && run.commentId ? run.commentId : taskId });
},
- [id, items, commentRuns, expandedResolved, timelineView.threadReplies, toggleResolvedExpand, isFlatTimeline],
+ [id, items, commentRuns, expandedResolved, timelineView.threadReplies, toggleResolvedExpand],
);
// Same frame-by-frame landing as a reply jump. A run that has replied may
// only show as a log button in its comment's header, so align that comment.
@@ -2641,21 +2618,19 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
);
const container = scrollContainerEl;
if (!container) return;
- if (!isFlatTimeline) {
- if (targetIdx < 0) return;
- if (measuredTimelineId !== id) {
- // A long description can put the whole list below the scroll viewport.
- // Bring its probe row into view so Virtuoso can measure before jumping.
- const list = virtualTimelineRef.current;
- if (list) container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;
- return;
- }
+ if (targetIdx < 0) return;
+ if (measuredTimelineId !== id) {
+ // A long description can put the whole list below the scroll viewport.
+ // Bring its probe row into view so Virtuoso can measure before jumping.
+ const list = virtualTimelineRef.current;
+ if (list) container.scrollTop += list.getBoundingClientRect().top - container.getBoundingClientRect().top;
+ return;
}
interruptedLandingRef.current = null;
let completed = false;
const cancel = scrollToTimelineComment({
- container, virtualizer: isFlatTimeline ? null : virtuosoRef.current,
+ container, virtualizer: virtuosoRef.current,
index: targetIdx, commentId: landingId,
onMounted: () => {
didHighlightRef.current = highlightCommentId;
@@ -2678,7 +2653,26 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
interruptedLandingRef.current = highlightCommentId;
}
};
- }, [highlightCommentId, highlightTargetId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, isFlatTimeline, measuredTimelineId, timelineLoading, commentTasksLoading, flashJumpTarget]);
+ }, [highlightCommentId, highlightTargetId, highlightRequestToken, activeDeliverableJump, id, writeViewState, items, targetIdx, scrollContainerEl, highlightRootId, expandedResolved, timelineView, toggleResolvedExpand, measuredTimelineId, timelineLoading, commentTasksLoading, flashJumpTarget]);
+
+ // Land on the comment in-page find stepped to, the way a deep link lands.
+ useEffect(() => {
+ const container = scrollContainerEl;
+ if (!findReveal || !container) return;
+ const index = items.findIndex((it) => it.id === findReveal.unit.itemId);
+ const finish = () => {
+ setFindReveal((current) => (current === findReveal ? null : current));
+ findReveal.done();
+ };
+ if (index < 0) {
+ finish();
+ return;
+ }
+ return scrollToTimelineComment({
+ container, virtualizer: virtuosoRef.current, index, commentId: findReveal.unit.anchorId,
+ onComplete: finish,
+ });
+ }, [findReveal, items, scrollContainerEl]);
const descEditorRef = useRef<ContentEditorRef>(null);
const descriptionEditingRef = useRef(false);
@@ -3504,7 +3498,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
/>
);
- // Shared row renderer for both timeline render modes (flat / virtualized).
+ // Row renderer for the virtualized timeline.
// The wrapper `id="comment-..."` is the deep-link target — equivalent to
// a native `<a href="#comment-...">` anchor. A run that left no comment is
// addressed by its task id, which the sidebar's unread link lands on.
@@ -3517,7 +3511,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
onExpand={() => toggleResolvedExpand(reply.id, true)} /> : <AgentRunComment run={item.run} entering={enteringRunIds.has(item.run.task.id)} standalone
highlightedId={highlightedId}
commentProps={reply ? {
- issueId: id, replyScrollParent: isFlatTimeline ? null : scrollContainerEl, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,
+ issueId: id, replyScrollParent: scrollContainerEl, entry: reply, replies: timelineView.threadReplies.get(reply.id) ?? EMPTY_REPLIES,
currentUserId: user?.id, canModerate: canModerateComments, onReply: submitReply,
onReplyAccepted: scrollToTimelineBottom, onEdit: editComment, onDelete: deleteComment,
onToggleReaction: handleToggleReaction, onCreateSubIssue: openCommentSubIssue,
@@ -3547,7 +3541,7 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
<div className="pb-3" id={`comment-${item.id}`}>
<CommentCard
issueId={id}
- replyScrollParent={isFlatTimeline ? null : scrollContainerEl}
+ replyScrollParent={scrollContainerEl}
runs={commentRuns.get(item.id) ?? EMPTY_COMMENT_RUNS}
enteringRunIds={enteringRunIds}
entry={item.entry}
@@ -4325,44 +4319,32 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d
{timelineLoading && timelineView.groups.length === 0 ? (
<TimelineSkeleton />
) : (
- // Only in-page find needs every row mounted for DOM text search.
- // Browsing and comment deep links keep viewport-sized rendering.
- !isFlatTimeline ? (
- !scrollContainerEl ? (
- // Skeleton while the callback ref populates so the gap
- // between IssueDetail mount and Virtuoso mount doesn't
- // flash empty.
- <TimelineSkeleton />
- ) : (
- <div ref={virtualTimelineRef} className="mt-4">
- <Virtuoso
- key={`${wsId}:${id}`}
- ref={virtuosoRef}
- customScrollParent={scrollContainerEl}
- data={items}
- initialScrollTop={readingAnchor ? undefined : restoredScrollTop}
- increaseViewportBy={{ top: 800, bottom: 800 }}
- totalListHeightChanged={handleTimelineHeightChange}
- rangeChanged={handleTimelineRangeChanged}
- computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}
- // Also load-bearing for long threads: keepThreadRowAnchored
- // corrects after Virtuoso's resize handling in the same frame.
- skipAnimationFrameInResizeObserver
- // followOutput intentionally NOT set. Virtuoso treats
- // it as a sticky "is at bottom" flag and resets
- // scrollTop to maxScrollTop on every height-change
- // tick — issue-detail is document-shaped, not chat.
- itemContent={renderItem}
- />
- </div>
- )
+ !scrollContainerEl ? (
+ // Skeleton while the callback ref populates so the gap
+ // between IssueDetail mount and Virtuoso mount doesn't
+ // flash empty.
+ <TimelineSkeleton />
) : (
- <div className="mt-4">
- {items.map((item, i) => (
- <Fragment key={`${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}>
- {renderItem(i, item)}
- </Fragment>
- ))}
+ <div ref={virtualTimelineRef} className="mt-4">
+ <Virtuoso
+ key={`${wsId}:${id}`}
+ ref={virtuosoRef}
+ customScrollParent={scrollContainerEl}
+ data={items}
+ initialScrollTop={readingAnchor ? undefined : restoredScrollTop}
+ increaseViewportBy={{ top: 800, bottom: 800 }}
+ totalListHeightChanged={handleTimelineHeightChange}
+ rangeChanged={handleTimelineRangeChanged}
+ computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}
+ // Also load-bearing for long threads: keepThreadRowAnchored
+ // corrects after Virtuoso's resize handling in the same frame.
+ skipAnimationFrameInResizeObserver
+ // followOutput intentionally NOT set. Virtuoso treats
+ // it as a sticky "is at bottom" flag and resets
+ // scrollTop to maxScrollTop on every height-change
+ // tick — issue-detail is document-shaped, not chat.
+ itemContent={renderItem}
+ />
</div>
)
)}
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 171d4ef60d..3519bbd33a 100644
--- a/packages/views/issues/hooks/use-in-page-find.test.ts
+++ b/packages/views/issues/hooks/use-in-page-find.test.ts
@@ -1,5 +1,5 @@
import { act, renderHook } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { collectTextMatches, useInPageFind } from "./use-in-page-find";
function makeRoot(html: string): HTMLElement {
@@ -120,3 +120,79 @@ describe("useInPageFind without the CSS Custom Highlight API", () => {
expect(result.current.activeIndex).toBe(-1);
});
});
+
+// The virtualized timeline: units are counted from their text, and only the
+// ones in the DOM are painted. Stepping to an unmounted one asks the host to
+// mount it.
+describe("useInPageFind with virtual content", () => {
+ let container: HTMLElement;
+ let virtualRoot: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ container.innerHTML = [
+ "<h1>Find before</h1>",
+ '<div id="timeline"><span>find in an activity line</span><p data-find-unit="mounted">find twice: find</p></div>',
+ "<footer>find after</footer>",
+ ].join("");
+ document.body.appendChild(container);
+ virtualRoot = container.querySelector<HTMLElement>("#timeline")!;
+ });
+
+ afterEach(() => {
+ container.remove();
+ });
+
+ async function flushFrames(count = 3): Promise<void> {
+ for (let i = 0; i < count; i++) {
+ await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
+ }
+ }
+
+ it("counts units from data in reading order and mounts the one stepped to", async () => {
+ const units = [
+ { key: "unmounted", text: "find me once" },
+ { key: "mounted", text: "find twice: find" },
+ ];
+ const getUnits = () => units;
+ const reveal = vi.fn((unit: { key: string }, done: () => void) => {
+ const el = document.createElement("p");
+ el.setAttribute("data-find-unit", unit.key);
+ el.textContent = "find me once";
+ virtualRoot.prepend(el);
+ done();
+ return () => {};
+ });
+ const { result } = renderHook(() =>
+ useInPageFind({
+ container,
+ contentKey: 0,
+ virtual: { root: () => virtualRoot, units: getUnits, reveal },
+ }),
+ );
+
+ act(() => {
+ result.current.openFind();
+ result.current.setQuery("find");
+ });
+ await flushFrames();
+
+ // Heading, both units' occurrences, footer. The activity line inside the
+ // timeline is not a unit, so it is not counted.
+ expect(result.current.matchCount).toBe(5);
+ expect(result.current.activeIndex).toBe(0);
+ expect(reveal).not.toHaveBeenCalled();
+
+ act(() => result.current.goNext());
+ expect(reveal).toHaveBeenCalledTimes(1);
+ expect(reveal.mock.calls[0]![0]).toMatchObject({ key: "unmounted" });
+ await flushFrames();
+ expect(result.current.matchCount).toBe(5);
+ expect(result.current.activeIndex).toBe(1);
+
+ // Already mounted: no reveal.
+ act(() => result.current.goNext());
+ expect(result.current.activeIndex).toBe(2);
+ 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 429f858ec0..40cec13996 100644
--- a/packages/views/issues/hooks/use-in-page-find.ts
+++ b/packages/views/issues/hooks/use-in-page-find.ts
@@ -6,17 +6,21 @@ import { isImeComposing } from "@multica/core/utils";
// In-page find (Cmd/Ctrl+F) for the issue detail page.
//
-// The comment timeline is virtualized, so native browser find only sees the
-// handful of comments mounted in the viewport. This hook powers a real
-// find-in-page bar: the host force-renders the timeline flat while find is
-// open (so every comment is in the DOM), and matches are painted with the
-// CSS Custom Highlight API — ranges only, never DOM mutation, so it works
-// over React-rendered markdown AND the contenteditable title/description
-// editors without fighting ProseMirror.
+// Native browser find only sees the comments the virtualized timeline has
+// mounted. This hook searches the rest of the page's DOM directly and, for the
+// timeline, the text of every comment from data (`virtual` below), so opening
+// find never mounts the whole history (MUL-9538). Stepping to a match in an
+// unmounted comment asks the host to mount just that comment, then paints it.
+// Matches are painted with the CSS Custom Highlight API — ranges only, never
+// DOM mutation, so it works over React-rendered markdown AND the
+// contenteditable title/description editors without fighting ProseMirror.
const HIGHLIGHT_NAME = "multica-find";
const ACTIVE_HIGHLIGHT_NAME = "multica-find-active";
+/** Marks the root of a searchable body inside the virtual region. */
+export const FIND_UNIT_ATTRIBUTE = "data-find-unit";
+
// Feature detection, evaluated lazily per call site. On browsers without the
// CSS Custom Highlight API the bar still opens and navigates, it just paints
// no tint. Guard `CSS`/`Highlight` for SSR too (no `window`).
@@ -41,19 +45,23 @@ export interface TextMatch {
// occurrence of `query`, in document order. Matches are confined to a single
// text node — a query straddling an element boundary (e.g. across a bold run)
// is not found, which is the standard trade-off for lightweight find.
+// `[data-find-ignore]` subtrees and `skip` are left out whole.
//
// Pure and DOM-only (no React / no CSS API) so it is unit-testable in jsdom.
-export function collectTextMatches(root: HTMLElement, query: string): TextMatch[] {
+export function collectTextMatches(root: HTMLElement, query: string, skip?: Element | null): TextMatch[] {
const matches: TextMatch[] = [];
const needle = query.toLowerCase();
if (!needle) return matches;
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
acceptNode(node) {
- const parent = node.parentElement;
- if (!parent) return NodeFilter.FILTER_REJECT;
- if (SKIP_TAGS.has(parent.tagName)) return NodeFilter.FILTER_REJECT;
- if (parent.closest("[data-find-ignore]")) return NodeFilter.FILTER_REJECT;
+ if (node.nodeType === Node.ELEMENT_NODE) {
+ const el = node as Element;
+ if (el === skip || SKIP_TAGS.has(el.tagName) || el.hasAttribute("data-find-ignore")) {
+ return NodeFilter.FILTER_REJECT;
+ }
+ return NodeFilter.FILTER_SKIP;
+ }
const value = node.nodeValue;
if (!value || value.trim().length === 0) return NodeFilter.FILTER_REJECT;
return NodeFilter.FILTER_ACCEPT;
@@ -73,19 +81,33 @@ export function collectTextMatches(root: HTMLElement, query: string): TextMatch[
return matches;
}
+/** Non-overlapping occurrences of `needle` in `text`, both already lower-cased. */
+export function countOccurrences(text: string, needle: string): number {
+ if (!needle) return 0;
+ let count = 0;
+ for (let index = text.indexOf(needle); index !== -1; index = text.indexOf(needle, index + needle.length)) {
+ count++;
+ }
+ return count;
+}
+
+function toRange(match: TextMatch): Range {
+ const range = new Range();
+ range.setStart(match.node, match.start);
+ range.setEnd(match.node, match.end);
+ return range;
+}
+
function isElementVisible(el: HTMLElement | null): boolean {
return !!el && el.getClientRects().length > 0;
}
-// Bring `range` into view by driving the scroll container's scrollTop directly.
+// Bring `rect` into view by driving the scroll container's scrollTop directly.
// Never native scrollIntoView: on this page it propagates to the desktop shell
// wrapper and shoves the whole view off-screen (#3929). Only scrolls when the
// match is actually outside the comfortable viewport band.
-function scrollRangeIntoView(container: HTMLElement | null, range: Range): void {
- if (!container) return;
- const rects = range.getClientRects();
- const rect = rects.length > 0 ? rects[0]! : range.getBoundingClientRect();
- if (!rect || (rect.width === 0 && rect.height === 0)) return;
+function scrollRectIntoView(container: HTMLElement | null, rect: DOMRect | undefined): void {
+ if (!container || !rect || (rect.width === 0 && rect.height === 0)) return;
const containerRect = container.getBoundingClientRect();
const pad = 80;
@@ -94,10 +116,37 @@ function scrollRangeIntoView(container: HTMLElement | null, range: Range): void
if (!above && !below) return;
const offsetWithin = rect.top - containerRect.top + container.scrollTop;
- const target = offsetWithin - container.clientHeight / 2 + rect.height / 2;
+ const target = offsetWithin - container.clientHeight / 2 + Math.min(rect.height, container.clientHeight) / 2;
container.scrollTop = Math.max(0, target);
}
+function rangeRect(range: Range): DOMRect | undefined {
+ const rects = range.getClientRects();
+ return rects.length > 0 ? rects[0]! : range.getBoundingClientRect();
+}
+
+/** Searchable text that is not necessarily in the DOM. */
+export interface InPageFindUnit {
+ /** Matches the unit root's `data-find-unit`; ids only, never quotes. */
+ key: string;
+ /** Lower-cased text, as {@link collectTextMatches} would see it rendered. */
+ text: string;
+}
+
+export interface InPageFindVirtualContent<U extends InPageFindUnit> {
+ /** The element rendering the units; the DOM walk leaves it out. */
+ root: () => HTMLElement | null;
+ /** Units in reading order. A new array means the content changed. */
+ units: () => readonly U[];
+ /**
+ * Bring `unit` into the DOM, rooted at `[data-find-unit={unit.key}]`, then
+ * call `done`. Returns a cancel for when the reader moves on first.
+ */
+ reveal: (unit: U, done: () => void) => () => void;
+}
+
+type FindMatch = { range: Range } | { unit: number; occurrence: number };
+
export interface UseInPageFindResult {
open: boolean;
query: string;
@@ -115,7 +164,7 @@ export interface UseInPageFindResult {
goPrev: () => void;
}
-export function useInPageFind(options: {
+export function useInPageFind<U extends InPageFindUnit = InPageFindUnit>(options: {
/** The scroll container whose text is searched. */
container: HTMLElement | null;
/**
@@ -125,21 +174,33 @@ export function useInPageFind(options: {
contentKey: unknown;
/** When false, the Cmd/Ctrl+F shortcut is inert (e.g. issue still loading). */
enabled?: boolean;
+ /** Content searched from data instead of the DOM (the virtualized timeline). */
+ virtual?: InPageFindVirtualContent<U>;
}): UseInPageFindResult {
- const { container, contentKey, enabled = true } = options;
+ const { container, contentKey, enabled = true, virtual } = options;
const [open, setOpen] = useState(false);
const [query, setQueryState] = useState("");
const [matchCount, setMatchCount] = useState(0);
const [activeIndex, setActiveIndex] = useState(-1);
+ // Bumped when a new query restarts at the first match, so the activation
+ // effect scrolls to it even when the index itself did not change.
+ const [restart, setRestart] = useState(0);
const inputRef = useRef<HTMLInputElement | null>(null);
const containerRef = useRef<HTMLElement | null>(container);
containerRef.current = container;
- const rangesRef = useRef<Range[]>([]);
+ const virtualRef = useRef(virtual);
+ virtualRef.current = virtual;
+ const matchesRef = useRef<FindMatch[]>([]);
+ const unitsRef = useRef<readonly U[]>([]);
+ // DOM ranges of the units that are mounted, by unit index.
+ const mountedRef = useRef(new Map<number, Range[]>());
+ const cancelRevealRef = useRef<(() => void) | null>(null);
const activeIndexRef = useRef(activeIndex);
activeIndexRef.current = activeIndex;
const supported = highlightApiSupported();
+ const units = virtual?.units;
const clearHighlights = useCallback(() => {
if (!supported) return;
@@ -147,14 +208,56 @@ export function useInPageFind(options: {
CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);
}, [supported]);
+ const cancelReveal = useCallback(() => {
+ cancelRevealRef.current?.();
+ cancelRevealRef.current = null;
+ }, []);
+
+ // Paint every match the DOM holds: the static ones, and those inside the
+ // units currently mounted. A unit's DOM is the truth for where its matches
+ // are; its data text only counts them.
+ const paint = useCallback((needle: string) => {
+ const mounted = new Map<number, Range[]>();
+ const root = virtualRef.current?.root();
+ const all: Range[] = [];
+ for (const match of matchesRef.current) if ("range" in match) all.push(match.range);
+ if (root && needle) {
+ const indexByKey = new Map<string, number>();
+ unitsRef.current.forEach((unit, index) => indexByKey.set(unit.key, index));
+ for (const el of root.querySelectorAll<HTMLElement>(`[${FIND_UNIT_ATTRIBUTE}]`)) {
+ const index = indexByKey.get(el.getAttribute(FIND_UNIT_ATTRIBUTE) ?? "");
+ if (index === undefined) continue;
+ const ranges = collectTextMatches(el, needle).map(toRange);
+ if (ranges.length === 0) continue;
+ mounted.set(index, ranges);
+ all.push(...ranges);
+ }
+ }
+ mountedRef.current = mounted;
+ if (!supported) return;
+ if (all.length > 0) CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(...all));
+ else CSS.highlights.delete(HIGHLIGHT_NAME);
+ }, [supported]);
+
// Paint the active match on top of the all-matches tint (higher priority)
- // and, when asked, bring it into view. Called both when the user navigates
- // and after a recompute, so the active tint always tracks live ranges — a
- // range that went stale (async re-highlight replacing text nodes) is
- // replaced even when the total match count is unchanged.
- const applyActive = useCallback(
- (ranges: Range[], index: number, scroll: boolean) => {
- const range = index >= 0 ? ranges[index] : undefined;
+ // and, when asked, bring it into view — mounting its comment first when it
+ // 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) => {
+ const match = index >= 0 ? matchesRef.current[index] : undefined;
+ let range: Range | undefined;
+ let unitElement: HTMLElement | null = null;
+ if (match && "range" in match) range = match.range;
+ else if (match) {
+ const ranges = mountedRef.current.get(match.unit);
+ // Data and DOM can disagree on a count (code highlighting splits text
+ // nodes); land on the nearest occurrence the DOM has.
+ range = ranges?.[Math.min(match.occurrence, ranges.length - 1)];
+ const key = unitsRef.current[match.unit]?.key;
+ unitElement = key === undefined ? null
+ : virtualRef.current?.root()?.querySelector<HTMLElement>(`[${FIND_UNIT_ATTRIBUTE}="${key}"]`) ?? null;
+ }
// Painting the active tint is the only highlight-API-only step. Active
// tracking and scroll-to-match must keep working on browsers without the
// CSS Custom Highlight API, otherwise prev/next would open the bar but
@@ -168,84 +271,115 @@ export function useInPageFind(options: {
CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);
}
}
- if (range && scroll) scrollRangeIntoView(containerRef.current, range);
+ if (!scroll || !match) return;
+ cancelReveal();
+ if ("range" in match || unitElement) {
+ scrollRectIntoView(containerRef.current, range ? rangeRect(range) : unitElement?.getBoundingClientRect());
+ return;
+ }
+ 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;
},
- [supported],
+ [supported, cancelReveal],
);
- // Rebuild the match set from the live DOM. `resetActive` starts navigation
- // over at the first match (query changed); otherwise the active index is
- // preserved as content shifts underneath (streaming comment, re-highlight).
+ // Rebuild the match set: the DOM outside the virtual region, and the units'
+ // text in its place. `resetActive` starts navigation over at the first
+ // match (query changed); otherwise the active index is preserved as content
+ // shifts underneath (streaming comment, re-highlight, a comment mounting).
const recompute = useCallback(
- (resetActive: boolean) => {
+ ({ resetActive }: { resetActive: boolean }) => {
const root = containerRef.current;
- if (!open || !root || query.trim().length === 0) {
- rangesRef.current = [];
+ const needle = query.trim().length === 0 ? "" : query.toLowerCase();
+ if (!open || !root || !needle) {
+ matchesRef.current = [];
+ mountedRef.current = new Map();
clearHighlights();
setMatchCount(0);
setActiveIndex(-1);
return;
}
- const matches = collectTextMatches(root, query);
- const ranges = matches.map((m) => {
- const range = new Range();
- range.setStart(m.node, m.start);
- range.setEnd(m.node, m.end);
- return range;
+ const candidate = virtualRef.current?.root() ?? null;
+ const virtualRoot = candidate && root.contains(candidate) ? candidate : null;
+ const before: FindMatch[] = [];
+ const after: FindMatch[] = [];
+ for (const match of collectTextMatches(root, needle, virtualRoot)) {
+ const follows = virtualRoot && virtualRoot.compareDocumentPosition(match.node) & Node.DOCUMENT_POSITION_FOLLOWING;
+ (follows ? after : before).push({ range: toRange(match) });
+ }
+ const inside: FindMatch[] = [];
+ unitsRef.current = virtualRoot ? virtualRef.current?.units() ?? [] : [];
+ unitsRef.current.forEach((unit, index) => {
+ const count = countOccurrences(unit.text, needle);
+ for (let occurrence = 0; occurrence < count; occurrence++) inside.push({ unit: index, occurrence });
});
- rangesRef.current = ranges;
+ matchesRef.current = [...before, ...inside, ...after];
+ paint(needle);
- if (ranges.length === 0) {
- clearHighlights();
- setMatchCount(0);
+ const total = matchesRef.current.length;
+ setMatchCount(total);
+ if (total === 0) {
+ cancelReveal();
setActiveIndex(-1);
+ if (supported) CSS.highlights.delete(ACTIVE_HIGHLIGHT_NAME);
return;
}
-
- if (supported) {
- CSS.highlights.set(HIGHLIGHT_NAME, new Highlight(...ranges));
+ if (resetActive) {
+ // The activation effect scrolls to it.
+ setActiveIndex(0);
+ setRestart((n) => n + 1);
+ return;
}
- setMatchCount(ranges.length);
const prev = activeIndexRef.current;
- const nextActive =
- resetActive || prev < 0 ? 0 : Math.min(prev, ranges.length - 1);
+ const nextActive = prev < 0 ? 0 : Math.min(prev, total - 1);
setActiveIndex(nextActive);
- // Scroll only when the query changed (resetActive) — never yank the view
- // while content mutates underneath a fixed active match.
- applyActive(ranges, nextActive, resetActive);
+ // Never yank the view while content mutates underneath a fixed match.
+ activate(nextActive, false);
},
- [open, query, supported, clearHighlights, applyActive],
+ [open, query, supported, clearHighlights, cancelReveal, paint, activate],
);
const recomputeRef = useRef(recompute);
recomputeRef.current = recompute;
// Recompute when the query changes or the bar opens/closes → restart at the
- // first match. Deferred a frame so the flat (non-virtualized) render the host
- // switches to on open has committed before we walk the DOM.
+ // first match. Deferred a frame so a commit in flight has landed before we
+ // walk the DOM.
useEffect(() => {
- const raf = requestAnimationFrame(() => recomputeRef.current(true));
+ const raf = requestAnimationFrame(() => recomputeRef.current({ resetActive: true }));
return () => cancelAnimationFrame(raf);
}, [open, query, container]);
// Recompute when searchable content changes, keeping the active match.
useEffect(() => {
if (!open) return;
- const raf = requestAnimationFrame(() => recomputeRef.current(false));
+ const raf = requestAnimationFrame(() => recomputeRef.current({ resetActive: false }));
return () => cancelAnimationFrame(raf);
- }, [contentKey, open]);
+ }, [contentKey, units, open]);
- // Async DOM churn (markdown/code highlight settling, streamed replies)
- // invalidates the ranges; re-derive them, coalescing bursts into one frame.
- // Runs regardless of highlight support so fallback counting/navigation stay
- // in sync with the live DOM.
+ // Async DOM churn (markdown/code highlight settling, streamed replies, rows
+ // mounting as the timeline scrolls) invalidates the ranges; re-derive them,
+ // coalescing bursts into one frame. Runs regardless of highlight support so
+ // fallback counting/navigation stay in sync with the live DOM.
useEffect(() => {
if (!open || !container) return;
let raf = 0;
const observer = new MutationObserver(() => {
cancelAnimationFrame(raf);
- raf = requestAnimationFrame(() => recomputeRef.current(false));
+ raf = requestAnimationFrame(() => recomputeRef.current({ resetActive: false }));
});
observer.observe(container, {
subtree: true,
@@ -258,12 +392,13 @@ export function useInPageFind(options: {
};
}, [open, container]);
- // Move the active tint and scroll when the user steps between matches.
- // (Recompute handles the active tint for content-driven changes.)
+ // Move the active tint and scroll when the user steps between matches or a
+ // new query restarts at the first one. (Recompute handles the active tint
+ // for content-driven changes.)
useEffect(() => {
if (!open) return;
- applyActive(rangesRef.current, activeIndex, true);
- }, [activeIndex, open, applyActive]);
+ activate(activeIndex, true);
+ }, [activeIndex, restart, open, activate]);
// Global Cmd/Ctrl+F. The listener is scoped to the mounted issue detail; on
// desktop, <Activity> cycles this effect with tab visibility, so only the
@@ -288,8 +423,16 @@ export function useInPageFind(options: {
return () => document.removeEventListener("keydown", onKeyDown);
}, [enabled]);
- // Drop highlights on unmount so a stale tint can't linger after navigation.
- useEffect(() => clearHighlights, [clearHighlights]);
+ // Drop highlights and any pending landing on close and unmount, so a stale
+ // tint can't linger after navigation.
+ useEffect(() => {
+ if (open) return;
+ cancelReveal();
+ }, [open, cancelReveal]);
+ useEffect(() => () => {
+ cancelReveal();
+ clearHighlights();
+ }, [cancelReveal, clearHighlights]);
const setQuery = useCallback((value: string) => setQueryState(value), []);
const openFind = useCallback(() => setOpen(true), []);
@@ -297,7 +440,7 @@ export function useInPageFind(options: {
const goNext = useCallback(() => {
setActiveIndex((prev) => {
- const n = rangesRef.current.length;
+ const n = matchesRef.current.length;
if (n === 0) return -1;
return prev < 0 ? 0 : (prev + 1) % n;
});
@@ -305,7 +448,7 @@ export function useInPageFind(options: {
const goPrev = useCallback(() => {
setActiveIndex((prev) => {
- const n = rangesRef.current.length;
+ const n = matchesRef.current.length;
if (n === 0) return -1;
return prev < 0 ? n - 1 : (prev - 1 + n) % n;
});
diff --git a/packages/views/issues/utils/markdown-search-text.test.ts b/packages/views/issues/utils/markdown-search-text.test.ts
new file mode 100644
index 0000000000..0277178eba
--- /dev/null
+++ b/packages/views/issues/utils/markdown-search-text.test.ts
@@ -0,0 +1,44 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { markdownSearchText } from "./markdown-search-text";
+
+// Text nodes of the rendered comment, as find walks them.
+const nodes = (markdown: string) => markdownSearchText(markdown).split("\n").map((part) => part.trim()).filter(Boolean);
+
+describe("markdownSearchText", () => {
+ it("keeps prose and drops block markers", () => {
+ expect(nodes("## Summary\n\n> quoted line\n\n- first item\n2. second item\n- [x] done item")).toEqual([
+ "Summary", "quoted line", "first item", "second item", "done item",
+ ]);
+ });
+
+ it("splits text where inline formatting starts a new text node", () => {
+ expect(nodes("foo **bar** baz `code()` and _em_ ~~old~~")).toEqual([
+ "foo", "bar", "baz", "code()", "and", "em", "old",
+ ]);
+ });
+
+ it("keeps snake_case and spaced operators literal", () => {
+ expect(nodes("call snake_case_name with a * b")).toEqual(["call snake_case_name with a * b"]);
+ });
+
+ it("renders links and mentions as their label, and images as nothing", () => {
+ expect(nodes("See [the docs](https://example.com/x) and [@Link](mention://agent/1) ![shot](https://cdn/x.png)")).toEqual([
+ "See", "the docs", "and", "@Link",
+ ]);
+ });
+
+ it("keeps fenced code lines and drops the fences", () => {
+ expect(nodes("before\n```ts\nconst a = 1;\n**not bold**\n```\nafter")).toEqual([
+ "before", "const a = 1;", "**not bold**", "after",
+ ]);
+ });
+
+ it("reads table cells and skips the delimiter row", () => {
+ expect(nodes("| Step | Time |\n| --- | ---: |\n| parse | 12 ms |")).toEqual(["Step", "Time", "parse", "12 ms"]);
+ });
+
+ it("unescapes characters and entities", () => {
+ expect(nodes("a \\*literal\\* &amp; more")).toEqual(["a *literal* & more"]);
+ });
+});
diff --git a/packages/views/issues/utils/markdown-search-text.ts b/packages/views/issues/utils/markdown-search-text.ts
new file mode 100644
index 0000000000..8433b20338
--- /dev/null
+++ b/packages/views/issues/utils/markdown-search-text.ts
@@ -0,0 +1,82 @@
+/**
+ * The text a reader sees when `markdown` renders, for counting in-page find
+ * matches in timeline comments that are not mounted (MUL-9538).
+ *
+ * Find matches inside one DOM text node at a time, so a query never spans
+ * formatting: `foo **bar**` renders as the text nodes "foo " and "bar". This
+ * keeps the same boundaries by writing a newline wherever rendering starts a
+ * new text node (the find input is one line, so no query contains one), and
+ * drops the syntax itself. It is a cheap approximation, not a Markdown parser:
+ * a mounted comment's DOM stays the source of truth for painting matches.
+ */
+export function markdownSearchText(markdown: string): string {
+ const cached = cache.get(markdown);
+ if (cached !== undefined) return cached;
+ const text = toSearchText(markdown);
+ cache.set(markdown, text);
+ if (cache.size > MAX_CACHED) cache.delete(cache.keys().next().value!);
+ return text;
+}
+
+// Keyed by the content itself, so an edited comment never reads a stale entry.
+const MAX_CACHED = 4_000;
+const cache = new Map<string, string>();
+
+const FENCE = /^ {0,3}(`{3,}|~{3,})/;
+const TABLE_DELIMITER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
+const THEMATIC_BREAK = /^ {0,3}([-*_])(\s*\1){2,}\s*$/;
+const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", "#39": "'" };
+
+function toSearchText(markdown: string): string {
+ const out: string[] = [];
+ let fence: string | null = null;
+ for (const line of markdown.replace(/\r\n?/g, "\n").split("\n")) {
+ const marker = FENCE.exec(line)?.[1];
+ if (fence) {
+ // Highlighted code stays one line per row; only the fences are syntax.
+ if (marker && marker[0] === fence[0] && marker.length >= fence.length) fence = null;
+ else out.push(line);
+ continue;
+ }
+ if (marker) {
+ fence = marker;
+ continue;
+ }
+ if (TABLE_DELIMITER.test(line) && line.includes("-") && line.includes("|")) continue;
+ if (THEMATIC_BREAK.test(line)) continue;
+ out.push(inlineText(blockContent(line)));
+ }
+ return out.join("\n");
+}
+
+/** Drop the block markers that open a line: quotes, headings, list items, task boxes. */
+function blockContent(line: string): string {
+ return line
+ .replace(/^\s*(>\s?)+/, "")
+ .replace(/^\s{0,3}#{1,6}(\s+|$)/, "")
+ .replace(/^\s*([-*+]|\d{1,9}[.)])\s+(\[[ xX]\]\s+)?/, "")
+ .replace(/\s+#+\s*$/, "");
+}
+
+function inlineText(line: string): string {
+ // Escaped punctuation is literal text; hold it out of the syntax rules.
+ const escaped: string[] = [];
+ return line
+ .replace(/\\([!-/:-@[-`{-~])/g, (_, char: string) => `\uE000${escaped.push(char) - 1}\uE001`)
+ // Images render as previews, not text.
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, "\n")
+ // Links and mentions render their label only.
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, "\n$1\n")
+ .replace(/<(https?:\/\/[^>\s]+)>/g, "\n$1\n")
+ .replace(/<\/?[a-zA-Z][^>]*>/g, "\n")
+ .replace(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g, (_, _ticks: string, code: string) => `\n${code}\n`)
+ .replace(/\*\*|__|~~|==/g, "\n")
+ // Single `*` / `_` emphasis delimiters sit against a word on one side only;
+ // snake_case and spaced operators stay literal.
+ .replace(/(^|[^\w*])[*_](?=[^\s*_])/g, "$1\n")
+ .replace(/([^\s*_])[*_](?=$|[^\w*])/g, "$1\n")
+ // Table cells are separate nodes.
+ .replace(/\|/g, "\n")
+ .replace(/&(amp|lt|gt|quot|apos|nbsp|#39);/g, (_, name: string) => ENTITIES[name] ?? "")
+ .replace(/\uE000(\d+)\uE001/g, (_, index: string) => escaped[Number(index)] ?? "");
+}
diff --git a/packages/views/issues/utils/timeline-find-units.test.ts b/packages/views/issues/utils/timeline-find-units.test.ts
new file mode 100644
index 0000000000..9ed14e02cb
--- /dev/null
+++ b/packages/views/issues/utils/timeline-find-units.test.ts
@@ -0,0 +1,78 @@
+// @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 { buildTimelineFindUnits, type TimelineFindItem, type TimelineFolds } from "./timeline-find-units";
+
+function task(id: string, overrides: Partial<AgentTask> = {}): AgentTask {
+ return { id, agent_id: "agent", runtime_id: "runtime", issue_id: "issue", status: "completed", priority: 0,
+ created_at: "2026-09-07T00:00:00Z", started_at: "2026-09-07T00:00:00Z", dispatched_at: null,
+ completed_at: "2026-09-07T00:00:00Z", result: null, error: null, ...overrides };
+}
+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 at = (minute: number) => `2026-09-07T00:0${minute}:00Z`;
+const OPEN: TimelineFolds = { expandedResolved: new Set(), collapsed: new Set() };
+const keys = (units: { key: string }[]) => units.map((unit) => unit.key);
+
+describe("buildTimelineFindUnits", () => {
+ const root = comment("root", "Root **question**");
+ const reply = comment("reply", "A reply", { parent_id: root.id, created_at: at(1) });
+ const answer = comment("answer", "Agent answer", { parent_id: reply.id, actor_type: "agent", source_task_id: "run-1", created_at: at(2) });
+ const deleted = comment("deleted", "gone", { parent_id: root.id, created_at: at(3), deleted_at: at(4) });
+ const answered: CommentRun = { task: task("run-1", { completed_at: at(2) }), commentId: answer.id, anchorCommentId: reply.id, hasReply: true };
+ const silent: CommentRun = {
+ task: task("run-2", { completed_at: at(5), result: { comment: "Output with `code`" } }),
+ anchorCommentId: root.id, hasReply: false,
+ };
+ const standalone: CommentRun = { task: task("run-3", { result: { comment: "Standalone output" } }), hasReply: false };
+ const replies = new Map([[root.id, [reply, answer, deleted]]]);
+ const runs = new Map([[root.id, [answered, silent]]]);
+
+ it("lists every comment and run output the timeline shows, in reading order", () => {
+ const items: TimelineFindItem[] = [
+ { kind: "comment", id: root.id, entry: root },
+ { kind: "activity-group", id: "activity" },
+ { kind: "run", id: standalone.task.id, run: standalone },
+ ];
+
+ const units = buildTimelineFindUnits(items, replies, runs, OPEN);
+
+ expect(units.map(({ key, itemId, anchorId }) => ({ key, itemId, anchorId }))).toEqual([
+ { key: "root", itemId: "root", anchorId: "root" },
+ { key: "reply", itemId: "root", anchorId: "reply" },
+ { key: "answer", itemId: "root", anchorId: "answer" },
+ { key: "run:run-2", itemId: "root", anchorId: "run-2" },
+ { key: "run:run-3", itemId: "run-3", anchorId: "run-3" },
+ ]);
+ expect(units[0]!.text).toBe("root \nquestion\n");
+ expect(units[3]!.text).toBe("output with \ncode\n");
+ });
+
+ it("leaves out what a fold hides, as the rendered timeline does", () => {
+ // A thread the reader collapsed shows only its header.
+ expect(buildTimelineFindUnits([{ kind: "comment", id: root.id, entry: root }], replies, runs,
+ { ...OPEN, collapsed: new Set([root.id]) })).toEqual([]);
+ // A resolved thread folded into its bar shows none of its comments.
+ const resolved = { ...root, resolved_at: at(9) };
+ expect(buildTimelineFindUnits([{ kind: "resolved-bar", id: root.id, entry: resolved }], replies, runs, OPEN)).toEqual([]);
+ // 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 }];
+ 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"]);
+ });
+
+ it("leaves out a failure notice, which renders as its run's block", () => {
+ const failed = task("run-1", { status: "failed" });
+ const notice = comment("notice", "agent exited with status 1", {
+ actor_type: "agent", comment_type: "system", source_task_id: failed.id,
+ });
+ const run: CommentRun = { task: failed, commentId: notice.id, hasReply: true };
+
+ expect(buildTimelineFindUnits([{ kind: "run", id: notice.id, run, entry: notice }], new Map(), new Map(), OPEN)).toEqual([]);
+ });
+});
diff --git a/packages/views/issues/utils/timeline-find-units.ts b/packages/views/issues/utils/timeline-find-units.ts
new file mode 100644
index 0000000000..d4573a2ab9
--- /dev/null
+++ b/packages/views/issues/utils/timeline-find-units.ts
@@ -0,0 +1,106 @@
+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 { markdownSearchText } from "./markdown-search-text";
+
+/**
+ * One searchable body in the issue timeline: a comment's Markdown, or the
+ * output of a run that posted no comment. Its rendered root carries
+ * `data-find-unit={key}`.
+ */
+export interface TimelineFindUnit {
+ key: string;
+ /** Timeline row (Virtuoso item) the body renders in. */
+ itemId: string;
+ /** `comment-<anchorId>` brings the body into the DOM, as a deep link does. */
+ anchorId: string;
+ /** Lower-cased rendered text (see {@link markdownSearchText}). */
+ 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
+ * the history (MUL-9538). It mirrors what renders: a folded or collapsed
+ * thread contributes only what stays on screen, as the bar's matches always
+ * did. Activity lines, names and timestamps are not searched.
+ */
+export function buildTimelineFindUnits(
+ items: readonly TimelineFindItem[],
+ 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;
+ }
+ // 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;
+}