🪶 perf: Cut the Mount Cost of Finished Agent Messages (#16057)

* 🪶 perf: Render a Finished Message's Markdown in One Pass

Opening a conversation rendered every assistant text part per top-level
block: a full mdast parse just to find block boundaries, then one
ReactMarkdown pipeline, two providers and a layout effect per paragraph,
table and fence. The split only pays while a message streams, where it
keeps completed blocks memoized.

A message that was never streamed in this view now renders as one pipeline
and skips the boundary parse, keyed on its source so an in-place edit
remounts it with fresh code and artifact indices. A message that streamed
here keeps the per-block split after it finishes, so ending an answer never
remounts its blocks. The benchmark gains a finished-message mount case.

* 🪪 perf: Keep the Agents List From Re-Rendering Every Message Part

The author header a message hands its parts, restated after an inline
steer, was an element built from the resolved agent. The agents list
resolves after first paint, so that element changed identity, broke the
memo on ContentParts and re-rendered every part of the message, even
though the header only shows after a steer.

Both row renderers now hand the parts one constant header element that
reads the author from AuthorContext. An agent or assistant resolving
re-renders only the headers on screen, and the row's own icon and label
reuse the same memoized author.

* 🧷 fix: Move a Finished Message to Per-Block Rendering on Its First Change

A finished message kept its single pipeline keyed on its source, so every
change remounted all of it. An artifact editor saves the message every few
hundred milliseconds while the user types, and each save collapsed its
expanded Mermaid rows and reset its code blocks, where per-block rendering
had re-rendered only the artifact's block.

The single pipeline now serves a message only while it is exactly as it
mounted. Generating or any content change moves it to per-block rendering
for good, which remounts it once; later changes re-render only the blocks
they touch. The move happens as generation starts, so the fade baseline is
set on the blocks it mounts.

The splitter also sliced each top-level block after its indentation, which
decides how the block parses: an indented fence under a two-digit list item
kept its indentation in the code, and a two-space-indented list turned a note
into a code block. Blocks now keep their line's indentation.
This commit is contained in:
Danny Avila 2026-09-18 16:19:19 -04:00 • committed by GitHub
parent 5c72d4146e
commit 79d1cbbafc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 891 additions and 235 deletions

View file

@ -0,0 +1,17 @@
import { createContext, useContext } from 'react';
import type { ReactNode } from 'react';
/** The author a message restates wherever its content resumes after a steer. */
export type TMessageAuthor = {
icon: ReactNode;
label: string;
};
/**
* Carries the message author to the headers inside its content. The author can
* resolve after the message paints, when an agent's name and avatar arrive with the
* agents list, and a context change reaches only the headers that read it rather
* than every part of the message.
*/
export const AuthorContext = createContext<TMessageAuthor | null>(null);
export const useAuthorContext = () => useContext(AuthorContext);

View file

@ -10,6 +10,7 @@ export * from './EditorContext';
export * from './ChatFormContext';
export * from './BookmarkContext';
export * from './MessageContext';
export * from './AuthorContext';
export * from './AssistantsContext';
export * from './AgentsContext';
export * from './AssistantsMapContext';

View file

@ -19,7 +19,8 @@ const Markdown = memo(function Markdown({ content = '', isLatestMessage }: TCont
const LaTeXParsing = useRecoilValue<boolean>(store.LaTeXParsing);
const isInitializing = content === '';
const animate = smoothStreaming && isLatestMessage && isSubmitting;
const streaming = isLatestMessage && isSubmitting;
const animate = smoothStreaming && streaming;
// Hydration signal for the fade: substantial content already present at the
// render where `animate` flips on means resumed/switched-to/follow-up
@ -52,6 +53,7 @@ const Markdown = memo(function Markdown({ content = '', isLatestMessage }: TCont
<MarkdownErrorBoundary content={content} codeExecution={true}>
<MarkdownBlocks
content={content}
streaming={streaming}
remarkPlugins={getRemarkPlugins(LaTeXParsing)}
rehypePlugins={getRehypePlugins()}
components={getMarkdownComponents()}

View file

@ -5,13 +5,15 @@ import { render } from '@testing-library/react';
import { getRemarkPlugins, getRehypePlugins, getMarkdownComponents } from './markdownConfig';
import { ArtifactProvider, CodeBlockProvider, MessageContext } from '~/Providers';
import CodeBlock from '~/components/Messages/Content/CodeBlock';
import MarkdownBlocks from './MarkdownBlocks';
import Markdown from './Markdown';
/**
* Streaming render benchmark comparing the previous whole-message renderer
* (one ReactMarkdown re-parsing everything per token) against the per-block
* memoized renderer. This file lives outside `__tests__/` and is named
* `.bench.tsx` so the default jest run skips it; execute it explicitly with:
* Render benchmark comparing the previous whole-message renderer (one
* ReactMarkdown re-parsing everything per token) against the per-block memoized
* renderer, both while a message streams and when a finished message mounts.
* This file lives outside `__tests__/` and is named `.bench.tsx` so the default
* jest run skips it; execute it explicitly with:
*
* node node_modules/jest/bin/jest.js --runInBand --coverage=false \
* --testMatch '**\/MarkdownBlocks.bench.tsx'
@ -83,8 +85,20 @@ const OldMarkdown = ({ content }: { content: string }) => (
</ArtifactProvider>
);
/** The per-block renderer a streaming message uses, without the fade. */
const NewMarkdown = ({ content }: { content: string }) => (
<Markdown content={content} isLatestMessage={true} />
<MarkdownBlocks
content={content}
streaming={true}
remarkPlugins={getRemarkPlugins()}
rehypePlugins={getRehypePlugins()}
components={getMarkdownComponents()}
/>
);
/** A finished message as a conversation opens with it. */
const SettledMarkdown = ({ content }: { content: string }) => (
<Markdown content={content} isLatestMessage={false} />
);
const streamingContext = {
@ -186,4 +200,53 @@ describe('Markdown streaming benchmark (OLD whole-message vs NEW per-block)', ()
// Memoization should cut total code-block renders by a wide margin.
expect(newRenders).toBeLessThan(oldRenders * 0.5);
});
it('reports mount cost for a message that was already finished', () => {
const iterations = 5;
const rows = [12, 40].map((sections) => {
const prefixes = [buildMessage(sections)];
measure(OldMarkdown, prefixes);
measure(NewMarkdown, prefixes);
measure(SettledMarkdown, prefixes);
const old: Array<{ totalMs: number; codeBlockRenders: number }> = [];
const perBlock: Array<{ totalMs: number; codeBlockRenders: number }> = [];
const settled: Array<{ totalMs: number; codeBlockRenders: number }> = [];
for (let i = 0; i < iterations; i += 1) {
old.push(measure(OldMarkdown, prefixes));
perBlock.push(measure(NewMarkdown, prefixes));
settled.push(measure(SettledMarkdown, prefixes));
}
const minMs = (rs: Array<{ totalMs: number }>) => Math.min(...rs.map((r) => r.totalMs));
return {
chars: prefixes[0].length,
oldMs: minMs(old),
perBlockMs: minMs(perBlock),
settledMs: minMs(settled),
oldRenders: old[0].codeBlockRenders,
settledRenders: settled[0].codeBlockRenders,
};
});
console.log(
[
'',
'================ Markdown finished-message mount benchmark ================',
`min of ${iterations} mounts, summed Profiler actualDuration; jsdom`,
...rows.map(
(r) =>
` ${r.chars} chars: OLD ${r.oldMs.toFixed(1)} ms | PER-BLOCK ${r.perBlockMs.toFixed(1)} ms | ` +
`SETTLED ${r.settledMs.toFixed(1)} ms (${(r.perBlockMs / r.settledMs).toFixed(2)}x faster than per-block)`,
),
'==========================================================================',
'',
].join('\n'),
);
// A finished message mounts through the whole-message pipeline: every code
// block renders exactly once, as it did before per-block rendering existed.
for (const r of rows) {
expect(r.settledRenders).toBe(r.oldRenders);
}
});
});

View file

@ -1,4 +1,4 @@
import React, { memo, useMemo, useLayoutEffect } from 'react';
import React, { memo, useMemo, useState, useLayoutEffect } from 'react';
import ReactMarkdown from 'react-markdown';
import type { PluggableList } from 'unified';
import type { ElementType } from 'react';
@ -86,46 +86,103 @@ MarkdownBlock.displayName = 'MarkdownBlock';
type MarkdownBlocksProps = SharedProps & {
content: string;
/** Whether this message is the one generating right now. */
streaming: boolean;
};
type BlockEntry = {
/**
* Code and artifact blocks capture their index in a ref when they mount, so a
* block has to remount whenever an index it holds could shift, and must not
* remount otherwise.
*/
key: string;
raw: string;
codeBaseIndex: number;
artifactBaseIndex: number;
mermaidBaseIndex: number;
};
/**
* Splits a message into top-level blocks and renders each independently so
* that, during streaming, only the last block re-parses while earlier blocks
* (tables, code, etc.) stay memoized. Each block's executable code and artifact
* indices are preserved in document order via per-block providers seeded with
* prefix-summed base indices.
* Each top-level block, seeded with the code, artifact and Mermaid indices of the
* blocks before it. The key carries those bases, so an in-place edit that inserts
* a block before existing code or artifacts remounts the blocks it shifted, while
* append-only streaming keeps completed blocks mounted.
*/
const toBlockEntries = (content: string): BlockEntry[] => {
let codeBaseIndex = 0;
let artifactBaseIndex = 0;
let mermaidBaseIndex = 0;
return splitMarkdownIntoBlocks(content).map((block, index) => {
const entry = {
key: `${index}-${codeBaseIndex}-${artifactBaseIndex}-${mermaidBaseIndex}`,
raw: block.raw,
codeBaseIndex,
artifactBaseIndex,
mermaidBaseIndex,
};
codeBaseIndex += block.codeBlockCount;
artifactBaseIndex += block.artifactCount;
mermaidBaseIndex += block.mermaidCount;
return entry;
});
};
/**
* The whole message as one block, which numbers its code and artifacts from zero
* itself. It only ever renders the message exactly as it mounted, so no index it
* assigns can go stale and its key never has to change.
*/
const toWholeMessage = (content: string): BlockEntry[] =>
content
? [{ key: 'whole', raw: content, codeBaseIndex: 0, artifactBaseIndex: 0, mermaidBaseIndex: 0 }]
: [];
/**
* Renders a message's markdown.
*
* While the message streams, each top-level block renders and memoizes on its
* own, so only the last, still-growing block re-parses on each token. Each
* block's executable code and artifact indices stay in document order through
* per-block providers seeded with prefix-summed base indices.
*
* A message that mounts finished renders as one pipeline instead, for as long as
* it stays exactly as it mounted. Splitting it would buy memoization nothing
* uses, at the price of a whole extra parse to find block boundaries and one
* pipeline per block, which is most of the cost of opening a long conversation.
*
* Once the message generates or its content changes, it moves to the split for
* good. Code and artifact blocks capture their index at mount, and per block only
* the blocks a change touches re-render, so finishing an answer never remounts its
* blocks and neither do repeated edits such as artifact saves. The move itself
* remounts the message once.
*/
const MarkdownBlocks = memo(function MarkdownBlocks({
content,
streaming,
remarkPlugins,
rehypePlugins,
components,
animate,
hydrated,
}: MarkdownBlocksProps) {
const blocks = useMemo(() => {
let codeBaseIndex = 0;
let artifactBaseIndex = 0;
let mermaidBaseIndex = 0;
return splitMarkdownIntoBlocks(content).map((block) => {
const entry = { raw: block.raw, codeBaseIndex, artifactBaseIndex, mermaidBaseIndex };
codeBaseIndex += block.codeBlockCount;
artifactBaseIndex += block.artifactCount;
mermaidBaseIndex += block.mermaidCount;
return entry;
});
}, [content]);
const [mountedContent] = useState(content);
const [hasChanged, setHasChanged] = useState(streaming);
const changing = streaming || content !== mountedContent;
if (changing && !hasChanged) {
setHasChanged(true);
}
const perBlock = hasChanged || changing;
const blocks = useMemo(
() => (perBlock ? toBlockEntries(content) : toWholeMessage(content)),
[content, perBlock],
);
return (
<>
{blocks.map((block, index) => (
// Key includes the base indices so that an in-place edit which inserts a
// block before existing code/artifact blocks (shifting their base) forces
// a remount, refreshing the index each code/artifact block captures in a
// ref. During append-only streaming these stay constant, so completed
// blocks keep a stable key and are not remounted.
{blocks.map((block) => (
<MarkdownBlock
key={`${index}-${block.codeBaseIndex}-${block.artifactBaseIndex}-${block.mermaidBaseIndex}`}
key={block.key}
content={block.raw}
codeBaseIndex={block.codeBaseIndex}
artifactBaseIndex={block.artifactBaseIndex}

View file

@ -0,0 +1,22 @@
import { memo } from 'react';
import { useAuthorContext } from '~/Providers';
import AuthorHeader from './AuthorHeader';
/**
* Restates the message author where content resumes after a steer, reading the
* author from `AuthorContext`.
*
* A header element built from the author changes identity when the author
* resolves, and handing that element to the memoized parts tree re-rendered every
* part of the message. Rendered through this component, the element a caller hands
* down never changes, and an author update re-renders only the headers on screen.
*/
const ResumeAuthorHeader = memo(function ResumeAuthorHeader() {
const author = useAuthorContext();
if (author == null) {
return null;
}
return <AuthorHeader icon={author.icon} label={author.label} />;
});
export default ResumeAuthorHeader;

View file

@ -18,3 +18,4 @@ export { default as PtcToolTrace } from './PtcToolTrace';
export { default as SubagentCall } from './SubagentCall';
export { default as SteerPart } from './SteerPart';
export { default as AuthorHeader } from './AuthorHeader';
export { default as ResumeAuthorHeader } from './ResumeAuthorHeader';

View file

@ -67,10 +67,41 @@ const readArtifacts = async () =>
id: el.getAttribute('data-id'),
}));
describe('MarkdownBlocks artifact-index parity (e2e)', () => {
/** The latest message of a conversation, generating while `submitting` holds. */
const liveView = (content: string, submitting: boolean) => (
<MemoryRouter>
<RecoilRoot>
<MessageContext.Provider
value={{
messageId: 'm1',
isExpanded: true,
isSubmitting: submitting,
isLatestMessage: true,
}}
>
<Markdown content={content} isLatestMessage={true} />
</MessageContext.Provider>
</RecoilRoot>
</MemoryRouter>
);
/**
* A finished message renders through one pipeline; one that streamed in this view
* renders per block. Every parity case has to hold on both paths.
*/
const renderMessage = (content: string, streamed: boolean) => {
const rendered = render(liveView(content, streamed));
rendered.rerender(liveView(content, false));
return rendered;
};
describe.each([
['a finished', false],
['a streamed', true],
])('MarkdownBlocks artifact-index parity (e2e) in %s message', (_label, streamed) => {
it('assigns document-order indices to multiple artifacts', async () => {
const content = `${artifact('a', 'A')}\n\n${artifact('b', 'B')}`;
render(wrap(<Markdown content={content} isLatestMessage={false} />));
renderMessage(content, streamed);
expect(await readArtifacts()).toEqual([
{ idx: '0', id: 'a' },
@ -85,7 +116,7 @@ describe('MarkdownBlocks artifact-index parity (e2e)', () => {
const oldIdx = await readArtifacts();
unmount();
render(wrap(<Markdown content={content} isLatestMessage={false} />));
renderMessage(content, streamed);
const newIdx = await readArtifacts();
expect(newIdx).toEqual(oldIdx);
@ -95,16 +126,20 @@ describe('MarkdownBlocks artifact-index parity (e2e)', () => {
]);
});
/**
* A finished message moves to per-block rendering on its first edit, and per
* block the base-aware keys remount the blocks whose index shifted.
*/
it('refreshes artifact indices when an in-place edit inserts an artifact before another', async () => {
const before = `Intro.\n\n${artifact('b', 'B')}`;
const after = `${artifact('a', 'A')}\n\n${artifact('b', 'B')}`;
const { rerender } = render(wrap(<Markdown content={before} isLatestMessage={false} />));
const { rerender } = renderMessage(before, streamed);
expect(await readArtifacts()).toEqual([{ idx: '0', id: 'b' }]);
rerender(wrap(<Markdown content={after} isLatestMessage={false} />));
// 'b' was index 0; inserting 'a' before it shifts its base to 1. Without the
// base-aware block key its ref-cached index would stay 0 (duplicating 'a').
rerender(liveView(after, false));
// 'b' was index 0; inserting 'a' before it shifts it to 1. Without a remount
// its ref-cached index would stay 0 (duplicating 'a').
expect(await readArtifacts()).toEqual([
{ idx: '0', id: 'a' },
{ idx: '1', id: 'b' },
@ -115,7 +150,7 @@ describe('MarkdownBlocks artifact-index parity (e2e)', () => {
// `:artifact{}` (text directive) renders as literal text, not an Artifact, so
// the following real artifact must still be index 0.
const content = `See :artifact{identifier="x"} inline.\n\n${artifact('a', 'A')}`;
render(wrap(<Markdown content={content} isLatestMessage={false} />));
renderMessage(content, streamed);
expect(await readArtifacts()).toEqual([{ idx: '0', id: 'a' }]);
});
@ -141,7 +176,7 @@ describe('MarkdownBlocks artifact-index parity (e2e)', () => {
':::',
].join('\n');
render(wrap(<Markdown content={content} isLatestMessage={false} />));
renderMessage(content, streamed);
const [artifactNode] = await screen.findAllByTestId('art');
expect(artifactNode.getAttribute('data-content')).toBe(`${markdown}\n`);

View file

@ -2,10 +2,11 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import ReactMarkdown from 'react-markdown';
import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { render, screen, within } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { getRemarkPlugins, getRehypePlugins, getMarkdownComponents } from '../markdownConfig';
import { ArtifactProvider, CodeBlockProvider } from '~/Providers';
import { MessageContext, ArtifactProvider, CodeBlockProvider } from '~/Providers';
import { splitMarkdownIntoBlocks } from '../splitMarkdown';
import Markdown from '../Markdown';
/**
@ -13,10 +14,14 @@ import Markdown from '../Markdown';
* router the same way it has one in the app — without it the diagram throws into its
* error boundary and the assertions compare two fallbacks instead of two renderers.
*/
const queryClient = new QueryClient();
const TestProviders = ({ children }: { children: React.ReactNode }) => (
<MemoryRouter>
<RecoilRoot>{children}</RecoilRoot>
</MemoryRouter>
<QueryClientProvider client={queryClient}>
<MemoryRouter>
<RecoilRoot>{children}</RecoilRoot>
</MemoryRouter>
</QueryClientProvider>
);
/**
@ -31,18 +36,48 @@ jest.mock('~/components/Messages/Content/Mermaid', () => ({
MermaidErrorBoundary: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const mockCodeBlockMounts = { count: 0 };
/**
* Stub CodeBlock so we can read the blockIndex each executable code block
* receives, while still exercising the real `code` override's skip/single-line
* decision (which decides whether a CodeBlock renders at all).
* decision (which decides whether a CodeBlock renders at all). It also counts
* mounts, which is how a remount of an already-rendered block shows up.
*/
jest.mock('~/components/Messages/Content/CodeBlock', () => ({
__esModule: true,
default: ({ lang, blockIndex }: { lang?: string; blockIndex?: number }) => (
<div data-testid="cb" data-block-index={String(blockIndex)} data-lang={String(lang)} />
),
default: function MockCodeBlock({
lang,
blockIndex,
codeChildren,
}: {
lang?: string;
blockIndex?: number;
codeChildren?: React.ReactNode;
}) {
const { useEffect } = jest.requireActual<typeof import('react')>('react');
useEffect(() => {
mockCodeBlockMounts.count += 1;
}, []);
return (
<div
data-testid="cb"
data-block-index={String(blockIndex)}
data-lang={String(lang)}
data-code={String(codeChildren)}
/>
);
},
}));
/** The real splitter, observed: whether a render paid for the block-boundary parse. */
jest.mock('../splitMarkdown', () => {
const actual = jest.requireActual<typeof import('../splitMarkdown')>('../splitMarkdown');
return { ...actual, splitMarkdownIntoBlocks: jest.fn(actual.splitMarkdownIntoBlocks) };
});
const splitSpy = jest.mocked(splitMarkdownIntoBlocks);
/** The previous whole-message renderer: a single ReactMarkdown under one set of providers. */
const OldMarkdown = ({ content }: { content: string }) => (
<ArtifactProvider>
@ -60,6 +95,29 @@ const OldMarkdown = ({ content }: { content: string }) => (
</ArtifactProvider>
);
/** The latest message of a conversation, generating while `submitting` holds. */
const LiveMarkdown = ({ content, submitting }: { content: string; submitting: boolean }) => (
<MessageContext.Provider
value={{
messageId: 'live',
isExpanded: false,
isSubmitting: submitting,
isLatestMessage: true,
}}
>
<Markdown content={content} isLatestMessage={true} />
</MessageContext.Provider>
);
const StreamingMarkdown = ({ content }: { content: string }) => (
<LiveMarkdown content={content} submitting={true} />
);
/** A message the conversation opened with, already finished. */
const SettledMarkdown = ({ content }: { content: string }) => (
<Markdown content={content} isLatestMessage={false} />
);
/**
* The whole-message renderer emits whitespace-only text nodes ("\n") between
* top-level block elements; the per-block renderer parses each block in
@ -95,6 +153,22 @@ const streamThrough = (
return container;
};
/** Streams a message line by line as the latest one, then finishes it. */
const streamAndFinish = (content: string) => {
const view = (value: string, submitting: boolean) => (
<TestProviders>
<LiveMarkdown content={value} submitting={submitting} />
</TestProviders>
);
const lines = content.split('\n');
const rendered = render(view(lines[0], true));
for (let i = 2; i <= lines.length; i += 1) {
rendered.rerender(view(lines.slice(0, i).join('\n'), true));
}
rendered.rerender(view(content, false));
return rendered;
};
const MIXED = [
'Intro paragraph.',
'',
@ -135,9 +209,10 @@ const EXPECTED = [
{ idx: '3', lang: 'ts' },
];
const NewMarkdown = ({ content }: { content: string }) => (
<Markdown content={content} isLatestMessage={false} />
);
beforeEach(() => {
splitSpy.mockClear();
mockCodeBlockMounts.count = 0;
});
describe('MarkdownBlocks code-block index parity', () => {
it('assigns document-order indices on a direct render (matches whole-message renderer)', () => {
@ -148,7 +223,7 @@ describe('MarkdownBlocks code-block index parity', () => {
);
const { container: newC } = render(
<TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
<SettledMarkdown content={MIXED} />
</TestProviders>,
);
@ -158,47 +233,166 @@ describe('MarkdownBlocks code-block index parity', () => {
it('keeps indices correct across a simulated stream (no drift under memoization)', () => {
const oldC = streamThrough(OldMarkdown, MIXED);
const newC = streamThrough(NewMarkdown, MIXED);
const newC = streamThrough(StreamingMarkdown, MIXED);
expect(indicesIn(oldC)).toEqual(EXPECTED);
expect(indicesIn(newC)).toEqual(EXPECTED);
});
it('streamed indices match a fresh direct render (stable for stored execution results)', () => {
const streamed = streamThrough(NewMarkdown, MIXED);
const streamed = streamThrough(StreamingMarkdown, MIXED);
const { container: fresh } = render(
<TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
<SettledMarkdown content={MIXED} />
</TestProviders>,
);
expect(indicesIn(streamed)).toEqual(indicesIn(fresh));
});
it('refreshes indices when an in-place edit inserts a code block before existing ones', () => {
const before = 'intro\n\n```js\na\n```';
const after = '```py\nx\n```\n\n```js\na\n```';
const { container, rerender } = render(
<TestProviders>
<Markdown content={before} isLatestMessage={false} />
</TestProviders>,
);
expect(indicesIn(container)).toEqual([{ idx: '0', lang: 'js' }]);
/**
* Code blocks capture their index when they mount. A finished message moves to
* per-block rendering on its first edit, and per block the base-aware keys
* remount the blocks an edit shifted. The fixture turns a Mermaid fence, which
* takes no code index, into an executable one, so the js block keeps a stale
* index unless it really remounts.
*/
it.each([
['a finished', false],
['a streamed', true],
])(
'refreshes indices when an in-place edit to %s message inserts a code block before existing ones',
(_label, streamedFirst) => {
const before = '```mermaid\ngraph TD\n```\n\n```js\na\n```';
const after = '```py\nx\n```\n\n```js\na\n```';
const view = (content: string, submitting: boolean) => (
<TestProviders>
<LiveMarkdown content={content} submitting={submitting} />
</TestProviders>
);
const { container, rerender } = render(view(before, streamedFirst));
rerender(view(before, false));
expect(indicesIn(container)).toEqual([{ idx: '0', lang: 'js' }]);
rerender(
rerender(view(after, false));
// The js block's index shifted 0 -> 1; without forcing a remount its ref-cached
// index would stay 0 (duplicating py). It must become 1.
expect(indicesIn(container)).toEqual([
{ idx: '0', lang: 'py' },
{ idx: '1', lang: 'js' },
]);
},
);
});
describe('MarkdownBlocks finished and streamed messages', () => {
const PROSE = '# H\n\nPara with `code`.\n\n| x | y |\n| - | - |\n| 1 | 2 |\n\n- a\n- b';
it('renders a finished message through one pipeline, without the block-boundary parse', () => {
const { container: oldC } = render(
<TestProviders>
<Markdown content={after} isLatestMessage={false} />
<OldMarkdown content={PROSE} />
</TestProviders>,
);
// The js block's base shifted 0 -> 1; without forcing a remount its ref-cached
// index would stay 0 (duplicating py). It must become 1.
expect(indicesIn(container)).toEqual([
{ idx: '0', lang: 'py' },
{ idx: '1', lang: 'js' },
]);
const { container: settledC } = render(
<TestProviders>
<SettledMarkdown content={PROSE} />
</TestProviders>,
);
expect(splitSpy).not.toHaveBeenCalled();
// One pipeline reproduces the whole-message renderer exactly, down to the
// whitespace between blocks that separately parsed blocks cannot carry.
expect(settledC.innerHTML).toBe(oldC.innerHTML);
});
it('splits the message that is generating, so only its last block re-parses', () => {
render(
<TestProviders>
<StreamingMarkdown content={PROSE} />
</TestProviders>,
);
expect(splitSpy).toHaveBeenCalledWith(PROSE);
});
it('keeps a streamed message split once it finishes, so no block remounts', () => {
const view = (content: string, submitting: boolean) => (
<TestProviders>
<LiveMarkdown content={content} submitting={submitting} />
</TestProviders>
);
const lines = MIXED.split('\n');
const { container, rerender } = render(view(lines[0], true));
for (let i = 2; i <= lines.length; i += 1) {
rerender(view(lines.slice(0, i).join('\n'), true));
}
const mountsWhileStreaming = mockCodeBlockMounts.count;
splitSpy.mockClear();
rerender(view(MIXED, false));
expect(mockCodeBlockMounts.count).toBe(mountsWhileStreaming);
expect(splitSpy).not.toHaveBeenCalled();
expect(indicesIn(container)).toEqual(EXPECTED);
});
/**
* Moving to per-block rendering remounts the message once, since the two paths
* build different trees; it happens as generation starts, so the fade baseline
* is set on the blocks it mounts. After that the message never remounts again.
*/
it('moves a finished message to per-block rendering once when it starts generating again', () => {
const view = (content: string, submitting: boolean) => (
<TestProviders>
<LiveMarkdown content={content} submitting={submitting} />
</TestProviders>
);
const opening = MIXED.split('\n').slice(0, 12).join('\n');
const { container, rerender } = render(view(opening, false));
expect(splitSpy).not.toHaveBeenCalled();
const mountsAtOpen = mockCodeBlockMounts.count;
rerender(view(opening, true));
expect(splitSpy).toHaveBeenCalledWith(opening);
expect(mockCodeBlockMounts.count).toBe(mountsAtOpen * 2);
// A generation that stops before producing anything must not move it back.
rerender(view(opening, false));
expect(mockCodeBlockMounts.count).toBe(mountsAtOpen * 2);
const mountsOnceSplit = mockCodeBlockMounts.count;
rerender(view(MIXED, true));
rerender(view(MIXED, false));
expect(indicesIn(container)).toEqual(EXPECTED);
expect(mockCodeBlockMounts.count - mountsOnceSplit).toBe(EXPECTED.length - mountsAtOpen);
});
/**
* An artifact editor saves the message it lives in every few hundred
* milliseconds while the user types. Only the first save may remount the
* message; after it, a save re-renders just the block it touched.
*/
it('moves a finished message to per-block rendering on its first edit, and edits in place after it', () => {
const view = (content: string) => (
<TestProviders>
<SettledMarkdown content={content} />
</TestProviders>
);
const { container, rerender } = render(view(MIXED));
expect(splitSpy).not.toHaveBeenCalled();
const mountsAtOpen = mockCodeBlockMounts.count;
rerender(view(MIXED.replace('Intro paragraph.', 'Intro paragraph, edited.')));
expect(mockCodeBlockMounts.count).toBe(mountsAtOpen * 2);
rerender(view(MIXED.replace('Intro paragraph.', 'Intro paragraph, edited twice.')));
rerender(view(MIXED.replace('Some `inline` code here.', 'Some edited `inline` code.')));
expect(mockCodeBlockMounts.count).toBe(mountsAtOpen * 2);
expect(indicesIn(container)).toEqual(EXPECTED);
});
});
describe('MarkdownBlocks DOM equivalence (non-code blocks)', () => {
describe('MarkdownBlocks DOM equivalence', () => {
const cases: Array<[string, string]> = [
['paragraphs', 'First paragraph.\n\nSecond paragraph.'],
['gfm table', ['| a | b |', '| - | - |', '| 1 | 2 |', '| 3 | 4 |'].join('\n')],
@ -208,6 +402,37 @@ describe('MarkdownBlocks DOM equivalence (non-code blocks)', () => {
['blockquote', '> quoted line one\n> quoted line two'],
['inline code', 'Use the `useMemo` hook for memoization.'],
['mixed', '# H\n\nPara with `code`.\n\n| x | y |\n| - | - |\n| 1 | 2 |\n\n- a\n- b'],
/* A fence indented too little to belong to item 10 is a top-level block whose
* indentation the whole-message parse strips from every code line. */
[
'fence indented under a two-digit list item',
[
'9. Build:',
'',
' make',
'',
'10. Run the tests:',
'',
' ```python',
' def test():',
' assert True',
' ```',
].join('\n'),
],
[
'list indented by two spaces',
[
' - Step one',
'',
' Note: run this',
'',
' - Step two',
'',
' ```python',
' print(1)',
' ```',
].join('\n'),
],
];
it.each(cases)('renders identical DOM to the whole-message renderer: %s', (_label, content) => {
@ -216,12 +441,14 @@ describe('MarkdownBlocks DOM equivalence (non-code blocks)', () => {
<OldMarkdown content={content} />
</TestProviders>,
);
const { container: newC } = render(
const { container: settledC } = render(
<TestProviders>
<Markdown content={content} isLatestMessage={false} />
<SettledMarkdown content={content} />
</TestProviders>,
);
expect(normalizeHtml(newC.innerHTML)).toBe(normalizeHtml(oldC.innerHTML));
const { container: streamedC } = streamAndFinish(content);
expect(normalizeHtml(settledC.innerHTML)).toBe(normalizeHtml(oldC.innerHTML));
expect(normalizeHtml(streamedC.innerHTML)).toBe(normalizeHtml(oldC.innerHTML));
});
});
@ -238,27 +465,48 @@ describe('MarkdownBlocks rendering smoke', () => {
it('renders executable code blocks for a multi-code message', () => {
render(
<TestProviders>
<Markdown content={MIXED} isLatestMessage={false} />
<SettledMarkdown content={MIXED} />
</TestProviders>,
);
expect(screen.getAllByTestId('cb')).toHaveLength(4);
});
});
describe('MarkdownBlocks document-level definitions', () => {
/**
* Constructs that need the whole document render as one block on both paths: a
* finished message always does, and the splitter falls back to it for a message
* that streamed.
*/
describe.each([
['a finished', false],
['a streamed', true],
])('MarkdownBlocks document-level constructs in %s message', (_label, streamed) => {
const renderMessage = (content: string) =>
streamed
? streamAndFinish(content)
: render(
<TestProviders>
<SettledMarkdown content={content} />
</TestProviders>,
);
it('resolves a reference-style link whose definition is in a separate block', () => {
const queryClient = new QueryClient();
const content = 'See [docs][d] for details.\n\n[d]: https://example.com/docs';
render(
<QueryClientProvider client={queryClient}>
<TestProviders>
<Markdown content={content} isLatestMessage={false} />
</TestProviders>
</QueryClientProvider>,
);
expect(screen.getByRole('link', { name: 'docs' })).toHaveAttribute(
const { container } = renderMessage(content);
expect(within(container).getByRole('link', { name: 'docs' })).toHaveAttribute(
'href',
'https://example.com/docs',
);
});
it('keeps the separator between adjacent raw HTML blocks', () => {
const content = '<div>one</div>\n\n<div>two</div>';
const { container: oldC } = render(
<TestProviders>
<OldMarkdown content={content} />
</TestProviders>,
);
const { container } = renderMessage(content);
expect(container.innerHTML).toBe(oldC.innerHTML);
});
});

View file

@ -25,59 +25,102 @@ jest.mock('~/components/Messages/Content/CodeBlock', () => ({
),
}));
const renderMarkdown = (content: string) =>
render(
<MarkdownBlocks
content={content}
remarkPlugins={getRemarkPlugins()}
rehypePlugins={getRehypePlugins()}
components={getMarkdownComponents()}
/>,
);
const view = (content: string, streaming: boolean) => (
<MarkdownBlocks
content={content}
streaming={streaming}
remarkPlugins={getRemarkPlugins()}
rehypePlugins={getRehypePlugins()}
components={getMarkdownComponents()}
/>
);
const renderMarkdown = (content: string, streaming: boolean) => render(view(content, streaming));
const mermaidIds = () =>
screen.getAllByTestId('mermaid').map((element) => element.getAttribute('data-mermaid-id'));
describe('Mermaid block ids', () => {
it('gives each Mermaid fence in a message a distinct id', () => {
renderMarkdown(
['```mermaid', 'graph TD', 'A-->B', '```', '', '```mermaid', 'graph TD', 'C-->D', '```'].join(
'\n',
),
);
/** A finished message renders as one pipeline and a streaming one per block; both number alike. */
describe.each([
['a finished', false],
['a streaming', true],
])('in %s message', (_label, streaming) => {
it('gives each Mermaid fence in a message a distinct id', () => {
renderMarkdown(
[
'```mermaid',
'graph TD',
'A-->B',
'```',
'',
'```mermaid',
'graph TD',
'C-->D',
'```',
].join('\n'),
streaming,
);
const ids = mermaidIds();
expect(ids).toHaveLength(2);
expect(new Set(ids).size).toBe(2);
});
const ids = mermaidIds();
expect(ids).toHaveLength(2);
expect(new Set(ids).size).toBe(2);
});
it('keeps Mermaid ids distinct across intervening executable code blocks', () => {
renderMarkdown(
[
'```mermaid',
'graph TD',
'A-->B',
'```',
'',
'```python',
'print("hi")',
'```',
'',
'```mermaid',
'graph TD',
'C-->D',
'```',
'',
'```mermaid',
'graph TD',
'E-->F',
'```',
].join('\n'),
);
it('keeps Mermaid ids distinct across intervening executable code blocks', () => {
renderMarkdown(
[
'```mermaid',
'graph TD',
'A-->B',
'```',
'',
'```python',
'print("hi")',
'```',
'',
'```mermaid',
'graph TD',
'C-->D',
'```',
'',
'```mermaid',
'graph TD',
'E-->F',
'```',
].join('\n'),
streaming,
);
const ids = mermaidIds();
expect(ids).toHaveLength(3);
expect(new Set(ids).size).toBe(3);
const ids = mermaidIds();
expect(ids).toHaveLength(3);
expect(new Set(ids).size).toBe(3);
});
it('does not let a Mermaid fence disturb executable code block indices', () => {
renderMarkdown(
[
'```python',
'print("first")',
'```',
'',
'```mermaid',
'graph TD',
'A-->B',
'```',
'',
'```python',
'print("second")',
'```',
].join('\n'),
streaming,
);
const indices = screen
.getAllByTestId('code-block')
.map((element) => element.getAttribute('data-block-index'));
expect(indices).toEqual(['0', '1']);
});
});
/**
@ -102,46 +145,13 @@ describe('Mermaid block ids', () => {
].join('\n');
const listStillGrowing = [listWithTwo, '', '- step three'].join('\n');
const { rerender } = renderMarkdown(listWithOne);
const { rerender } = renderMarkdown(listWithOne, true);
expect(mermaidIds()).toEqual(['mermaid-0']);
const view = (content: string) => (
<MarkdownBlocks
content={content}
remarkPlugins={getRemarkPlugins()}
rehypePlugins={getRehypePlugins()}
components={getMarkdownComponents()}
/>
);
rerender(view(listWithTwo));
rerender(view(listWithTwo, true));
expect(mermaidIds()).toEqual(['mermaid-0', 'mermaid-1']);
rerender(view(listStillGrowing));
rerender(view(listStillGrowing, true));
expect(mermaidIds()).toEqual(['mermaid-0', 'mermaid-1']);
});
it('does not let a Mermaid fence disturb executable code block indices', () => {
renderMarkdown(
[
'```python',
'print("first")',
'```',
'',
'```mermaid',
'graph TD',
'A-->B',
'```',
'',
'```python',
'print("second")',
'```',
].join('\n'),
);
const indices = screen
.getAllByTestId('code-block')
.map((element) => element.getAttribute('data-block-index'));
expect(indices).toEqual(['0', '1']);
});
});

View file

@ -39,6 +39,12 @@ describe('splitMarkdownIntoBlocks', () => {
expect(raws(content)).toEqual(['Lead.', artifact, 'Tail.']);
});
it("keeps a top-level block's indentation, which decides how it parses", () => {
const fence = [' ```python', ' def test():', ' assert True', ' ```'].join('\n');
const content = ['9. Build:', '', ' make', '', '10. Run the tests:', '', fence].join('\n');
expect(raws(content)).toEqual([content.slice(0, content.indexOf('\n\n ```')), fence]);
});
it('keeps a list as one block (does not split items)', () => {
const list = '- one\n- two\n- three';
expect(raws(list)).toEqual([list]);

View file

@ -101,6 +101,18 @@ const parseToMdast = (content: string): MdastNode =>
mdastExtensions: [gfmFromMarkdown(), directiveFromMarkdown(), mathFromMarkdown()],
}) as MdastNode;
/**
* Where the line holding a top-level block begins, when only indentation precedes
* the block on it. mdast starts a node after its indentation, but that indentation
* carries meaning: it is stripped from an indented fence's code lines, and it
* decides which list item a later indented line belongs to. A block parsed on its
* own has to keep it to parse the way it does inside the whole message.
*/
const lineStartOf = (content: string, offset: number): number => {
const lineStart = content.lastIndexOf('\n', offset - 1) + 1;
return /^[ \t]*$/.test(content.slice(lineStart, offset)) ? lineStart : offset;
};
/**
* Split a markdown string into its top-level blocks, returning the exact source
* slice for each block plus the index counts it consumes. Completed blocks
@ -149,7 +161,7 @@ export function splitMarkdownIntoBlocks(content: string): MarkdownBlock[] {
const counts = { code: 0, artifact: 0, mermaid: 0 };
countWithin(node, counts);
blocks.push({
raw: content.slice(start, end),
raw: content.slice(lineStartOf(content, start), end),
codeBlockCount: counts.code,
artifactCount: counts.artifact,
mermaidCount: counts.mermaid,

View file

@ -10,7 +10,7 @@ import {
getHeaderPrefixForScreenReader,
} from '~/utils';
import { useLocalize, useAttachments, useMessageHelpers, useContentMetadata } from '~/hooks';
import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel';
import { revealOnRowHoverClasses, messageFooterClasses } from './styles';
@ -20,10 +20,17 @@ import { showThinkingAtom } from '~/store/showThinking';
import Elapsed, { shouldShowElapsed } from './Elapsed';
import ContentParts from './Content/ContentParts';
import SiblingSwitch from './SiblingSwitch';
import { AuthorContext } from '~/Providers';
import HoverButtons from './HoverButtons';
import SubRow from './SubRow';
import store from '~/store';
/**
* The one header every assistant message hands its parts. It reads the author from
* `AuthorContext`, so the author resolving after paint cannot break the parts' memo.
*/
const RESUME_AUTHOR_HEADER = <ResumeAuthorHeader />;
function MessageParts(props: TMessageProps) {
const localize = useLocalize();
const { message, siblingIdx, siblingCount, setSiblingIdx } = props;
@ -86,15 +93,12 @@ function MessageParts(props: TMessageProps) {
],
);
const authorHeader = useMemo(
() =>
isCreatedByUser === true ? undefined : (
<AuthorHeader
icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}
label={name}
/>
),
[isCreatedByUser, iconData, assistant, agent, name],
const author = useMemo(
() => ({
icon: <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />,
label: name,
}),
[iconData, assistant, agent, name],
);
const { hasParallelContent } = useContentMetadata(message);
@ -112,8 +116,8 @@ function MessageParts(props: TMessageProps) {
<div className="m-auto justify-center px-4 py-3 sm:px-0">
<MessageRow
id={messageId ?? ''}
icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}
label={name}
icon={author.icon}
label={author.label}
hoverLabel={getHeaderHoverLabel(
hasConfiguredSender,
agent?.model,
@ -169,26 +173,28 @@ function MessageParts(props: TMessageProps) {
</SubRow>
}
>
<ErrorSourceProvider message={message}>
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
attachments={attachments}
isSubmitting={isSubmitting}
searchResults={searchResults}
manualSkills={message.manualSkills}
messageId={message.messageId}
authorHeader={authorHeader}
setSiblingIdx={setSiblingIdx}
isCreatedByUser={message.isCreatedByUser}
conversationId={conversation?.conversationId}
showThinking={showThinking}
isLatestMessage={messageId === latestMessageId}
content={message.content as Array<TMessageContentParts | undefined>}
/>
</ErrorSourceProvider>
<AuthorContext.Provider value={author}>
<ErrorSourceProvider message={message}>
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
attachments={attachments}
isSubmitting={isSubmitting}
searchResults={searchResults}
manualSkills={message.manualSkills}
messageId={message.messageId}
authorHeader={isCreatedByUser === true ? undefined : RESUME_AUTHOR_HEADER}
setSiblingIdx={setSiblingIdx}
isCreatedByUser={message.isCreatedByUser}
conversationId={conversation?.conversationId}
showThinking={showThinking}
isLatestMessage={messageId === latestMessageId}
content={message.content as Array<TMessageContentParts | undefined>}
/>
</ErrorSourceProvider>
</AuthorContext.Provider>
</MessageRow>
</div>
</div>

View file

@ -12,8 +12,8 @@ import {
} from '~/utils';
import { revealOnRowHoverClasses, messageFooterClasses } from '~/components/Chat/Messages/styles';
import { useLocalize, useAttachments, useMessageActions, useContentMetadata } from '~/hooks';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import ToolCallLimitNotice from '~/components/Chat/Messages/Content/ToolCallLimitNotice';
import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
import Elapsed, { shouldShowElapsed } from '~/components/Chat/Messages/Elapsed';
import { getHeaderHoverLabel } from '~/components/Chat/Messages/ui/HeaderLabel';
@ -24,8 +24,15 @@ import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { showThinkingAtom } from '~/store/showThinking';
import SubRow from '~/components/Chat/Messages/SubRow';
import { AuthorContext } from '~/Providers';
import store from '~/store';
/**
* The one header every assistant message hands its parts. It reads the author from
* `AuthorContext`, so the author resolving after paint cannot break the parts' memo.
*/
const RESUME_AUTHOR_HEADER = <ResumeAuthorHeader />;
type ContentRenderProps = {
message?: TMessage;
/**
@ -138,15 +145,12 @@ const ContentRender = memo(function ContentRender({
],
);
const authorHeader = useMemo(
() =>
msg?.isCreatedByUser === true ? undefined : (
<AuthorHeader
icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}
label={messageLabel ?? ''}
/>
),
[msg?.isCreatedByUser, iconData, assistant, agent, messageLabel],
const author = useMemo(
() => ({
icon: <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />,
label: messageLabel ?? '',
}),
[iconData, assistant, agent, messageLabel],
);
const { hasParallelContent } = useContentMetadata(msg);
@ -158,8 +162,8 @@ const ContentRender = memo(function ContentRender({
return (
<MessageRow
id={msg.messageId}
icon={<MessageIcon iconData={iconData} assistant={assistant} agent={agent} />}
label={messageLabel ?? ''}
icon={author.icon}
label={author.label}
hoverLabel={getHeaderHoverLabel(
hasConfiguredSender,
agent?.model,
@ -214,27 +218,29 @@ const ContentRender = memo(function ContentRender({
</SubRow>
}
>
<ErrorSourceProvider message={msg}>
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
messageId={msg.messageId}
attachments={attachments}
searchResults={searchResults}
manualSkills={msg.manualSkills}
authorHeader={authorHeader}
setSiblingIdx={setSiblingIdx}
isLatestMessage={isLatestMessage}
isSubmitting={isSubmitting}
isCreatedByUser={msg.isCreatedByUser}
createdAt={msg.createdAt ?? msg.clientTimestamp}
showThinking={showThinking}
conversationId={conversation?.conversationId}
content={msg.content as Array<TMessageContentParts | undefined>}
/>
</ErrorSourceProvider>
<AuthorContext.Provider value={author}>
<ErrorSourceProvider message={msg}>
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
messageId={msg.messageId}
attachments={attachments}
searchResults={searchResults}
manualSkills={msg.manualSkills}
authorHeader={msg.isCreatedByUser === true ? undefined : RESUME_AUTHOR_HEADER}
setSiblingIdx={setSiblingIdx}
isLatestMessage={isLatestMessage}
isSubmitting={isSubmitting}
isCreatedByUser={msg.isCreatedByUser}
createdAt={msg.createdAt ?? msg.clientTimestamp}
showThinking={showThinking}
conversationId={conversation?.conversationId}
content={msg.content as Array<TMessageContentParts | undefined>}
/>
</ErrorSourceProvider>
</AuthorContext.Provider>
{/** A turn that ran out of agent steps is incomplete, not broken. Rendered
* here rather than inside `ContentParts` because it is a message-level
* outcome, and `ContentParts` also serves surfaces (subagent panels,

View file

@ -0,0 +1,170 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { render, screen, within } from '@testing-library/react';
import type { Agent, TConversation, TMessage } from 'librechat-data-provider';
import type { TMessageChatContext } from '~/common';
import ContentRender from '../ContentRender';
const mockRenders = { parts: 0 };
/**
* Memoized like the real parts tree with its default comparator, and rendering the
* resume header it is handed where a steer would place it.
*/
jest.mock('~/components/Chat/Messages/Content/ContentParts', () => {
const { memo } = jest.requireActual<typeof import('react')>('react');
return {
__esModule: true,
default: memo(function MockContentParts({ authorHeader }: { authorHeader?: React.ReactNode }) {
mockRenders.parts += 1;
return <div data-testid="parts">{authorHeader}</div>;
}),
};
});
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
default: ({ agent }: { agent?: { name?: string } }) => (
<span data-testid="message-icon" data-agent={agent?.name ?? ''} />
),
}));
jest.mock('~/components/Chat/Messages/HoverButtons', () => ({
__esModule: true,
default: () => null,
}));
jest.mock('~/components/Chat/Messages/ui/MessageTimestamp', () => ({
__esModule: true,
default: () => null,
}));
/**
* Stands in for the agents map: `useMessageActions` reads it through context, so the
* agents list landing re-renders the memoized row without any new props.
*/
const mockAgentContext = React.createContext<Agent | undefined>(undefined);
const mockActions = {
enterEdit: jest.fn(),
handleContinue: jest.fn(),
handleFeedback: jest.fn(),
copyToClipboard: jest.fn(),
getCanCopy: jest.fn(() => true),
regenerateMessage: jest.fn(),
};
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
useAttachments: () => ({ attachments: undefined, searchResults: undefined }),
useContentMetadata: () => ({ hasParallelContent: false }),
useMessageActions: ({
message,
chatContext,
}: {
message?: TMessage;
chatContext: TMessageChatContext;
}) => {
const { useContext } = jest.requireActual<typeof import('react')>('react');
const agent = useContext(mockAgentContext);
return {
...mockActions,
edit: false,
index: chatContext.index,
agent,
assistant: undefined,
conversation: chatContext.conversation,
messageLabel: agent?.name ?? message?.sender,
latestMessageId: chatContext.latestMessageId,
latestMessageDepth: chatContext.latestMessageDepth,
hasConfiguredSender: false,
};
},
}));
const conversation = {
conversationId: 'convo-1',
endpoint: 'agents',
agent_id: 'agent_lia',
} as TConversation;
const chatContext: TMessageChatContext = {
ask: jest.fn(),
index: 0,
regenerate: jest.fn(),
conversation,
latestMessageId: 'user-1',
latestMessageDepth: 1,
handleContinue: jest.fn(),
feedbackEnabled: false,
isSubmitting: false,
};
const assistantMessage = {
messageId: 'assistant-1',
parentMessageId: 'user-1',
conversationId: conversation.conversationId,
sender: 'agent_lia',
isCreatedByUser: false,
text: '',
content: [{ type: 'text', text: 'Done.' }],
createdAt: '2026-09-17T00:00:00.000Z',
} as TMessage;
const lia = { id: 'agent_lia', name: 'Lia' } as Agent;
const setSiblingIdx = jest.fn();
const setCurrentEditId = jest.fn();
/** Renders one row with no agent resolved yet, and lets the test land the agents list. */
const renderRow = (message: TMessage) => {
const view = (agent?: Agent) => (
<RecoilRoot>
<mockAgentContext.Provider value={agent}>
<ContentRender
message={message}
chatContext={chatContext}
siblingIdx={0}
siblingCount={1}
setSiblingIdx={setSiblingIdx}
currentEditId={null}
setCurrentEditId={setCurrentEditId}
/>
</mockAgentContext.Provider>
</RecoilRoot>
);
const result = render(view());
return { ...result, resolveAgent: (agent: Agent) => result.rerender(view(agent)) };
};
describe('ContentRender resume author header', () => {
beforeEach(() => {
mockRenders.parts = 0;
});
it('keeps the parts tree from re-rendering when the agent resolves after paint', () => {
const { resolveAgent } = renderRow(assistantMessage);
const partsRendersAtPaint = mockRenders.parts;
resolveAgent(lia);
// The row itself did re-render: its own header now names the agent.
expect(screen.getAllByTestId('message-icon')[0]).toHaveAttribute('data-agent', 'Lia');
expect(mockRenders.parts).toBe(partsRendersAtPaint);
});
it('still restates the resolved author inside the message', () => {
const { resolveAgent } = renderRow(assistantMessage);
const parts = screen.getByTestId('parts');
expect(within(parts).getByRole('heading', { level: 2 })).toHaveTextContent('agent_lia');
resolveAgent(lia);
expect(within(parts).getByRole('heading', { level: 2 })).toHaveTextContent('Lia');
expect(within(parts).getByTestId('message-icon')).toHaveAttribute('data-agent', 'Lia');
});
it('hands a user message no resume header', () => {
renderRow({ ...assistantMessage, messageId: 'user-2', isCreatedByUser: true });
expect(screen.getByTestId('parts')).toBeEmptyDOMElement();
});
});