Skip to content

Commit f9469bc

Browse files
perf(web): pull request comments reuse their markdown parse
Pull request comments passed a new autolink plugin list on every render, which broke ChatMarkdown's memo and kept their markdown out of the shared parse cache, so every panel render parsed every comment again. On a pull request with thousands of comments that was most of the panel's render time. The plugin list is now built once per repository, ChatMarkdown shares a renderer and its cache for any extra plugin list that keeps its identity, and the thought previews pass constant lists. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent aa0b3e2 commit f9469bc

9 files changed

Lines changed: 87 additions & 35 deletions

‎apps/web/src/components/ChatMarkdown.browser.test.tsx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,21 @@ it("reuses the parse of a streaming reply's finished blocks when it remounts", a
165165
expect(parsedSources.filter((source) => source.includes("Finished block"))).toHaveLength(1);
166166
});
167167

168+
it("reuses the parse of a remounted message that has stable extra plugins", async () => {
169+
setup();
170+
const parsed = vi.fn();
171+
const countingPlugins = [() => () => void parsed()];
172+
const message = (
173+
<ChatMarkdown cwd="/tmp/project" text="Cached text" extraRemarkPlugins={countingPlugins} />
174+
);
175+
{
176+
await using _first = await render(message);
177+
}
178+
await using screen = await render(message);
179+
await expect.element(screen.getByText("Cached text")).toBeVisible();
180+
expect(parsed).toHaveBeenCalledTimes(1);
181+
});
182+
168183
describe("ChatMarkdown favicon privacy", () => {
169184
it("suppresses private link images while preserving public links across updates", async () => {
170185
setup();

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ interface ChatMarkdownProps {
241241
imageBaseDir?: string | undefined;
242242
workspaceMutationId?: string | null | undefined;
243243
onImageExpand?: ((preview: ExpandedImagePreview) => void) | undefined;
244+
/** Keep one list per configuration (a module constant): it keys the shared parse cache. */
244245
extraRemarkPlugins?: NonNullable<ReactMarkdownOptions["remarkPlugins"]>;
245246
renderContextReference?: ((reference: ChatMarkdownContextReference) => ReactNode) | undefined;
246247
/** Loads media a source control host keeps behind a credential through the server, which holds
@@ -1647,6 +1648,18 @@ const CHAT_MARKDOWN_REMARK_PLUGIN_SETS = {
16471648
mathBreaks: [REMARK_MATH, ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
16481649
} satisfies Record<string, PluggableList>;
16491650

1651+
const combinedPlugins = new WeakMap<PluggableList, WeakMap<PluggableList, PluggableList>>();
1652+
1653+
// One combined list per pair, so a stable extra list shares a renderer and its parse cache.
1654+
function withExtraPlugins(shared: PluggableList, extra: PluggableList): PluggableList {
1655+
if (extra.length === 0) return shared;
1656+
let byShared = combinedPlugins.get(extra);
1657+
if (!byShared) combinedPlugins.set(extra, (byShared = new WeakMap()));
1658+
let combined = byShared.get(shared);
1659+
if (!combined) byShared.set(shared, (combined = [...shared, ...extra]));
1660+
return combined;
1661+
}
1662+
16501663
const markdownRenderers = new WeakMap<
16511664
PluggableList,
16521665
WeakMap<PluggableList, ReturnType<typeof createMarkdownRenderer>>
@@ -1735,15 +1748,11 @@ function ChatMarkdown({
17351748
? "breaks"
17361749
: "plain"
17371750
];
1738-
// Extra and incremental plugins are per instance, so their output is not shared.
1739-
const uncachedPlugins = extraRemarkPlugins.length > 0 || incrementalParsing;
1740-
const remarkPlugins = uncachedPlugins
1741-
? [
1742-
...sharedRemarkPlugins,
1743-
...extraRemarkPlugins,
1744-
...(incrementalParsing ? [createIncrementalMarkdownPlugin()] : []),
1745-
]
1746-
: sharedRemarkPlugins;
1751+
// The incremental parser keeps per-instance state, so its output is not shared.
1752+
const uncachedPlugins = incrementalParsing;
1753+
const remarkPlugins = incrementalParsing
1754+
? [...sharedRemarkPlugins, ...extraRemarkPlugins, createIncrementalMarkdownPlugin()]
1755+
: withExtraPlugins(sharedRemarkPlugins, extraRemarkPlugins);
17471756
const blocks = streamingBlocks ?? [text];
17481757

17491758
return (

‎apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { PluggableList } from "unified";
12
import type { Root, RootContent } from "mdast";
23
import {
34
resolveWorkEntryToolPresentation,
@@ -237,3 +238,6 @@ export function remarkThoughtPreview(fallback: string) {
237238
: [{ type: "text", value: fallback }];
238239
};
239240
}
241+
242+
export const THOUGHT_PREVIEW_PLUGINS: PluggableList = [[remarkThoughtPreview, "Thought"]];
243+
export const THINKING_PREVIEW_PLUGINS: PluggableList = [[remarkThoughtPreview, "Thinking"]];

‎apps/web/src/components/chat/TimelineWorkEntryRow.tsx‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ import {
6464
workEntryRawCommand,
6565
buildToolCallExpandedBody,
6666
workEntryIconName,
67-
remarkThoughtPreview,
67+
THINKING_PREVIEW_PLUGINS,
68+
THOUGHT_PREVIEW_PLUGINS,
6869
} from "./TimelineWorkEntryRow.logic";
6970

7071
export function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) {
@@ -421,12 +422,11 @@ function WorkEntryLogRow(props: WorkEntryRowProps) {
421422
text={workEntry.detail ?? previewText}
422423
cwd={ctx.markdownCwd}
423424
parseRawHtml={false}
424-
extraRemarkPlugins={[
425-
[
426-
remarkThoughtPreview,
427-
workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
428-
],
429-
]}
425+
extraRemarkPlugins={
426+
workEntry.toolLifecycleStatus === "inProgress"
427+
? THINKING_PREVIEW_PLUGINS
428+
: THOUGHT_PREVIEW_PLUGINS
429+
}
430430
/>
431431
) : threadLabel ? (
432432
<ThreadReadLabel

‎apps/web/src/components/chat/TimelineWorkGroupRows.tsx‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ import {
4848
SimpleWorkEntryRow,
4949
} from "./TimelineWorkEntryRow";
5050
import {
51-
remarkThoughtPreview,
51+
THINKING_PREVIEW_PLUGINS,
52+
THOUGHT_PREVIEW_PLUGINS,
5253
toolGroupSummaryIconName,
5354
workEntryIconName,
5455
} from "./TimelineWorkEntryRow.logic";
@@ -537,7 +538,7 @@ export function LiveWorkEntryTimelineRow({
537538
text={thoughtLine}
538539
cwd={ctx.markdownCwd}
539540
parseRawHtml={false}
540-
extraRemarkPlugins={[[remarkThoughtPreview, "Thought"]]}
541+
extraRemarkPlugins={THOUGHT_PREVIEW_PLUGINS}
541542
/>
542543
</span>
543544
}
@@ -558,7 +559,7 @@ export function LiveWorkEntryTimelineRow({
558559
text={row.entry.detail ?? label}
559560
cwd={ctx.markdownCwd}
560561
parseRawHtml={false}
561-
extraRemarkPlugins={[[remarkThoughtPreview, row.active ? "Thinking" : "Thought"]]}
562+
extraRemarkPlugins={row.active ? THINKING_PREVIEW_PLUGINS : THOUGHT_PREVIEW_PLUGINS}
562563
/>
563564
) : threadLabel ? (
564565
<ThreadReadLabel

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { projectChangeRequestUrl } from "@t3tools/client-runtime/change-request-links";
22
import { normalizeThreadPullRequestKey } from "@t3tools/client-runtime/thread-pull-requests";
3-
import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
43
import { useAtomValue } from "@effect/atom-react";
54
import { usePullRequestStack } from "~/state/usePullRequestStack";
65
import {
@@ -106,6 +105,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState";
106105
import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab";
107106
import { openOnHostLabel } from "./pullRequestLinkContextMenu";
108107
import { PullRequestMarkdownContext } from "./PullRequestMarkdown";
108+
import { pullRequestAutolinkPlugins } from "./pullRequestMarkdown.logic";
109109
import { PullRequestComposer } from "./PullRequestComposer";
110110
import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
111111
import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
@@ -240,7 +240,7 @@ function pullRequestMarkdownContext(
240240
threadRef: ScopedThreadRef | null,
241241
) {
242242
return {
243-
autolinks: changeRequestReferenceAutolinker(detail),
243+
remarkPlugins: pullRequestAutolinkPlugins(detail),
244244
lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false,
245245
threadRef,
246246
};

‎apps/web/src/components/pullRequest/PullRequestMarkdown.browser.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { PullRequestMarkdown, PullRequestMarkdownContext } from "./PullRequestMa
77

88
async function renderBody(host: string, options: { lineBreaks?: boolean } = {}) {
99
const context = {
10-
autolinks: null,
10+
remarkPlugins: [],
1111
lineBreaks: sourceControlClients.get(host).hardLineBreaks ?? false,
1212
threadRef: null,
1313
};

‎apps/web/src/components/pullRequest/PullRequestMarkdown.tsx‎

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,26 @@
11
import { ExternalLinkIcon, PaperclipIcon } from "lucide-react";
22
import { markdownImageSourceFragment } from "@t3tools/client-runtime/markdown-images";
3-
import {
4-
sourceControlClients,
5-
type ReferenceAutolink,
6-
} from "@t3tools/client-runtime/source-control-clients";
3+
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
74
import {
85
SOURCE_CONTROL_MEDIA_ASSET,
96
type AssetResource,
107
type EnvironmentId,
118
type ScopedThreadRef,
129
} from "@t3tools/contracts";
1310
import { createContext, useContext } from "react";
14-
import type { Options as ReactMarkdownOptions } from "react-markdown";
11+
import type { PluggableList } from "unified";
1512

1613
import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls";
1714
import { cn } from "~/lib/utils";
1815
import { PULL_REQUESTS_PANEL_REF } from "~/rightPanelStore";
1916

2017
import ChatMarkdown from "../ChatMarkdown";
2118
import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
22-
import { remarkPullRequestAutolinks, splitPullRequestBody } from "./pullRequestMarkdown.logic";
19+
import { splitPullRequestBody } from "./pullRequestMarkdown.logic";
2320

2421
export const PullRequestMarkdownContext = createContext<{
25-
autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null;
22+
/** Stable per repository, so comments share one renderer and its parse cache. */
23+
remarkPlugins: PluggableList;
2624
lineBreaks: boolean;
2725
threadRef: ScopedThreadRef | null;
2826
} | null>(null);
@@ -72,11 +70,7 @@ export function PullRequestMarkdown({
7270
}) {
7371
const segments = splitPullRequestBody(text);
7472
const context = useContext(PullRequestMarkdownContext);
75-
const autolinks = context?.autolinks;
7673
const resolvedThreadRef = threadRef ?? context?.threadRef ?? undefined;
77-
const extraRemarkPlugins: NonNullable<ReactMarkdownOptions["remarkPlugins"]> = autolinks
78-
? [[remarkPullRequestAutolinks, { autolinks }]]
79-
: [];
8074
return (
8175
<div
8276
className={cn(
@@ -95,7 +89,7 @@ export function PullRequestMarkdown({
9589
threadRef={resolvedThreadRef}
9690
pullRequestPanelRef={resolvedThreadRef ?? PULL_REQUESTS_PANEL_REF}
9791
environmentId={environmentId}
98-
extraRemarkPlugins={extraRemarkPlugins}
92+
{...(context ? { extraRemarkPlugins: context.remarkPlugins } : {})}
9993
lineBreaks={lineBreaks ?? context?.lineBreaks ?? false}
10094
sourceControlMedia
10195
/>

‎apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
1+
import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown";
2+
import {
3+
sourceControlClients,
4+
type ReferenceAutolink,
5+
} from "@t3tools/client-runtime/source-control-clients";
6+
import type { PluggableList } from "unified";
27

38
export {
49
splitPullRequestBody,
@@ -52,3 +57,27 @@ export function remarkPullRequestAutolinks(options: {
5257
};
5358
return (tree: MarkdownNode) => visit(tree);
5459
}
60+
61+
const NO_AUTOLINK_PLUGINS: PluggableList = [];
62+
const autolinkPlugins = new Map<string, PluggableList>();
63+
64+
/**
65+
* One plugin list per repository, so every comment of a pull request shares one markdown
66+
* renderer and its parse cache instead of parsing again on each render.
67+
*/
68+
export function pullRequestAutolinkPlugins(
69+
changeRequest: { readonly provider: string; readonly url: string } | null,
70+
): PluggableList {
71+
if (changeRequest === null) return NO_AUTOLINK_PLUGINS;
72+
const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link
73+
.repositoryUrl;
74+
if (repositoryUrl === undefined) return NO_AUTOLINK_PLUGINS;
75+
const key = `${changeRequest.provider}\u0000${repositoryUrl}`;
76+
let plugins = autolinkPlugins.get(key);
77+
if (plugins === undefined) {
78+
const autolinks = changeRequestReferenceAutolinker(changeRequest);
79+
plugins = autolinks ? [[remarkPullRequestAutolinks, { autolinks }]] : NO_AUTOLINK_PLUGINS;
80+
autolinkPlugins.set(key, plugins);
81+
}
82+
return plugins;
83+
}

0 commit comments

Comments
 (0)