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): optimize streaming markdown derivations

DavidShen404573454cde
diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
index af5059350d..65bb6363a5 100644
--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx
@@ -38,7 +38,11 @@ import {
} from './rehypeStreamWordFade';
import { repairStreamingMarkdown } from './repairStreamingMarkdown';
import { StreamingMarkdownChunk } from './StreamingMarkdownChunk';
-import { splitStreamingMarkdownChunks } from './streamingMarkdownChunks';
+import {
+ getStreamingMarkdownThrottleInterval,
+ splitStreamingMarkdownChunks,
+ STREAMING_MARKDOWN_THROTTLE_BASE_MS,
+} from './streamingMarkdownChunks';
import { useReducedMotion } from '@/hooks/useReducedMotion';
import { useStreamFadeEnabled } from '@/hooks/useStreamFadePreference';
import { CopyAsImageBlock, mathBlockToLatex, tableToTsv } from './CopyAsImageBlock';
@@ -320,8 +324,8 @@ interface MarkdownRendererProps {
* Stable per-session — only changes on session switch (parent remount). */
workingDir: string;
content: string;
- /** When true, react-markdown re-parse + rehype-highlight runs at most
- * ~10fps via useStreamingThrottle. The final value is always flushed
+ /** When true, react-markdown re-parse + rehype-highlight is rate-limited
+ * (10fps for short content, slower for long documents). The final value is always flushed
* synchronously when this flag flips back to false, so the completed
* message never misses its last token. Default false (static content
* paths like TextLightbox bypass the throttle entirely). */
@@ -382,8 +386,8 @@ function parseSessionCardHref(href: string): {
}
/**
- * Throttle a rapidly-changing string to at most one render per
- * `intervalMs`. Caps react-markdown re-parse + rehype-highlight CPU
+ * Throttle a rapidly-changing string to at most one render per adaptive
+ * interval. Caps react-markdown re-parse + rehype-highlight CPU
* during SDK streaming, where text deltas can land 30-60 times/s even
* after the main-process IPC batcher.
*
@@ -393,12 +397,23 @@ function parseSessionCardHref(href: string): {
* guaranteed (no-token-lost). Switching back to false flushes the
* latest value synchronously.
*/
-function useStreamingThrottle(value: string, enabled: boolean, intervalMs = 100): string {
+function useStreamingThrottle(value: string, enabled: boolean): string {
+ const intervalMs = enabled
+ ? getStreamingMarkdownThrottleInterval(value)
+ : STREAMING_MARKDOWN_THROTTLE_BASE_MS;
const [throttled, setThrottled] = useState(value);
+ const throttledRef = useRef(value);
const latestRef = useRef(value);
const lastEmitRef = useRef(0);
const timerRef = useRef<number | null>(null);
+ const emit = useCallback((nextValue: string, now: number) => {
+ lastEmitRef.current = now;
+ if (throttledRef.current === nextValue) return;
+ throttledRef.current = nextValue;
+ setThrottled(nextValue);
+ }, []);
+
useEffect(() => {
latestRef.current = value;
@@ -409,27 +424,39 @@ function useStreamingThrottle(value: string, enabled: boolean, intervalMs = 100)
}
// Stream just ended — flush whatever the most recent value is so
// the final frame is never the last throttled snapshot.
- if (throttled !== value) setThrottled(value);
+ if (throttledRef.current !== value) {
+ throttledRef.current = value;
+ setThrottled(value);
+ }
+ // A new stream should get a leading frame even if it starts shortly
+ // after the previous one ended.
+ lastEmitRef.current = 0;
return;
}
const now = performance.now();
const elapsed = now - lastEmitRef.current;
if (elapsed >= intervalMs) {
- lastEmitRef.current = now;
- setThrottled(value);
+ if (timerRef.current != null) {
+ window.clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ emit(value, now);
return;
}
- if (timerRef.current == null) {
- timerRef.current = window.setTimeout(() => {
+
+ // Re-arm on every update so an interval bucket change cannot leave a
+ // timer using the previous (shorter) delay. The latest ref keeps the
+ // trailing edge lossless even when several batches arrive in between.
+ if (timerRef.current != null) window.clearTimeout(timerRef.current);
+ timerRef.current = window.setTimeout(
+ () => {
timerRef.current = null;
- lastEmitRef.current = performance.now();
- setThrottled(latestRef.current);
- }, intervalMs - elapsed);
- }
- // No new timer needed — an in-flight one will pick up latestRef
- // when it fires.
- }, [value, enabled, intervalMs, throttled]);
+ emit(latestRef.current, performance.now());
+ },
+ Math.max(0, intervalMs - elapsed),
+ );
+ }, [emit, value, enabled, intervalMs]);
useEffect(() => {
return () => {
diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
index 9081c2c7bb..5b5361ea87 100644
--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx
+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx
@@ -53,7 +53,11 @@ import {
isPlanUserBoundary,
isSubagentParentToolUseId,
} from '@cindy/maker-shared/message-render';
-import { extractRenderedMarkdownImageTargets } from './markdownImageTargets';
+import {
+ extractCachedRenderedMarkdownImageTargets,
+ extractRenderedMarkdownImageTargets,
+ type MarkdownImageTargetCache,
+} from './markdownImageTargets';
// 子代理卡判据只能有一份:此前桌面自带一份只认 Agent/Task/collab:* 的副本,新增 harness
// (PI 的 subagent)加进共享判据也到不了 AgentTaskCard,会静默落进普通工具组(codex review)。
import { isAgentTaskToolName } from '@cindy/maker-shared/agent-task';
@@ -1450,6 +1454,8 @@ export function buildRenderItems(
workingDir?: string;
/** Bot-owned Session: show newly created files as deliverables, not an engineering diff card. */
botSessionId?: string;
+ /** Reuse image Markdown extraction for completed assistant messages across stream batches. */
+ markdownImageTargetCache?: MarkdownImageTargetCache;
},
): {
items: RenderItem[];
@@ -1499,7 +1505,14 @@ export function buildRenderItems(
const urls = new Set<string>();
for (const message of messages.slice(lo, hi)) {
if (message.role !== 'assistant' || message.systemCardType || message.isStreaming) continue;
- for (const url of extractRenderedMarkdownImageTargets(message.content)) urls.add(url);
+ const imageTargets = opts?.markdownImageTargetCache
+ ? extractCachedRenderedMarkdownImageTargets(
+ message.content,
+ opts.markdownImageTargetCache,
+ message.clientId,
+ )
+ : extractRenderedMarkdownImageTargets(message.content);
+ for (const url of imageTargets) urls.add(url);
}
inlineImageUrlsByTurnStart.set(lo, urls);
};
@@ -2697,12 +2710,18 @@ export function MessageStream({
const generatedFilesItemCacheRef = useRef(
new Map<string, Extract<RenderItem, { type: 'generated_files' }>>(),
);
+ // Completed assistant bodies are immutable for the rest of a turn, while
+ // the active tail keeps changing on every stream batch. Keep this cache at
+ // MessageStream scope so history pagination and live deltas can share the
+ // parsed image targets without retaining state beyond the session mount.
+ const markdownImageTargetCacheRef = useRef<MarkdownImageTargetCache>(new Map());
const { items: ungroupedRenderItems, singleResultMap } = useMemo(() => {
const built = buildRenderItems(messages, taskUpdates, ghostCardSnapshot, {
historyWindowIncomplete: !historyLoaded || Boolean(hasMoreMessages) || historyWindowHasIsland,
turnChangeSets,
workingDir,
botSessionId: simplifiedBotConversation ? sessionId : undefined,
+ markdownImageTargetCache: markdownImageTargetCacheRef.current,
});
return {
items: reuseGeneratedFilesRenderItems(built.items, generatedFilesItemCacheRef.current),
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts b/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts
index dd91badefe..498b4a17d2 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts
+++ b/apps/desktop/src/renderer/components/chat/__tests__/markdownImageTargets.test.ts
@@ -1,5 +1,9 @@
import { describe, expect, it } from 'vitest';
-import { extractRenderedMarkdownImageTargets } from '../markdownImageTargets';
+import {
+ extractCachedRenderedMarkdownImageTargets,
+ extractRenderedMarkdownImageTargets,
+ type MarkdownImageTargetCache,
+} from '../markdownImageTargets';
describe('extractRenderedMarkdownImageTargets', () => {
it('collects rendered images and ignores Markdown literals that render as code or raw HTML', () => {
@@ -40,4 +44,33 @@ describe('extractRenderedMarkdownImageTargets', () => {
].join('\n')),
).toEqual([url, `${url}/after-inline-code`, `${url}/raw-img`]);
});
+
+ it('reuses completed-message results and invalidates them when content changes', () => {
+ const cache: MarkdownImageTargetCache = new Map();
+ const first = extractCachedRenderedMarkdownImageTargets(
+ '![one](cindy-media://one.png)',
+ cache,
+ 'assistant-1',
+ );
+ const same = extractCachedRenderedMarkdownImageTargets(
+ '![one](cindy-media://one.png)',
+ cache,
+ 'assistant-1',
+ );
+ expect(same).toBe(first);
+
+ const changed = extractCachedRenderedMarkdownImageTargets(
+ '![two](cindy-media://two.png)',
+ cache,
+ 'assistant-1',
+ );
+ expect(changed).toEqual(['cindy-media://two.png']);
+ expect(changed).not.toBe(first);
+
+ const empty = extractCachedRenderedMarkdownImageTargets('plain text', cache, 'assistant-2');
+ expect(empty).toEqual([]);
+ expect(extractCachedRenderedMarkdownImageTargets('plain text', cache, 'assistant-2')).toBe(
+ empty,
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownChunks.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownChunks.test.tsx
index 31ff2f9f1a..230d8ff83d 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownChunks.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/streamingMarkdownChunks.test.tsx
@@ -7,11 +7,37 @@ import { afterEach, describe, expect, it } from 'vitest';
import { StreamingMarkdownChunk } from '../StreamingMarkdownChunk';
import { createWordFadeState } from '../rehypeStreamWordFade';
-import { splitStreamingMarkdownChunks } from '../streamingMarkdownChunks';
+import {
+ getStreamingMarkdownThrottleInterval,
+ splitStreamingMarkdownChunks,
+ STREAMING_MARKDOWN_THROTTLE_BASE_MS,
+ STREAMING_MARKDOWN_THROTTLE_MAX_MS,
+} from '../streamingMarkdownChunks';
afterEach(cleanup);
describe('splitStreamingMarkdownChunks', () => {
+ it('自适应节流只提高复杂长文的间隔并保持有界', () => {
+ const short = getStreamingMarkdownThrottleInterval('short prose');
+ const longSingleHeading = getStreamingMarkdownThrottleInterval(
+ `# Heading\n\n${'paragraph '.repeat(2_000)}`,
+ );
+ const longMultiHeading = getStreamingMarkdownThrottleInterval(
+ Array.from(
+ { length: 12 },
+ (_, index) => `## Section ${index}\n\n${'paragraph '.repeat(2_000)}`,
+ ).join('\n\n'),
+ );
+
+ expect(short).toBe(STREAMING_MARKDOWN_THROTTLE_BASE_MS);
+ expect(longSingleHeading).toBeGreaterThan(short);
+ expect(longMultiHeading).toBeGreaterThanOrEqual(longSingleHeading);
+ expect(longMultiHeading).toBeLessThanOrEqual(STREAMING_MARKDOWN_THROTTLE_MAX_MS);
+ expect(getStreamingMarkdownThrottleInterval('x'.repeat(320_001))).toBe(
+ STREAMING_MARKDOWN_THROTTLE_MAX_MS,
+ );
+ });
+
it('只在已经出现下一段的顶层空行后确认稳定前缀', () => {
expect(splitStreamingMarkdownChunks('alpha\n\n')).toEqual([
{ start: 0, content: 'alpha\n\n' },
diff --git a/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts b/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts
index b2159df1df..e0d389518b 100644
--- a/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts
+++ b/apps/desktop/src/renderer/components/chat/markdownImageTargets.ts
@@ -11,6 +11,19 @@ const markdownImageParser = unified()
.use(remarkParse)
.use(REMARK_PLUGINS_PRIVILEGED);
+/**
+ * Per-session cache for image targets extracted from completed assistant
+ * messages. The content is checked as well as the client id because a live
+ * message is updated in place while it streams; stale targets must never
+ * leak into the next turn.
+ */
+export interface MarkdownImageTargetCacheEntry {
+ content: string;
+ targets: string[];
+}
+
+export type MarkdownImageTargetCache = Map<string, MarkdownImageTargetCacheEntry>;
+
/** 与 MarkdownRenderer 同源解析,只返回实际会进入 img renderer 的图片地址。 */
export function extractRenderedMarkdownImageTargets(markdown: string): string[] {
if (!markdown.includes('![') && !/<img/i.test(markdown)) return [];
@@ -26,3 +39,21 @@ export function extractRenderedMarkdownImageTargets(markdown: string): string[]
});
return urls;
}
+
+/**
+ * Read or populate the completed-message cache used by MessageStream.
+ * Empty results are cached too: most assistant messages contain no images,
+ * and treating that as a cacheable result avoids repeatedly parsing prose.
+ */
+export function extractCachedRenderedMarkdownImageTargets(
+ markdown: string,
+ cache: MarkdownImageTargetCache,
+ cacheKey: string,
+): string[] {
+ const cached = cache.get(cacheKey);
+ if (cached?.content === markdown) return cached.targets;
+
+ const targets = extractRenderedMarkdownImageTargets(markdown);
+ cache.set(cacheKey, { content: markdown, targets });
+ return targets;
+}
diff --git a/apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts b/apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts
index f2ec6a0305..ea6a1eec30 100644
--- a/apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts
+++ b/apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts
@@ -87,6 +87,36 @@ function needsWholeDocumentContext(markdown: string): boolean {
);
}
+export const STREAMING_MARKDOWN_THROTTLE_BASE_MS = 100;
+export const STREAMING_MARKDOWN_THROTTLE_MAX_MS = 400;
+
+/**
+ * Choose a bounded stream update interval from the amount of Markdown work.
+ *
+ * Multi-heading documents intentionally stay one ReactMarkdown tree so heading
+ * ids, reference definitions, and raw HTML keep their document-wide context.
+ * Increasing the interval for those expensive trees reduces repeated parse /
+ * highlight work without changing the rendered source or chunk boundaries.
+ * The caller still flushes the latest value when streaming ends.
+ */
+export function getStreamingMarkdownThrottleInterval(markdown: string): number {
+ const length = markdown.length;
+ let interval = STREAMING_MARKDOWN_THROTTLE_BASE_MS;
+
+ if (length > 12_000) interval = 125;
+ if (length > 32_000) interval = 175;
+ if (length > 80_000) interval = 250;
+ if (length > 160_000) interval = 325;
+ if (length > 320_000) interval = STREAMING_MARKDOWN_THROTTLE_MAX_MS;
+
+ // Length is intentionally the only signal here. This function runs on
+ // every incoming token before the throttle can coalesce it; scanning for
+ // headings or HTML at that point would recreate the O(n) work we are trying
+ // to avoid. The length buckets conservatively cover long multi-heading,
+ // fenced-code, and HTML-heavy documents alike.
+ return Math.min(interval, STREAMING_MARKDOWN_THROTTLE_MAX_MS);
+}
+
/**
* 把流式 Markdown 切成已经封口的顶层前缀块与仍在增长的尾块。
*