From b7247521a5194b59441092d7065a91b4a45e89ac Mon Sep 17 00:00:00 2001 From: phantom5099 <1011668688@qq.com> Date: Mon, 23 Nov 2026 02:02:35 +0800 Subject: [PATCH 1/2] perf: reduce desktop streaming render cost --- packages/desktop/src/agent/MessageStream.tsx | 90 +++++++-- packages/desktop/src/hooks/useAgent.ts | 32 ++- .../desktop/src/shared/MarkdownRenderer.tsx | 24 ++- packages/desktop/src/shared/MessageItem.tsx | 2 +- packages/desktop/src/shared/ToolCallGroup.tsx | 8 +- packages/desktop/src/shared/ToolSummary.tsx | 8 +- packages/desktop/src/stores/agent.store.ts | 188 +++++++++--------- .../desktop/test/MarkdownRenderer.test.ts | 8 + packages/desktop/test/global-store.test.ts | 36 ++++ 9 files changed, 270 insertions(+), 126 deletions(-) diff --git a/packages/desktop/src/agent/MessageStream.tsx b/packages/desktop/src/agent/MessageStream.tsx index 3033d9d0..8ce31f18 100644 --- a/packages/desktop/src/agent/MessageStream.tsx +++ b/packages/desktop/src/agent/MessageStream.tsx @@ -19,6 +19,51 @@ interface MessageStreamProps { const EMPTY_MAPPING: Record = {}; +interface MessageEntryProps { + threadId: string; + turnId: string; + item: Item; + cwd: string; + onApprove: (threadId: string, callId: string) => void; + onReject: (threadId: string, callId: string) => void; + callIdToToolName: Record; + onRollbackHere?: () => void; + onForkFromHere?: () => void; + toolResult?: Item & { type: 'tool_result' }; +} + +function StreamingMessageEntry({ + threadId, + turnId, + item, + cwd, + onApprove, + onReject, + callIdToToolName, + onRollbackHere, + onForkFromHere, + toolResult, +}: MessageEntryProps) { + const currentItem = useAgentStore((state) => { + const turn = state.threads[threadId]?.turns.find((candidate) => candidate.id === turnId); + return turn?.items.find((candidate) => candidate.id === item.id) ?? item; + }); + + return ( + + ); +} + interface TurnDiffPanelProps { uiTurnId: string; isInterrupted?: boolean; @@ -258,15 +303,7 @@ export default function MessageStream({ threadId }: MessageStreamProps) { .map( (t) => `${t.id}:${t.status}:${t.items.length}:${t.items - .map((i) => { - const contentSize = - i.type === 'reasoning' - ? i.content.length - : i.type === 'message' - ? textOf(i.parts).length - : ''; - return `${i.type}:${i.id}:${i.type === 'tool_call' ? i.status : ''}:${contentSize}`; - }) + .map((i) => `${i.type}:${i.id}:${i.type === 'tool_call' ? i.status : ''}`) .join(',')}` ) .join('|'), @@ -618,17 +655,30 @@ export default function MessageStream({ threadId }: MessageStreamProps) { {entry.toolCalls ? ( ) : entry.item ? ( - + (() => { + const isStreamingItem = + (entry.item.type === 'message' && + entry.item.role === 'assistant' && + entry.item.partial === true) || + (entry.item.type === 'reasoning' && entry.item.partial === true); + const props = { + turnId: entry.turnId, + item: entry.item, + threadId, + cwd: threadCwd, + onApprove: approveTool, + onReject: rejectTool, + callIdToToolName, + onRollbackHere: isUserMsg && cbs ? cbs.onRollbackHere : undefined, + onForkFromHere: isUserMsg && cbs ? cbs.onForkFromHere : undefined, + toolResult: entry.toolResult, + }; + return isStreamingItem ? ( + + ) : ( + + ); + })() ) : null} {isLastInTurn && diff --git a/packages/desktop/src/hooks/useAgent.ts b/packages/desktop/src/hooks/useAgent.ts index e17e47b9..d3af3e69 100644 --- a/packages/desktop/src/hooks/useAgent.ts +++ b/packages/desktop/src/hooks/useAgent.ts @@ -90,6 +90,7 @@ export function useAgentCore() { const sendQueuedInputRef = useRef<((threadId: string) => Promise) | null>(null); const startTurn = useAgentStore((s) => s.startTurn); const applyChunk = useAgentStore((s) => s.applyChunk); + const applyChunks = useAgentStore((s) => s.applyChunks); const updateTurnId = useAgentStore((s) => s.updateTurnId); const completeTurn = useAgentStore((s) => s.completeTurn); const setPendingInput = useAgentStore((s) => s.setPendingInput); @@ -228,8 +229,33 @@ export function useAgentCore() { if (!opts.preRegistered) registerInflight(threadId, controller); const state = createStreamState(randomId()); + const pendingChunks: Array<{ turnId: string; chunk: Item }> = []; + let flushScheduled = false; + + const flushPending = () => { + flushScheduled = false; + if (pendingChunks.length === 0) return; + const updates = pendingChunks.splice(0, pendingChunks.length); + applyChunks(threadId, updates); + }; + + const scheduleFlush = () => { + if (flushScheduled) return; + flushScheduled = true; + if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') { + window.requestAnimationFrame(flushPending); + } else { + setTimeout(flushPending, 16); + } + }; + + const enqueueItem = (item: Item) => { + pendingChunks.push({ turnId: activeTurnId, chunk: item }); + scheduleFlush(); + }; + const fx: StreamEffects = { - applyItem: (item) => applyChunk(threadId, activeTurnId, item), + applyItem: enqueueItem, applyTodo: (items) => applyTodoUpdate(threadId, items), setUsage: (usage) => { setThreadUsage(threadId, usage); @@ -241,6 +267,7 @@ export function useAgentCore() { useAgentStore.getState().clearThreadUsage(threadId); }, syncTurnId: (turnId) => { + flushPending(); const next = String(turnId); updateTurnId(threadId, activeTurnId, next); activeTurnId = next; @@ -267,8 +294,10 @@ export function useAgentCore() { } catch (err: any) { failed = true; const msg = err instanceof ApiError ? (err.body?.message ?? err.message) : String(err); + flushPending(); applyChunk(threadId, activeTurnId, { id: randomId(), type: 'error', message: msg }); } finally { + flushPending(); completeTurn(threadId, activeTurnId, failed || state.hasError ? 'error' : 'completed'); if (!failed && !state.hasError && state.planTitle !== null) { setPendingPlan(threadId, { sessionId: threadId, title: state.planTitle }); @@ -281,6 +310,7 @@ export function useAgentCore() { [ startTurn, applyChunk, + applyChunks, applyTodoUpdate, completeTurn, setPendingPlan, diff --git a/packages/desktop/src/shared/MarkdownRenderer.tsx b/packages/desktop/src/shared/MarkdownRenderer.tsx index ed5a2c19..4bf1277b 100644 --- a/packages/desktop/src/shared/MarkdownRenderer.tsx +++ b/packages/desktop/src/shared/MarkdownRenderer.tsx @@ -4,12 +4,16 @@ import remarkGfm from 'remark-gfm'; import rehypeRaw from 'rehype-raw'; import CodeBlock from './CodeBlock'; +const REMARK_PLUGINS = [remarkGfm]; +const REHYPE_PLUGINS = [rehypeRaw]; + interface MarkdownRendererProps { content: string; className?: string; + partial?: boolean; } -export default function MarkdownRenderer({ content, className }: MarkdownRendererProps) { +export default function MarkdownRenderer({ content, className, partial = false }: MarkdownRendererProps) { const components = useMemo( () => ({ code(props: React.HTMLAttributes & { inline?: boolean }) { @@ -72,13 +76,17 @@ export default function MarkdownRenderer({ content, className }: MarkdownRendere return (
- - {content} - + {partial ? ( +
{content}
+ ) : ( + + {content} + + )}
); } diff --git a/packages/desktop/src/shared/MessageItem.tsx b/packages/desktop/src/shared/MessageItem.tsx index 76d08dfe..ab08d9f9 100644 --- a/packages/desktop/src/shared/MessageItem.tsx +++ b/packages/desktop/src/shared/MessageItem.tsx @@ -210,7 +210,7 @@ const MessageItem = memo(function MessageItem({
{text && (
- + {item.partial && ( )} diff --git a/packages/desktop/src/shared/ToolCallGroup.tsx b/packages/desktop/src/shared/ToolCallGroup.tsx index b38b5867..3cfbd95e 100644 --- a/packages/desktop/src/shared/ToolCallGroup.tsx +++ b/packages/desktop/src/shared/ToolCallGroup.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { memo, useState } from 'react'; import { ChevronDown, ChevronRight, Wrench } from 'lucide-react'; import type { Item } from '@shared/types'; import ToolSummary from './ToolSummary'; @@ -14,7 +14,7 @@ function statusLabel(entries: ToolCallEntry[]): string { return '已完成'; } -export default function ToolCallGroup({ entries }: { entries: ToolCallEntry[] }) { +const ToolCallGroup = memo(function ToolCallGroup({ entries }: { entries: ToolCallEntry[] }) { const [open, setOpen] = useState(false); if (entries.length === 1) return ; const status = statusLabel(entries); @@ -48,4 +48,6 @@ export default function ToolCallGroup({ entries }: { entries: ToolCallEntry[] }) )}
); -} +}); + +export default ToolCallGroup; diff --git a/packages/desktop/src/shared/ToolSummary.tsx b/packages/desktop/src/shared/ToolSummary.tsx index f395daf4..fc5c0bde 100644 --- a/packages/desktop/src/shared/ToolSummary.tsx +++ b/packages/desktop/src/shared/ToolSummary.tsx @@ -1,4 +1,4 @@ -import { useState, useMemo } from 'react'; +import { memo, useState, useMemo } from 'react'; import { ChevronRight, ChevronDown, FilePenLine, FileText, Folder, Globe, Search, Terminal, Wrench } from 'lucide-react'; import type { Item } from '@shared/types'; import { buildToolDiff } from '../lib/diff-compute'; @@ -113,7 +113,7 @@ export function buildToolSummaryTitle( }; } -export default function ToolSummary({ toolCall, toolResult }: ToolSummaryProps) { +const ToolSummary = memo(function ToolSummary({ toolCall, toolResult }: ToolSummaryProps) { const [open, setOpen] = useState(false); const isFileTool = toolCall.name === 'write_file' || toolCall.name === 'edit_file'; @@ -184,4 +184,6 @@ export default function ToolSummary({ toolCall, toolResult }: ToolSummaryProps) )}
); -} +}); + +export default ToolSummary; diff --git a/packages/desktop/src/stores/agent.store.ts b/packages/desktop/src/stores/agent.store.ts index 771fac30..666a466e 100644 --- a/packages/desktop/src/stores/agent.store.ts +++ b/packages/desktop/src/stores/agent.store.ts @@ -24,6 +24,95 @@ function appendText(parts: ContentPart[], text: string): void { else parts.push({ type: 'text', text }); } +function applyChunkToThread(thread: Thread, turnId: string, chunk: Item): void { + const turn = thread.turns.find((t) => t.id === turnId); + if (!turn) return; + + if (chunk.type === 'message' && chunk.role === 'assistant' && chunk.partial) { + const existing = turn.items.find((i) => i.id === chunk.id); + if (existing && existing.type === 'message' && existing.role === 'assistant') { + appendText(existing.parts, textOf(chunk.parts)); + existing.partial = true; + } else { + turn.items.push({ ...chunk, partial: true }); + } + return; + } + + if (chunk.type === 'message' && chunk.role === 'assistant' && chunk.partial === false) { + const existing = turn.items.findIndex((i) => i.id === chunk.id); + if (existing >= 0) { + const current = turn.items[existing]; + if (!current) return; + if (current.type === 'message' && current.role === 'assistant') { + turn.items[existing] = { + ...chunk, + parts: current.parts.length > 0 ? current.parts : chunk.parts, + partial: false, + }; + } else { + turn.items[existing] = { ...chunk, partial: false }; + } + } else { + turn.items.push({ ...chunk, partial: false }); + } + return; + } + + if (chunk.type === 'tool_call') { + const existing = turn.items.findIndex((i) => i.id === chunk.id); + if (existing >= 0) { + const existingItem = turn.items[existing] as Item & { status?: string }; + if (existingItem.status === 'pending' && chunk.status === 'running') return; + turn.items[existing] = { + ...chunk, + args: + Object.keys(chunk.args ?? {}).length > 0 + ? chunk.args + : existingItem.type === 'tool_call' + ? existingItem.args + : chunk.args, + }; + } else { + turn.items.push(chunk); + } + return; + } + + if (chunk.type === 'tool_result') { + let targetChunk = chunk; + const callIdx = turn.items.findIndex( + (i) => i.type === 'tool_call' && i.id === chunk.callId + ); + if (callIdx >= 0) { + const callItem = turn.items[callIdx] as any; + if (callItem.status !== 'rejected') callItem.status = 'approved'; + targetChunk = buildToolDiff(chunk, callItem) as any; + turn.items.push(targetChunk); + return; + } + for (const otherTurn of thread.turns) { + if (otherTurn === turn) continue; + const otherCallIdx = otherTurn.items.findIndex( + (i) => i.type === 'tool_call' && i.id === chunk.callId + ); + if (otherCallIdx >= 0) { + const callItem = otherTurn.items[otherCallIdx] as any; + if (callItem.status !== 'rejected') callItem.status = 'approved'; + targetChunk = buildToolDiff(chunk, callItem) as any; + otherTurn.items.push(targetChunk); + return; + } + } + turn.items.push(targetChunk); + return; + } + + const existing = turn.items.findIndex((i) => i.id === chunk.id); + if (existing >= 0) turn.items[existing] = chunk; + else turn.items.push(chunk); +} + function randomId(): string { return crypto.randomUUID ? crypto.randomUUID() : Math.random().toString(36).slice(2, 11); } @@ -123,6 +212,7 @@ interface AgentActions { meta?: { cwd?: string; title?: string; model?: string } ) => void; applyChunk: (threadId: string, turnId: string, chunk: Item) => void; + applyChunks: (threadId: string, updates: Array<{ turnId: string; chunk: Item }>) => void; updateTurnId: (threadId: string, oldTurnId: string, newTurnId: string) => void; completeTurn: (threadId: string, turnId: string, status: 'completed' | 'error') => void; setPendingInput: (input: string | null) => void; @@ -397,97 +487,15 @@ export const useAgentStore = create()( applyChunk: (threadId, turnId, chunk) => set((s) => { const thread = s.threads[threadId]; - if (!thread) return; - const turn = thread.turns.find((t) => t.id === turnId); - if (!turn) return; - - if (chunk.type === 'message' && chunk.role === 'assistant' && chunk.partial) { - const existing = turn.items.find((i) => i.id === chunk.id); - if (existing && existing.type === 'message' && existing.role === 'assistant') { - appendText(existing.parts, textOf(chunk.parts)); - existing.partial = true; - } else { - turn.items.push({ ...chunk, partial: true }); - } - return; - } - - if (chunk.type === 'message' && chunk.role === 'assistant' && chunk.partial === false) { - const existing = turn.items.findIndex((i) => i.id === chunk.id); - if (existing >= 0) { - const current = turn.items[existing]; - if (!current) return; - if (current.type === 'message' && current.role === 'assistant') { - turn.items[existing] = { - ...chunk, - parts: current.parts.length > 0 ? current.parts : chunk.parts, - partial: false, - }; - } else { - turn.items[existing] = { ...chunk, partial: false }; - } - } else { - turn.items.push({ ...chunk, partial: false }); - } - return; - } - - if (chunk.type === 'tool_call') { - const existing = turn.items.findIndex((i) => i.id === chunk.id); - if (existing >= 0) { - const existingItem = turn.items[existing] as Item & { status?: string }; - if (existingItem.status === 'pending' && chunk.status === 'running') { - return; - } - turn.items[existing] = { - ...chunk, - args: Object.keys(chunk.args ?? {}).length > 0 ? chunk.args : - existingItem.type === 'tool_call' ? existingItem.args : chunk.args, - }; - } else { - turn.items.push(chunk); - } - return; - } - - if (chunk.type === 'tool_result') { - let targetChunk = chunk; - const callIdx = turn.items.findIndex( - (i) => i.type === 'tool_call' && i.id === chunk.callId - ); - if (callIdx >= 0) { - const callItem = turn.items[callIdx] as any; - if (callItem.status !== 'rejected') { - callItem.status = 'approved'; - } - targetChunk = buildToolDiff(chunk, callItem) as any; - turn.items.push(targetChunk); - return; - } - for (const t of thread.turns) { - if (t === turn) continue; - const otherCallIdx = t.items.findIndex( - (i) => i.type === 'tool_call' && i.id === chunk.callId - ); - if (otherCallIdx >= 0) { - const callItem = t.items[otherCallIdx] as any; - if (callItem.status !== 'rejected') { - callItem.status = 'approved'; - } - targetChunk = buildToolDiff(chunk, callItem) as any; - t.items.push(targetChunk); - return; - } - } - turn.items.push(targetChunk); - return; - } + if (thread) applyChunkToThread(thread, turnId, chunk); + }), - const existing = turn.items.findIndex((i) => i.id === chunk.id); - if (existing >= 0) { - turn.items[existing] = chunk; - } else { - turn.items.push(chunk); + applyChunks: (threadId, updates) => + set((s) => { + const thread = s.threads[threadId]; + if (!thread) return; + for (const update of updates) { + applyChunkToThread(thread, update.turnId, update.chunk); } }), diff --git a/packages/desktop/test/MarkdownRenderer.test.ts b/packages/desktop/test/MarkdownRenderer.test.ts index 6c63f7e0..0b887576 100644 --- a/packages/desktop/test/MarkdownRenderer.test.ts +++ b/packages/desktop/test/MarkdownRenderer.test.ts @@ -35,6 +35,14 @@ describe('MarkdownRenderer', () => { expect(html).toContain('hello world'); }); + it('keeps partial content as plain text', () => { + const html = render( + createElement(MarkdownRenderer, { content: '**still streaming**', partial: true }) + ); + expect(html).toContain('**still streaming**'); + expect(html).not.toContain('md-strong'); + }); + it('renders inline code', () => { const html = render(createElement(MarkdownRenderer, { content: 'use `npm install`' })); expect(html).toContain('md-inline-code'); diff --git a/packages/desktop/test/global-store.test.ts b/packages/desktop/test/global-store.test.ts index 270d2cb0..b071b95a 100644 --- a/packages/desktop/test/global-store.test.ts +++ b/packages/desktop/test/global-store.test.ts @@ -116,6 +116,42 @@ describe('global store - agent streaming actions', () => { expect((committed as any).partial).toBe(false); }); + it('applyChunks applies a stream batch with one store notification', () => { + useAgentStore.getState().startTurn(threadId, makeTurn([])); + let notifications = 0; + const unsubscribe = useAgentStore.subscribe(() => { + notifications += 1; + }); + + useAgentStore.getState().applyChunks(threadId, [ + { + turnId, + chunk: { + id: 'msg-batch', + type: 'message', + role: 'assistant', + parts: [textPart('Hello ')], + partial: true, + }, + }, + { + turnId, + chunk: { + id: 'msg-batch', + type: 'message', + role: 'assistant', + parts: [textPart('world')], + partial: true, + }, + }, + ]); + unsubscribe(); + + const message = useAgentStore.getState().threads[threadId].turns[0].items[0]; + expect(notifications).toBe(1); + expect(message && message.type === 'message' ? textOf(message.parts) : '').toBe('Hello world'); + }); + it('applyChunk upserts tool_call by id', () => { const turn = makeTurn([]); useAgentStore.getState().startTurn(threadId, turn); From 10cddd28c7c1685558fb9c59e31b139514ef48b7 Mon Sep 17 00:00:00 2001 From: phantom5099 <1011668688@qq.com> Date: Mon, 23 Nov 2026 02:15:05 +0800 Subject: [PATCH 2/2] perf: isolate sidebar thread list updates --- packages/desktop/src/agent/AgentSidebar.tsx | 6 +++--- packages/desktop/src/stores/agent.store.ts | 12 +++++++++++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/desktop/src/agent/AgentSidebar.tsx b/packages/desktop/src/agent/AgentSidebar.tsx index ae8752e1..1d59bd89 100644 --- a/packages/desktop/src/agent/AgentSidebar.tsx +++ b/packages/desktop/src/agent/AgentSidebar.tsx @@ -32,14 +32,14 @@ export default function AgentSidebar() { const [projectMenuOpen, setProjectMenuOpen] = useState(false); const [hoveredThreadId, setHoveredThreadId] = useState(null); - const rawThreads = useAgentStore((s) => s.threads); + const threadListVersion = useAgentStore((s) => s.threadListVersion); const threadList = useMemo(() => { const normalizedRoot = normalizeCwd(rootPath); - return Object.values(rawThreads) + return Object.values(useAgentStore.getState().threads) .filter((t) => normalizeCwd(t.cwd).startsWith(normalizedRoot)) .map((t) => ({ id: t.id, title: t.title, cwd: t.cwd, updatedAt: t.updatedAt })) .sort((a, b) => b.updatedAt - a.updatedAt); - }, [rawThreads, rootPath]); + }, [threadListVersion, rootPath]); const currentProject = workspace.projects.find((p) => p.id === workspace.currentProjectId); const projectName = currentProject?.name || workspace.name || '项目'; diff --git a/packages/desktop/src/stores/agent.store.ts b/packages/desktop/src/stores/agent.store.ts index 666a466e..5d2c4e4f 100644 --- a/packages/desktop/src/stores/agent.store.ts +++ b/packages/desktop/src/stores/agent.store.ts @@ -145,6 +145,7 @@ export interface StoredProfile { interface AgentState { currentThreadId: string | null; threads: Record; + threadListVersion: number; profile: ProfileName; permissionMode: PermissionMode; model: string; @@ -232,6 +233,7 @@ export const useAgentStore = create()( immer((set) => ({ currentThreadId: null, threads: {}, + threadListVersion: 0, profile: 'build', permissionMode: 'askBeforeExec', model: '', @@ -316,6 +318,7 @@ export const useAgentStore = create()( removeThread: (id) => set((s) => { delete s.threads[id]; + s.threadListVersion = (s.threadListVersion ?? 0) + 1; delete s.usageByThreadId[id]; delete s.todoByThreadId[id]; delete s.pendingPlanByThreadId[id]; @@ -326,6 +329,7 @@ export const useAgentStore = create()( upsertThread: (thread) => set((s) => { s.threads[thread.id] = thread; + s.threadListVersion = (s.threadListVersion ?? 0) + 1; }), setThreadTurns: (threadId, turns) => @@ -339,7 +343,10 @@ export const useAgentStore = create()( setThreadCwd: (threadId, cwd) => set((s) => { const thread = s.threads[threadId]; - if (thread) thread.cwd = cwd; + if (thread) { + thread.cwd = cwd; + s.threadListVersion = (s.threadListVersion ?? 0) + 1; + } }), setProfile: (profile) => @@ -410,6 +417,7 @@ export const useAgentStore = create()( } } s.threads = next; + s.threadListVersion = (s.threadListVersion ?? 0) + 1; for (const id of Object.keys(s.usageByThreadId)) { if (!incomingIds.has(id)) { delete s.usageByThreadId[id]; @@ -482,6 +490,7 @@ export const useAgentStore = create()( thread.turns.push(turn); thread.updatedAt = Date.now(); } + s.threadListVersion = (s.threadListVersion ?? 0) + 1; }), applyChunk: (threadId, turnId, chunk) => @@ -516,6 +525,7 @@ export const useAgentStore = create()( if (!turn) return; turn.status = status; thread.updatedAt = Date.now(); + s.threadListVersion = (s.threadListVersion ?? 0) + 1; for (const item of turn.items) { if (item.type === 'message' && item.role === 'assistant') { item.partial = false;