Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

perf(desktop): reuse unchanged streaming markdown blocks

DavidShenceb279db0b85
diff --git a/apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx b/apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx
index d2e160661d..cbc2a9dcb7 100644
--- a/apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx
+++ b/apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx
@@ -1,6 +1,7 @@
import type {
AnimationEvent as ReactAnimationEvent,
ComponentPropsWithoutRef,
+ CSSProperties,
} from 'react';
import { useCallback } from 'react';
import type { Element } from 'hast';
@@ -36,6 +37,15 @@ function removeStreamWordClass(className?: string): string | undefined {
return next || undefined;
}
+function withoutWordFadeDelay(style: CSSProperties | undefined, key?: string): CSSProperties | undefined {
+ if (!key || !style) return style;
+ // The ref owns the absolute timeline on this DOM node. Reapplying a relative
+ // delay on every parse both seeks an in-flight animation and invalidates the
+ // style of every historical word. Only a remount needs to restore its delay.
+ const { ['--wf-delay']: _delay, ...rest } = style as CSSProperties & { '--wf-delay'?: string };
+ return Object.keys(rest).length > 0 ? rest : undefined;
+}
+
/**
* ReactMarkdown 给自定义 renderer 的外层 key 是位置型 span-N。这里再用逻辑 key
* 标识真实 DOM span:位置被复用给别的段时会 remount,旧动画不能污染新段。
@@ -79,6 +89,7 @@ export function StreamFadeSpan({
ref={attachSpan}
{...props}
className={settled ? removeStreamWordClass(props.className) : props.className}
+ style={withoutWordFadeDelay(props.style, wordFadeKey)}
data-wf-key={wordFadeKey}
onAnimationEnd={handleAnimationEnd}
>
@@ -127,6 +138,7 @@ export function StreamFadeListItem({
ref={attachListItem}
{...markerProps}
data-stream-marker={settled ? undefined : markerProps['data-stream-marker']}
+ style={withoutWordFadeDelay(props.style, wordFadeKey)}
data-wf-key={wordFadeKey}
onAnimationEnd={handleAnimationEnd}
>
diff --git a/apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx b/apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx
index fa5604d6f0..3d79b48c9b 100644
--- a/apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx
+++ b/apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx
@@ -13,6 +13,7 @@ import {
type WordFadeState,
} from './rehypeStreamWordFade';
import { StreamFadeListItem, StreamFadeSpan } from './StreamFadeSpan';
+import { createStreamingMarkdownBlockCache, withStreamingMarkdownBlocks } from './streamingMarkdownBlocks';
interface StreamingMarkdownChunkProps {
sourceKey: string;
@@ -57,9 +58,15 @@ export const StreamingMarkdownChunk = memo(function StreamingMarkdownChunk({
wholeDocument && wordFadeState
? createWholeDocumentWordFadeCandidate(wordFadeState, sourceWordFadeState)
: createWordFadeCandidate(sourceWordFadeState);
+ const blocks = createStreamingMarkdownBlockCache();
return {
candidate,
- plugins: [...rehypePlugins, [rehypeStreamWordFade, candidate]] as PluggableList,
+ plugins: [
+ ...rehypePlugins,
+ blocks.capture,
+ [rehypeStreamWordFade, candidate],
+ blocks.wrap,
+ ] as PluggableList,
};
}, [content, rehypePlugins, sourceWordFadeState, wholeDocument, wordFadeState]);
@@ -90,11 +97,16 @@ export const StreamingMarkdownChunk = memo(function StreamingMarkdownChunk({
};
}, [components, emitSourceLines, sourceWordFadeState]);
+ const cachedComponents = useMemo(
+ () => sourceWordFadeState ? withStreamingMarkdownBlocks(chunkComponents, urlTransform) : chunkComponents,
+ [chunkComponents, sourceWordFadeState, urlTransform],
+ );
+
return (
<ReactMarkdown
remarkPlugins={remarkPlugins}
rehypePlugins={wordFade?.plugins ?? rehypePlugins}
- components={chunkComponents}
+ components={cachedComponents}
urlTransform={urlTransform}
skipHtml
>
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/StreamFadeSpan.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/StreamFadeSpan.test.tsx
index cd46c76dc4..3ff7dc21f6 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/StreamFadeSpan.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/StreamFadeSpan.test.tsx
@@ -167,6 +167,38 @@ describe('StreamFadeSpan', () => {
]);
});
+ it('追加内容不改写既有词的 delay,既不重算旧样式也不快进活动动画', () => {
+ const state = createWordFadeState();
+ let now = 0;
+ state.timeline.nowFn = () => now;
+ const view = render(<StreamingMarkdownHarness content="one two three" state={state} />);
+ const first = view.container.querySelector<HTMLSpanElement>('[data-wf-key]')!;
+ const write = vi.spyOn(first.style, 'setProperty');
+ now = 50;
+ view.rerender(<StreamingMarkdownHarness content="one two three four" state={state} />);
+ expect(write).not.toHaveBeenCalled();
+ expect(first.style.getPropertyValue('--wf-delay')).toBe('0ms');
+ fireAnimationEnd(first);
+ now = 500;
+ view.rerender(<StreamingMarkdownHarness content="one two three four five" state={state} />);
+ expect(write).not.toHaveBeenCalled();
+ expect(view.container.querySelector('[data-wf-key]')).toBe(first);
+ expect(first.classList.contains('stream-word')).toBe(false);
+ write.mockRestore();
+ });
+
+ it('活动词重挂载才根据绝对开始时刻恢复负 delay', () => {
+ const state = createWordFadeState();
+ let now = 0;
+ state.timeline.nowFn = () => now;
+ const first = render(<StreamingMarkdownHarness content="one two" state={state} />);
+ first.unmount();
+ now = 75;
+ const second = render(<StreamingMarkdownHarness content="one two" state={state} />);
+ expect(Array.from(second.container.querySelectorAll<HTMLElement>('[data-wf-key]'),
+ (node) => node.style.getPropertyValue('--wf-delay'))).toEqual(['-75ms', '-59ms']);
+ });
+
it('千级突发段把透明等待限制在 160ms 内,同时保留前段节奏', () => {
const state = createWordFadeState();
state.timeline.nowFn = () => 0;
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownBlocks.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownBlocks.test.tsx
new file mode 100644
index 0000000000..d65f39ccd7
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownBlocks.test.tsx
@@ -0,0 +1,130 @@
+// @vitest-environment jsdom
+
+import { cleanup, render } from '@testing-library/react';
+import ReactMarkdown, { type Components, type UrlTransform } from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+import rehypeSlug from 'rehype-slug';
+import type { PluggableList } from 'unified';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { StreamingMarkdownChunk } from '../StreamingMarkdownChunk';
+import { createWordFadeState, type WordFadeState } from '../rehypeStreamWordFade';
+
+afterEach(cleanup);
+
+const remarkPlugins: PluggableList = [remarkGfm];
+const rehypePlugins: PluggableList = [rehypeSlug];
+const defaultComponents: Components = { img: ({ node: _node, src, ...props }) => <img {...props} src={src || undefined} /> };
+
+function Harness({ content, state, components = defaultComponents, urlTransform }: {
+ content: string;
+ state: WordFadeState;
+ components?: Components;
+ urlTransform?: UrlTransform;
+}) {
+ return <StreamingMarkdownChunk
+ sourceKey="0"
+ content={content}
+ remarkPlugins={remarkPlugins}
+ rehypePlugins={rehypePlugins}
+ components={components}
+ urlTransform={urlTransform}
+ wordFadeState={state}
+ emitSourceLines={false}
+ wholeDocument
+ />;
+}
+
+function withoutFadeMarkup(container: HTMLElement): string {
+ const clone = container.cloneNode(true) as HTMLElement;
+ for (const element of clone.querySelectorAll('[data-wf-key]')) {
+ if (element.tagName === 'SPAN') element.replaceWith(...element.childNodes);
+ else {
+ element.removeAttribute('data-wf-key');
+ element.removeAttribute('data-stream-marker');
+ element.removeAttribute('style');
+ }
+ }
+ return clone.innerHTML;
+}
+
+describe('streaming Markdown block reuse', () => {
+ it('长文追加只渲染变化的块,旧词的 DOM、样式与选择锚点均不变', () => {
+ const state = createWordFadeState();
+ let now = 0;
+ state.timeline.nowFn = () => now;
+ const renderParagraph = vi.fn();
+ const components: Components = {
+ p: ({ children }) => { renderParagraph(); return <p>{children}</p>; },
+ };
+ const prefix = Array.from({ length: 80 }, (_, i) => `## Heading ${i}\n\nold paragraph ${i}\n\n`).join('');
+ const view = render(<Harness content={`${prefix}live`} state={state} components={components} />);
+ const paragraph = view.container.querySelector('p')!;
+ const word = paragraph.querySelector('[data-wf-key]')!;
+ const selection = window.getSelection()!;
+ const range = document.createRange();
+ range.selectNodeContents(word);
+ selection.removeAllRanges();
+ selection.addRange(range);
+ const anchor = selection.anchorNode;
+ const selected = selection.toString();
+ const observer = new MutationObserver(() => {});
+ observer.observe(paragraph, { subtree: true, attributes: true, childList: true, characterData: true });
+ renderParagraph.mockClear();
+ now = 500;
+ view.rerender(<Harness content={`${prefix}live grows`} state={state} components={components} />);
+ expect(renderParagraph).toHaveBeenCalledTimes(1);
+ expect(view.container.querySelector('p')).toBe(paragraph);
+ expect(paragraph.querySelector('[data-wf-key]')).toBe(word);
+ expect(observer.takeRecords()).toEqual([]);
+ expect(selection.anchorNode).toBe(anchor);
+ expect(selection.toString()).toBe(selected);
+ expect(view.container.querySelector('cindy-stream-block')).toBeNull();
+ observer.disconnect();
+ selection.removeAllRanges();
+ });
+
+ it.each([
+ '# Same\n\nbody\n\n# Same\n\n[guide]\n\n[guide]: https://example.com',
+ '# First\n\ntext[^note]\n\n# Second\n\n[^note]: footnote body',
+ '# First\n\n<details>\n<script>hidden()</script>\n\nhidden block\n</details>\n\n# Second',
+ '# First\n\n- **bold** and `inline`\n- next\n\n# Second\n\n```ts\nconst a = 1;\n```\n\n| x | y |\n| - | - |\n| a | b |',
+ '# First\n\n[safe](https://example.com) [unsafe](javascript:alert) ![bad](javascript:alert)\n\n# Second',
+ ])('缓存保留整篇语义及 ReactMarkdown 的安全过滤:%s', (content) => {
+ const cached = render(<Harness content={content} state={createWordFadeState()} />);
+ const plain = render(<ReactMarkdown remarkPlugins={remarkPlugins} rehypePlugins={rehypePlugins} components={defaultComponents} skipHtml>{content}</ReactMarkdown>);
+ expect(withoutFadeMarkup(cached.container)).toBe(plain.container.innerHTML);
+ });
+
+ it('晚到的引用定义让旧块失效;重复标题的全局 slug 仍唯一', () => {
+ const state = createWordFadeState();
+ const prefix = '# Same\n\nSee [guide].\n\n# Same\n\nother';
+ const view = render(<Harness content={prefix} state={state} />);
+ expect(view.container.querySelector('a')).toBeNull();
+ view.rerender(<Harness content={`${prefix}\n\n[guide]: https://example.com`} state={state} />);
+ expect(view.container.querySelector('a')?.getAttribute('href')).toBe('https://example.com');
+ expect(Array.from(view.container.querySelectorAll('h1'), node => node.id)).toEqual(['same', 'same-1']);
+ });
+
+ it('components 或 URL 策略改变时不能复用旧结果', () => {
+ const state = createWordFadeState();
+ const content = '# Heading\n\n[guide](https://example.com)';
+ const view = render(<Harness content={content} state={state} />);
+ const components: Components = { p: ({ children }) => <p title="changed context">{children}</p> };
+ view.rerender(<Harness content={content} state={state} components={components} />);
+ expect(view.container.querySelector('p')?.title).toBe('changed context');
+ view.rerender(<Harness content={content} state={state} components={components} urlTransform={() => ''} />);
+ expect(view.container.querySelector('a')?.getAttribute('href')).toBe('');
+ view.rerender(<Harness content={content} state={state} components={components} />);
+ expect(view.container.querySelector('a')?.getAttribute('href')).toBe('https://example.com');
+ });
+
+ it('语义块改变但后文相同时,匹配状态与实际 DOM 的 key 保持一致', () => {
+ const state = createWordFadeState();
+ const view = render(<Harness content={'# First\n\none two\n\n# Second\n\none two'} state={state} />);
+ view.rerender(<Harness content={'# First\n\n`one two`\n\n# Second\n\none two'} state={state} />);
+ const domKeys = Array.from(view.container.querySelectorAll('span[data-wf-key]'), node => node.getAttribute('data-wf-key'));
+ expect(domKeys).toEqual(state.sourceStateByKey.get('0')!.previous.map(segment => segment.key));
+ expect(new Set(domKeys).size).toBe(domKeys.length);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx b/apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx
new file mode 100644
index 0000000000..26b504e14e
--- /dev/null
+++ b/apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx
@@ -0,0 +1,106 @@
+import { memo, useMemo } from 'react';
+import ReactMarkdown, { type Components, type UrlTransform } from 'react-markdown';
+import type { Element, Root } from 'hast';
+import type { Plugin, PluggableList } from 'unified';
+
+const BLOCK_TAG = 'cindy-stream-block';
+
+interface BlockSnapshot {
+ signature: string;
+ tree: Root;
+}
+
+interface BlockElement extends Element {
+ data: NonNullable<Element['data']> & { streamBlock: BlockSnapshot };
+}
+
+interface BlockProps extends BlockSnapshot {
+ components: Components;
+ urlTransform?: UrlTransform;
+}
+
+/**
+ * Keep the already-committed React subtree (including active animation refs and
+ * selection anchors). The signature is taken AFTER document-wide plugins but
+ * BEFORE word-fade timing, so late references/slug changes invalidate it while
+ * the passage of time does not.
+ */
+const StreamingMarkdownBlock = memo(function StreamingMarkdownBlock({
+ tree,
+ components,
+ urlTransform,
+}: BlockProps) {
+ const plugins = useMemo<PluggableList>(() => [
+ // ReactMarkdown's post-processing mutates URL properties. Keep the source
+ // intact so a later URL policy/components change starts from original URLs.
+ (() => () => structuredClone(tree)) as Plugin<[], Root>,
+ ], [tree]);
+ // Reuse ReactMarkdown's own HTML skipping and URL filtering, rather than
+ // creating a parallel HAST-to-DOM policy for cached blocks. No source is
+ // reparsed: the plugin supplies the block from the full-document parse.
+ return (
+ <ReactMarkdown rehypePlugins={plugins} components={components} urlTransform={urlTransform} skipHtml>
+ {''}
+ </ReactMarkdown>
+ );
+}, (previous, next) =>
+ previous.signature === next.signature &&
+ previous.components === next.components &&
+ previous.urlTransform === next.urlTransform,
+);
+
+/** Candidate-local only; React.memo, not a mutable module cache, publishes reuse. */
+export function createStreamingMarkdownBlockCache() {
+ const signatures = new WeakMap<Element, string>();
+ const capture: Plugin<[], Root> = () => (tree) => {
+ for (const node of tree.children) {
+ if (node.type === 'element') signatures.set(node, JSON.stringify(node));
+ }
+ };
+ const wrap: Plugin<[], Root> = () => (tree) => {
+ tree.children = tree.children.map((node) => {
+ if (node.type !== 'element') return node;
+ const signature = signatures.get(node);
+ if (signature === undefined) return node;
+ // Content can move when earlier Markdown changes structure. Equal prose
+ // alone must not reuse a DOM tree whose logical fade identities changed.
+ const keys: string[] = [];
+ const collectKeys = (element: Element) => {
+ const key = element.properties.dataWfKey;
+ if (typeof key === 'string') keys.push(key);
+ for (const child of element.children) {
+ if (child.type === 'element') collectKeys(child);
+ }
+ };
+ collectKeys(node);
+ const block: BlockElement = {
+ type: 'element',
+ tagName: BLOCK_TAG,
+ properties: {},
+ children: [],
+ data: { streamBlock: {
+ signature: `${signature}\n${JSON.stringify(keys)}`,
+ tree: { type: 'root', children: [node] },
+ } },
+ };
+ return block;
+ });
+ };
+ return { capture, wrap };
+}
+
+export function withStreamingMarkdownBlocks(
+ components: Components,
+ urlTransform?: UrlTransform,
+): Components {
+ const blockComponents = {
+ [BLOCK_TAG]: ({ node }: { node: BlockElement }) => (
+ <StreamingMarkdownBlock
+ {...node.data.streamBlock}
+ components={components}
+ urlTransform={urlTransform}
+ />
+ ),
+ };
+ return { ...components, ...blockComponents };
+}