Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(conversation): reduce streaming re-renders with reference stabilization and self-subscribing components (#14470)

Innei5e1a35f259c3
diff --git a/package.json b/package.json
index 4afa1acba39..0d044318f9d 100644
--- a/package.json
+++ b/package.json
@@ -281,7 +281,7 @@
"@lobehub/icons": "^5.0.0",
"@lobehub/market-sdk": "0.33.3",
"@lobehub/tts": "^5.1.2",
- "@lobehub/ui": "^5.9.6",
+ "@lobehub/ui": "^5.10.1",
"@modelcontextprotocol/sdk": "^1.26.0",
"@napi-rs/canvas": "^0.1.88",
"@neondatabase/serverless": "^1.0.2",
diff --git a/packages/agent-mock/src/cases/builtins/todo-write-stress.ts b/packages/agent-mock/src/cases/builtins/todo-write-stress.ts
index d8abf6a5517..d5cb1e7d3f1 100644
--- a/packages/agent-mock/src/cases/builtins/todo-write-stress.ts
+++ b/packages/agent-mock/src/cases/builtins/todo-write-stress.ts
@@ -1,25 +1,818 @@
-import { defineCase, llmStep, toolStep } from '../../builders/defineCase';
+import { defineCase, errorStep, llmStep, toolStep } from '../../builders/defineCase';
+
+// ---------------------------------------------------------------------------
+// Helpers — all mapped to lobe-gtd
+// ---------------------------------------------------------------------------
+
+/** lobe-gtd / createTodos */
+const createTodos = (items: string[], durationMs = 60) =>
+ toolStep({
+ identifier: 'lobe-gtd',
+ apiName: 'createTodos',
+ arguments: JSON.stringify({ adds: items }),
+ result: {
+ createdItems: items,
+ todos: {
+ items: items.map((text) => ({ text, status: 'todo' as const })),
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ durationMs,
+ });
+
+/** lobe-gtd / updateTodos — batch operations */
+const updateTodos = (
+ operations: Array<{ type: string; index?: number; newText?: string; status?: string }>,
+ currentItems: Array<{ text: string; status: string }>,
+ durationMs = 60,
+) =>
+ toolStep({
+ identifier: 'lobe-gtd',
+ apiName: 'updateTodos',
+ arguments: JSON.stringify({ operations }),
+ result: {
+ appliedOperations: operations,
+ todos: {
+ items: currentItems,
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ durationMs,
+ });
+
+/** lobe-gtd / createPlan */
+const createPlan = (
+ goal: string,
+ description: string,
+ context: string,
+ planId: string,
+ durationMs = 80,
+) =>
+ toolStep({
+ identifier: 'lobe-gtd',
+ apiName: 'createPlan',
+ arguments: JSON.stringify({ goal, description, context }),
+ result: {
+ plan: {
+ id: planId,
+ goal,
+ description,
+ context,
+ completed: false,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ durationMs,
+ });
+
+/** lobe-gtd / updatePlan */
+const updatePlan = (
+ planId: string,
+ set: { goal?: string; description?: string; context?: string; completed?: boolean },
+ durationMs = 60,
+) =>
+ toolStep({
+ identifier: 'lobe-gtd',
+ apiName: 'updatePlan',
+ arguments: JSON.stringify({ planId, ...set }),
+ result: {
+ plan: {
+ id: planId,
+ goal: set.goal ?? 'Updated plan',
+ description: set.description ?? '',
+ context: set.context ?? '',
+ completed: set.completed ?? false,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ },
+ },
+ durationMs,
+ });
+
+/** lobe-gtd / execTask */
+const execTask = (description: string, instruction: string, durationMs = 200) =>
+ toolStep({
+ identifier: 'lobe-gtd',
+ apiName: 'execTask',
+ arguments: JSON.stringify({ description, instruction }),
+ result: {
+ parentMessageId: `mock-msg-task-${Date.now()}`,
+ task: { description, instruction },
+ type: 'execTask' as const,
+ },
+ durationMs,
+ });
+
+/** LLM "breathing" step between tool-call batches — simulates agent processing results */
+const breathe = (text: string, durationMs = 250) => llmStep({ text, durationMs });
+
+// ---------------------------------------------------------------------------
+// The main case — ~200 lobe-gtd tool calls across 8 phases
+// ---------------------------------------------------------------------------
export const todoWriteStress = defineCase({
id: 'todo-write-stress',
- name: 'TodoWrite × 50',
- description: '50 sequential addTodo tool calls bracketed by short LLM steps',
+ name: 'TodoWrite × 200 (complex)',
+ description:
+ '~200 GTD tool calls across 8 realistic phases: discovery, schema audit, store migration, ' +
+ 'TRPC refactor, i18n extraction, component rewrites, testing, and final verification.',
tags: ['stress', 'todo', 'builtin'],
+
steps: [
+ // =====================================================================
+ // Phase 0 — Agent kickoff
+ // =====================================================================
+ llmStep({
+ text: '我将执行一次完整的 monorepo 重构,预计涉及约 200 个工具调用。按 8 个阶段推进。',
+ reasoning:
+ '这是一个大规模的 monorepo 迁移任务。需要先盘点现有代码,再逐步推进 schema、store、router、i18n、组件、测试的迁移,最后做全面验证。每一步都会产生工具调用。',
+ durationMs: 1200,
+ }),
+
+ // =====================================================================
+ // Phase 1 — Discovery & audit (24 tools)
+ // =====================================================================
+ llmStep({
+ text: '第一阶段:全面盘点现有代码结构。创建总体计划,再拆解为 15 个待办事项。',
+ reasoning: '先创建一个顶层计划文档,再将盘点工作拆解为具体的 todo 项。',
+ toolsCalling: [
+ { id: 'tc-plan-1', identifier: 'lobe-gtd', apiName: 'createPlan', arguments: '{}' },
+ { id: 'tc-todos-1', identifier: 'lobe-gtd', apiName: 'createTodos', arguments: '{}' },
+ ],
+ durationMs: 600,
+ }),
+ createPlan(
+ 'Monorepo 重构',
+ '全面迁移 schema、store、router、i18n、组件、测试',
+ '涉及 10 张数据库表、15 个 store slice、15 个 TRPC router、15 个 i18n 命名空间、8 个核心组件',
+ 'plan-migration-001',
+ ),
+ ...Array.from({ length: 5 }).flatMap((_, batch) => {
+ const allItems = [
+ '盘点 Zustand store slices',
+ '统计 TRPC routers 数量',
+ '扫描 antd 硬编码使用',
+ '检查 @lobehub/ui 一致性',
+ '列出所有 Drizzle schema 表',
+ '统计 Next.js App Router 路由',
+ '盘点 features/ 模块',
+ '扫描硬编码 i18n 字符串',
+ '找出重复工具函数',
+ '测量当前 bundle 大小',
+ '分析首屏加载性能',
+ '审查测试覆盖率',
+ '识别 flaky E2E 测试',
+ '记录 CI/CD 流水线',
+ '列出环境变量',
+ ];
+ return [
+ createTodos(allItems.slice(batch * 3, batch * 3 + 3)),
+ breathe('已创建一批待办,继续盘点。'),
+ ];
+ }),
+ // Mark first 3 as completed after discovery
+ ...Array.from({ length: 5 }).flatMap((_, batch) => [
+ updateTodos(
+ Array.from({ length: 3 }, (_, j) => ({ type: 'complete' as const, index: batch * 3 + j })),
+ Array.from({ length: 15 }, (_, k) => ({
+ text: [
+ '盘点 Zustand store slices',
+ '统计 TRPC routers 数量',
+ '扫描 antd 硬编码使用',
+ '检查 @lobehub/ui 一致性',
+ '列出所有 Drizzle schema 表',
+ '统计 Next.js App Router 路由',
+ '盘点 features/ 模块',
+ '扫描硬编码 i18n 字符串',
+ '找出重复工具函数',
+ '测量当前 bundle 大小',
+ '分析首屏加载性能',
+ '审查测试覆盖率',
+ '识别 flaky E2E 测试',
+ '记录 CI/CD 流水线',
+ '列出环境变量',
+ ][k],
+ status: k < batch * 3 + 3 ? 'completed' : 'todo',
+ })),
+ ),
+ breathe('已标记完成,继续下一批。'),
+ ]),
+
+ // =====================================================================
+ // Phase 2 — Schema & database migration (28 tools)
+ // =====================================================================
+ llmStep({
+ text: '第二阶段:数据库 schema 迁移。为 10 张核心表创建 todo 并逐一推进。',
+ reasoning: '需要逐一检查表结构,添加索引,然后生成迁移脚本。先从核心业务表开始。',
+ durationMs: 900,
+ }),
+ createPlan(
+ 'Schema 迁移计划',
+ '为 10 张核心表添加性能索引并生成 Drizzle 迁移文件',
+ '审计 users, messages, agents, conversations, topics, plugins, files, knowledgeBases, documents, chunks',
+ 'plan-schema-001',
+ ),
+ createTodos([
+ '审计 users 表结构并添加索引',
+ '审计 messages 表结构并添加索引',
+ '审计 agents 表结构并添加索引',
+ '审计 conversations 表结构并添加索引',
+ '审计 topics 表结构并添加索引',
+ ]),
+ createTodos([
+ '审计 plugins 表结构并添加索引',
+ '审计 files 表结构并添加索引',
+ '审计 knowledgeBases 表结构并添加索引',
+ '审计 documents 表结构并添加索引',
+ '审计 chunks 表结构并添加索引',
+ ]),
+ // Process each table: mark processing → complete
+ ...['users', 'messages', 'agents', 'conversations', 'topics'].flatMap((table, i) => [
+ updateTodos(
+ [{ type: 'processing', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ '审计 users 表结构并添加索引',
+ '审计 messages 表结构并添加索引',
+ '审计 agents 表结构并添加索引',
+ '审计 conversations 表结构并添加索引',
+ '审计 topics 表结构并添加索引',
+ ][k],
+ status: k === i ? 'processing' : k < i ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(
+ `为 ${table} 表添加索引`,
+ `检查 src/database/schemas/${table}.ts 的表结构,添加 createdAt 性能索引,生成迁移 SQL`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ '审计 users 表结构并添加索引',
+ '审计 messages 表结构并添加索引',
+ '审计 agents 表结构并添加索引',
+ '审计 conversations 表结构并添加索引',
+ '审计 topics 表结构并添加索引',
+ ][k],
+ status: k <= i ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已处理 ${table} 表,继续下一张。`),
+ ]),
+ ...['plugins', 'files', 'knowledgeBases', 'documents', 'chunks'].flatMap((table, i) => [
+ updateTodos(
+ [{ type: 'processing', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ '审计 plugins 表结构并添加索引',
+ '审计 files 表结构并添加索引',
+ '审计 knowledgeBases 表结构并添加索引',
+ '审计 documents 表结构并添加索引',
+ '审计 chunks 表结构并添加索引',
+ ][k],
+ status: k === i ? 'processing' : k < i ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(
+ `为 ${table} 表添加索引`,
+ `检查 src/database/schemas/${table}.ts 的表结构,添加 createdAt 性能索引,生成迁移 SQL`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ '审计 plugins 表结构并添加索引',
+ '审计 files 表结构并添加索引',
+ '审计 knowledgeBases 表结构并添加索引',
+ '审计 documents 表结构并添加索引',
+ '审计 chunks 表结构并添加索引',
+ ][k],
+ status: k <= i ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已处理 ${table} 表,继续下一张。`),
+ ]),
+ createTodos(['生成 Drizzle 迁移文件 0042_add_indexes', '运行 drizzle-kit dry-run 验证']),
+ updateTodos(
+ [
+ { type: 'complete', index: 0 },
+ { type: 'complete', index: 1 },
+ ],
+ [
+ { text: '生成 Drizzle 迁移文件 0042_add_indexes', status: 'completed' },
+ { text: '运行 drizzle-kit dry-run 验证', status: 'completed' },
+ ],
+ ),
+
+ // =====================================================================
+ // Phase 3 — Store slice migration (30 tools)
+ // =====================================================================
llmStep({
- text: '我将逐步规划 50 项任务,分为五个主题:环境、需求、设计、实现、验收。',
- reasoning: '按主题分组,每组 10 项;先思路后枚举。',
+ text: '第三阶段:迁移 Zustand store slices 到新的 data-fetching 模式。',
+ reasoning:
+ '将 15 个 store slice 逐一迁移到 SWR + zustand 模式。先完成的标记 completed,进行中的标记 in_progress。',
+ durationMs: 1000,
+ }),
+ createPlan(
+ 'Store 迁移计划',
+ '将 15 个 Zustand store slice 迁移到 SWR + Zustand 数据获取模式',
+ '核心 slice: message, chat, agent, tool, session, topic, file, knowledgeBase, plugin, user, setting, discover, compression',
+ 'plan-store-001',
+ ),
+ ...[
+ 'message',
+ 'chat',
+ 'agent',
+ 'tool',
+ 'session',
+ 'topic',
+ 'file',
+ 'knowledgeBase',
+ 'plugin',
+ 'user',
+ 'setting',
+ 'discover',
+ 'compression',
+ 'file',
+ 'notification',
+ ].flatMap((slice, i) => [
+ createTodos([`迁移 ${slice} store slice 到 SWR 模式`]),
+ updateTodos(
+ [{ type: 'processing', index: 0 }],
+ [{ text: `迁移 ${slice} store slice 到 SWR 模式`, status: 'processing' }],
+ ),
+ execTask(
+ `迁移 ${slice} store slice`,
+ `重构 src/store/chat/slices/${slice}/index.ts,将数据获取逻辑迁移到 SWR + Zustand 模式`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: 0 }],
+ [{ text: `迁移 ${slice} store slice 到 SWR 模式`, status: 'completed' }],
+ ),
+ breathe(`已迁移 ${slice},继续下一个 slice。`),
+ ]),
+ updatePlan('plan-store-001', { completed: true }),
+
+ // =====================================================================
+ // Phase 4 — TRPC router refactors (25 tools)
+ // =====================================================================
+ llmStep({
+ text: '第四阶段:重构 15 个 TRPC router 到 v11 patterns。',
+ reasoning: 'TRPC v11 有更好的类型推断。需要更新每个 router 的 procedure 定义。',
durationMs: 800,
}),
- ...Array.from({ length: 50 }, (_, i) =>
- toolStep({
- identifier: 'lobe-todo-write',
- apiName: 'addTodo',
- arguments: JSON.stringify({ title: `任务 ${i + 1}` }),
- result: { success: true, id: `todo-${i}`, title: `任务 ${i + 1}` },
- durationMs: 120,
- }),
+ createPlan(
+ 'TRPC 迁移计划',
+ '将 15 个 TRPC router 迁移到 v11 patterns',
+ 'routers: agent, message, session, topic, file, plugin, knowledgeBase, share, user, setting, notification, discover, generation, tool, thread',
+ 'plan-trpc-001',
),
- llmStep({ text: '已完成 50 项任务规划。', durationMs: 400 }),
+ createTodos([
+ '迁移 agent router 到 TRPC v11',
+ '迁移 message router 到 TRPC v11',
+ '迁移 session router 到 TRPC v11',
+ '迁移 topic router 到 TRPC v11',
+ '迁移 file router 到 TRPC v11',
+ ]),
+ createTodos([
+ '迁移 plugin router 到 TRPC v11',
+ '迁移 knowledgeBase router 到 TRPC v11',
+ '迁移 share router 到 TRPC v11',
+ '迁移 user router 到 TRPC v11',
+ '迁移 setting router 到 TRPC v11',
+ ]),
+ createTodos([
+ '迁移 notification router 到 TRPC v11',
+ '迁移 discover router 到 TRPC v11',
+ '迁移 generation router 到 TRPC v11',
+ '迁移 tool router 到 TRPC v11',
+ '迁移 thread router 到 TRPC v11',
+ ]),
+ ...[
+ 'agent',
+ 'message',
+ 'session',
+ 'topic',
+ 'file',
+ 'plugin',
+ 'knowledgeBase',
+ 'share',
+ 'user',
+ 'setting',
+ 'notification',
+ 'discover',
+ 'generation',
+ 'tool',
+ 'thread',
+ ].flatMap((router, i) => {
+ const batch = Math.floor(i / 5);
+ const localIdx = i % 5;
+ return [
+ updateTodos(
+ [{ type: 'processing', index: localIdx }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ [
+ '迁移 agent router 到 TRPC v11',
+ '迁移 message router 到 TRPC v11',
+ '迁移 session router 到 TRPC v11',
+ '迁移 topic router 到 TRPC v11',
+ '迁移 file router 到 TRPC v11',
+ ],
+ [
+ '迁移 plugin router 到 TRPC v11',
+ '迁移 knowledgeBase router 到 TRPC v11',
+ '迁移 share router 到 TRPC v11',
+ '迁移 user router 到 TRPC v11',
+ '迁移 setting router 到 TRPC v11',
+ ],
+ [
+ '迁移 notification router 到 TRPC v11',
+ '迁移 discover router 到 TRPC v11',
+ '迁移 generation router 到 TRPC v11',
+ '迁移 tool router 到 TRPC v11',
+ '迁移 thread router 到 TRPC v11',
+ ],
+ ][batch][k],
+ status: k === localIdx ? 'processing' : k < localIdx ? 'completed' : 'todo',
+ })),
+ ),
+ updateTodos(
+ [{ type: 'complete', index: localIdx }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: [
+ [
+ '迁移 agent router 到 TRPC v11',
+ '迁移 message router 到 TRPC v11',
+ '迁移 session router 到 TRPC v11',
+ '迁移 topic router 到 TRPC v11',
+ '迁移 file router 到 TRPC v11',
+ ],
+ [
+ '迁移 plugin router 到 TRPC v11',
+ '迁移 knowledgeBase router 到 TRPC v11',
+ '迁移 share router 到 TRPC v11',
+ '迁移 user router 到 TRPC v11',
+ '迁移 setting router 到 TRPC v11',
+ ],
+ [
+ '迁移 notification router 到 TRPC v11',
+ '迁移 discover router 到 TRPC v11',
+ '迁移 generation router 到 TRPC v11',
+ '迁移 tool router 到 TRPC v11',
+ '迁移 thread router 到 TRPC v11',
+ ],
+ ][batch][k],
+ status: k <= localIdx ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已处理 ${router} router,继续。`),
+ ];
+ }),
+ createTodos(['运行 type-check 验证 TRPC 迁移', '修复 type-check 发现的类型问题']),
+ updateTodos(
+ [
+ { type: 'complete', index: 0 },
+ { type: 'processing', index: 1 },
+ ],
+ [
+ { text: '运行 type-check 验证 TRPC 迁移', status: 'completed' },
+ { text: '修复 type-check 发现的类型问题', status: 'processing' },
+ ],
+ ),
+ execTask('修复 TRPC 类型问题', '运行 bun run type-check,逐一修复类型错误直到通过'),
+ updateTodos(
+ [{ type: 'complete', index: 1 }],
+ [
+ { text: '运行 type-check 验证 TRPC 迁移', status: 'completed' },
+ { text: '修复 type-check 发现的类型问题', status: 'completed' },
+ ],
+ ),
+
+ // =====================================================================
+ // Phase 5 — i18n key extraction + error recovery (28 tools)
+ // =====================================================================
+ llmStep({
+ text: '第五阶段:i18n key 提取。扫描 15 个命名空间,提取硬编码字符串。',
+ reasoning: '逐文件扫描,替换硬编码中文/英文字符串为 i18n key。',
+ durationMs: 700,
+ }),
+ createPlan(
+ 'i18n 提取计划',
+ '扫描 15 个命名空间,提取硬编码字符串为 i18n key',
+ '命名空间: common, chat, agent, setting, plugin, tool, auth, file, knowledge, share, discover, notification, onboarding, error, taskTemplate',
+ 'plan-i18n-001',
+ ),
+ ...[
+ 'common',
+ 'chat',
+ 'agent',
+ 'setting',
+ 'plugin',
+ 'tool',
+ 'auth',
+ 'file',
+ 'knowledge',
+ 'share',
+ ].flatMap((ns, i) => {
+ return [
+ createTodos([`提取 ${ns} 命名空间的硬编码字符串`]),
+ updateTodos(
+ [{ type: 'processing', index: 0 }],
+ [{ text: `提取 ${ns} 命名空间的硬编码字符串`, status: 'processing' }],
+ ),
+ execTask(
+ `提取 ${ns} i18n keys`,
+ `扫描 src/locales/default/${ns}.ts,将硬编码字符串替换为 i18n key`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: 0 }],
+ [{ text: `提取 ${ns} 命名空间的硬编码字符串`, status: 'completed' }],
+ ),
+ breathe(`已提取 ${ns},继续下一个命名空间。`),
+ ];
+ }),
+ ...['discover', 'notification', 'onboarding', 'error', 'taskTemplate'].flatMap((ns) => [
+ createTodos([`提取 ${ns} 命名空间的硬编码字符串`]),
+ updateTodos(
+ [{ type: 'processing', index: 0 }],
+ [{ text: `提取 ${ns} 命名空间的硬编码字符串`, status: 'processing' }],
+ ),
+ execTask(
+ `提取 ${ns} i18n keys`,
+ `扫描 src/locales/default/${ns}.ts,将硬编码字符串替换为 i18n key`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: 0 }],
+ [{ text: `提取 ${ns} 命名空间的硬编码字符串`, status: 'completed' }],
+ ),
+ breathe(`已提取 ${ns},继续下一个命名空间。`),
+ ]),
+ // Simulate an error + recovery
+ errorStep({
+ message: 'i18n sync failed: zh-CN/agent.ts has duplicate key "confirmDelete"',
+ type: 'I18nSyncError',
+ }),
+ createTodos(['修复 i18n sync 重复 key 问题']),
+ updateTodos(
+ [{ type: 'processing', index: 0 }],
+ [{ text: '修复 i18n sync 重复 key 问题', status: 'processing' }],
+ ),
+ execTask(
+ '修复 i18n 重复 key',
+ '检查 src/locales/zh-CN/agent.ts,合并重复的 confirmDelete key,重新运行 pnpm i18n',
+ ),
+ updateTodos(
+ [{ type: 'complete', index: 0 }],
+ [{ text: '修复 i18n sync 重复 key 问题', status: 'completed' }],
+ ),
+
+ // =====================================================================
+ // Phase 6 — Component rewrites with createStaticStyles (26 tools)
+ // =====================================================================
+ llmStep({
+ text: '第六阶段:将 8 个核心组件从 createStyles 迁移到 createStaticStyles。',
+ reasoning: 'createStaticStyles 使用 cssVar,零运行时开销。先迁移高频使用的核心组件。',
+ durationMs: 900,
+ }),
+ createPlan(
+ '组件样式迁移计划',
+ '将 8 个核心组件从 createStyles 迁移到 createStaticStyles',
+ '组件: ChatInput, Conversation, AgentSettings, KnowledgeBase, PluginStore, FileExplorer, ShareModal, UserSettings',
+ 'plan-styles-001',
+ ),
+ createTodos([
+ '迁移 ChatInput 到 createStaticStyles',
+ '迁移 Conversation 到 createStaticStyles',
+ '迁移 AgentSettings 到 createStaticStyles',
+ '迁移 KnowledgeBase 到 createStaticStyles',
+ ]),
+ createTodos([
+ '迁移 PluginStore 到 createStaticStyles',
+ '迁移 FileExplorer 到 createStaticStyles',
+ '迁移 ShareModal 到 createStaticStyles',
+ '迁移 UserSettings 到 createStaticStyles',
+ ]),
+ ...[
+ 'ChatInput',
+ 'Conversation',
+ 'AgentSettings',
+ 'KnowledgeBase',
+ 'PluginStore',
+ 'FileExplorer',
+ 'ShareModal',
+ 'UserSettings',
+ ].flatMap((comp, i) => {
+ const localIdx = i % 4;
+ return [
+ updateTodos(
+ [{ type: 'processing', index: localIdx }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ [
+ '迁移 ChatInput 到 createStaticStyles',
+ '迁移 Conversation 到 createStaticStyles',
+ '迁移 AgentSettings 到 createStaticStyles',
+ '迁移 KnowledgeBase 到 createStaticStyles',
+ ],
+ [
+ '迁移 PluginStore 到 createStaticStyles',
+ '迁移 FileExplorer 到 createStaticStyles',
+ '迁移 ShareModal 到 createStaticStyles',
+ '迁移 UserSettings 到 createStaticStyles',
+ ],
+ ][Math.floor(i / 4)][k],
+ status: k === localIdx ? 'processing' : k < localIdx ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(
+ `迁移 ${comp} 样式`,
+ `将 src/features/${comp}/index.tsx 中的 createStyles 替换为 createStaticStyles,使用 cssVar`,
+ ),
+ updateTodos(
+ [{ type: 'complete', index: localIdx }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ [
+ '迁移 ChatInput 到 createStaticStyles',
+ '迁移 Conversation 到 createStaticStyles',
+ '迁移 AgentSettings 到 createStaticStyles',
+ '迁移 KnowledgeBase 到 createStaticStyles',
+ ],
+ [
+ '迁移 PluginStore 到 createStaticStyles',
+ '迁移 FileExplorer 到 createStaticStyles',
+ '迁移 ShareModal 到 createStaticStyles',
+ '迁移 UserSettings 到 createStaticStyles',
+ ],
+ ][Math.floor(i / 4)][k],
+ status: k <= localIdx ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已迁移 ${comp},继续下一个组件。`),
+ ];
+ }),
+ // Verify
+ createTodos(['验证迁移后的组件编译通过']),
+ updateTodos(
+ [{ type: 'processing', index: 0 }],
+ [{ text: '验证迁移后的组件编译通过', status: 'processing' }],
+ ),
+ execTask('编译验证', '运行 bun run type-check 确认迁移后的组件没有类型错误'),
+ updateTodos(
+ [{ type: 'complete', index: 0 }],
+ [{ text: '验证迁移后的组件编译通过', status: 'completed' }],
+ ),
+
+ // =====================================================================
+ // Phase 7 — Testing (20 tools)
+ // =====================================================================
+ llmStep({
+ text: '第七阶段:编写和修复测试。覆盖 store、router、E2E 三个层面。',
+ reasoning: '先写单元测试确保 store 迁移正确,再写集成测试覆盖 router,最后修复 flaky E2E。',
+ durationMs: 800,
+ }),
+ createTodos([
+ '写 message store 单元测试',
+ '写 chat store 单元测试',
+ '写 agent store 单元测试',
+ '写 agent router 集成测试',
+ ]),
+ ...['message store', 'chat store', 'agent store', 'agent router'].flatMap((target, i) => [
+ updateTodos(
+ [{ type: 'processing', index: i }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ '写 message store 单元测试',
+ '写 chat store 单元测试',
+ '写 agent store 单元测试',
+ '写 agent router 集成测试',
+ ][k],
+ status: k === i ? 'processing' : k < i ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(`编写 ${target} 测试`, `为 ${target} 编写 vitest 测试用例,覆盖核心功能路径`),
+ updateTodos(
+ [{ type: 'complete', index: i }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ '写 message store 单元测试',
+ '写 chat store 单元测试',
+ '写 agent store 单元测试',
+ '写 agent router 集成测试',
+ ][k],
+ status: k <= i ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已完成 ${target},继续下一项测试。`),
+ ]),
+ // Fix flaky E2E
+ createTodos([
+ '修复 login E2E flaky 测试',
+ '修复 conversation E2E flaky 测试',
+ '运行全量 Vitest 套件',
+ '运行 E2E 套件',
+ ]),
+ ...['login E2E', 'conversation E2E', '全量 Vitest', 'E2E 套件'].flatMap((target, i) => [
+ updateTodos(
+ [{ type: 'processing', index: i }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ '修复 login E2E flaky 测试',
+ '修复 conversation E2E flaky 测试',
+ '运行全量 Vitest 套件',
+ '运行 E2E 套件',
+ ][k],
+ status: k === i ? 'processing' : k < i ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(`${target}`, `执行 ${target} 相关的测试修复与验证工作`),
+ updateTodos(
+ [{ type: 'complete', index: i }],
+ Array.from({ length: 4 }, (_, k) => ({
+ text: [
+ '修复 login E2E flaky 测试',
+ '修复 conversation E2E flaky 测试',
+ '运行全量 Vitest 套件',
+ '运行 E2E 套件',
+ ][k],
+ status: k <= i ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已完成 ${target},继续下一项。`),
+ ]),
+
+ // =====================================================================
+ // Phase 8 — Final verification (19 tools)
+ // =====================================================================
+ llmStep({
+ text: '第八阶段:最终验证——type-check、完整测试套件、bundle 分析、安全审计。',
+ reasoning: '全面跑一遍 CI 流水线的关键步骤,确保迁移没有引入回归。',
+ durationMs: 1000,
+ }),
+ createPlan(
+ '最终验证计划',
+ '全面验证迁移结果,确保无回归',
+ '验证项: type-check, vitest, production build, e2e, security audit, CI workflow, migration guide',
+ 'plan-verify-001',
+ ),
+ createTodos(['全量 type-check', '完整 Vitest 套件', '生产构建', 'E2E 套件', '安全审计']),
+ ...['全量 type-check', '完整 Vitest 套件', '生产构建', 'E2E 套件', '安全审计'].flatMap(
+ (task, i) => [
+ updateTodos(
+ [{ type: 'processing', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: ['全量 type-check', '完整 Vitest 套件', '生产构建', 'E2E 套件', '安全审计'][k],
+ status: k === i ? 'processing' : k < i ? 'completed' : 'todo',
+ })),
+ ),
+ execTask(`执行 ${task}`, `运行 ${task} 确认迁移无回归`),
+ updateTodos(
+ [{ type: 'complete', index: i }],
+ Array.from({ length: 5 }, (_, k) => ({
+ text: ['全量 type-check', '完整 Vitest 套件', '生产构建', 'E2E 套件', '安全审计'][k],
+ status: k <= i ? 'completed' : 'todo',
+ })),
+ ),
+ breathe(`已完成 ${task},继续验证。`),
+ ],
+ ),
+ // Final cleanup
+ createTodos(['更新 CI workflow', '写迁移指南文档']),
+ updateTodos(
+ [
+ { type: 'processing', index: 0 },
+ { type: 'processing', index: 1 },
+ ],
+ [
+ { text: '更新 CI workflow', status: 'processing' },
+ { text: '写迁移指南文档', status: 'processing' },
+ ],
+ ),
+ execTask('更新 CI 配置', '修改 .github/workflows/ci.yml 添加并行 vitest shards'),
+ execTask('写迁移指南', '创建 docs/MIGRATION.md 记录所有迁移变更和操作步骤'),
+ updateTodos(
+ [
+ { type: 'complete', index: 0 },
+ { type: 'complete', index: 1 },
+ ],
+ [
+ { text: '更新 CI workflow', status: 'completed' },
+ { text: '写迁移指南文档', status: 'completed' },
+ ],
+ ),
+ updatePlan('plan-verify-001', { completed: true }),
+ updatePlan('plan-migration-001', { completed: true }),
+
+ // =====================================================================
+ // Done
+ // =====================================================================
+ llmStep({
+ text: '全部 8 个阶段完成。共执行约 200 个 GTD 工具调用,涵盖计划创建、待办管理、任务执行和错误恢复。迁移已通过 type-check、单测、E2E 和安全审计。',
+ reasoning: '确认所有 todo 已标记完成,所有 plan 已标记 completed,汇总执行统计。',
+ durationMs: 600,
+ }),
],
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
index 0e712fd6755..8910a328afb 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx
@@ -1,9 +1,9 @@
import { getBuiltinRender } from '@lobechat/builtin-tools/renders';
import { getBuiltinStreaming } from '@lobechat/builtin-tools/streamings';
import { LOADING_FLAT } from '@lobechat/const';
-import { type ChatToolResult, type ToolIntervention } from '@lobechat/types';
import { AccordionItem, Flexbox, Skeleton } from '@lobehub/ui';
import { Divider } from 'antd';
+import isEqual from 'fast-deep-equal';
import { memo, useEffect, useState } from 'react';
import SafeBoundary from '@/components/ErrorBoundary';
@@ -13,6 +13,7 @@ import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { useToolStore } from '@/store/tool';
import { toolSelectors } from '@/store/tool/selectors';
+import { dataSelectors, useConversationStore } from '../../../store';
import Actions from './Actions';
import Inspectors from './Inspector';
@@ -27,172 +28,167 @@ const Detail = dynamic(() => import('./Detail'), {
});
export interface GroupToolProps {
- apiName: string;
- arguments?: string;
assistantMessageId: string;
disableEditing?: boolean;
id: string;
- identifier: string;
- intervention?: ToolIntervention;
- result?: ChatToolResult;
- toolMessageId?: string;
- type?: string;
}
-const Tool = memo<GroupToolProps>(
- ({
- arguments: requestArgs,
- apiName,
- assistantMessageId,
- disableEditing,
- id,
- intervention,
- identifier,
- result,
- type,
- toolMessageId,
- }) => {
- // Get renderDisplayControl from manifest
- const renderDisplayControl = useToolStore(
- toolSelectors.getRenderDisplayControl(identifier, apiName),
- );
- const [showDebug, setShowDebug] = useState(false);
- const [showToolRender, setShowToolRender] = useState(false);
- // Controls switching between custom render and fallback ArgumentRender
- const [showCustomToolRender, setShowCustomToolRender] = useState(true);
-
- const isPending = intervention?.status === 'pending';
- const isReject = intervention?.status === 'rejected';
- const isAbort = intervention?.status === 'aborted';
- const needExpand = renderDisplayControl !== 'collapsed' || isPending;
- const isAlwaysExpand = renderDisplayControl === 'alwaysExpand';
-
- let isArgumentsStreaming = false;
- try {
- JSON.parse(requestArgs || '{}');
- } catch {
- isArgumentsStreaming = true;
+const Tool = memo<GroupToolProps>(({ assistantMessageId, disableEditing, id }) => {
+ // Subscribe directly to this tool's data so a streaming chunk that only
+ // updates a sibling tool does not push new props through this subtree.
+ const tool = useConversationStore(dataSelectors.getToolInBlock(assistantMessageId, id), isEqual);
+
+ // Stable defaults so downstream hook ordering is preserved even on the brief
+ // window where the tool is not yet present in the store snapshot.
+ const apiName = tool?.apiName ?? '';
+ const identifier = tool?.identifier ?? '';
+ const requestArgs = tool?.arguments;
+ const intervention = tool?.intervention;
+ const result = tool?.result;
+ const type = tool?.type;
+ const toolMessageId = tool?.result_msg_id;
+
+ // Get renderDisplayControl from manifest
+ const renderDisplayControl = useToolStore(
+ toolSelectors.getRenderDisplayControl(identifier, apiName),
+ );
+ const [showDebug, setShowDebug] = useState(false);
+ const [showToolRender, setShowToolRender] = useState(false);
+ // Controls switching between custom render and fallback ArgumentRender
+ const [showCustomToolRender, setShowCustomToolRender] = useState(true);
+
+ const isPending = intervention?.status === 'pending';
+ const isReject = intervention?.status === 'rejected';
+ const isAbort = intervention?.status === 'aborted';
+ const needExpand = renderDisplayControl !== 'collapsed' || isPending;
+ const isAlwaysExpand = renderDisplayControl === 'alwaysExpand';
+
+ let isArgumentsStreaming = false;
+ try {
+ JSON.parse(requestArgs || '{}');
+ } catch {
+ isArgumentsStreaming = true;
+ }
+
+ const hasStreamingRenderer = !!getBuiltinStreaming(identifier, apiName);
+ const forceShowStreamingRender = isArgumentsStreaming && hasStreamingRenderer;
+
+ // Get precise tool calling state from operation
+ const isToolCallingFromOperation = useChatStore(
+ operationSelectors.isMessageInToolCalling(assistantMessageId),
+ );
+
+ // Only treat "missing/placeholder result" as in-flight while this assistant
+ // message still has a running operation. After the run ends, tools may
+ // legitimately have no merged `result` — do not keep showing "executing".
+ const isAssistantMessageBusy = useChatStore(
+ operationSelectors.isMessageProcessing(assistantMessageId),
+ );
+
+ const hasError = !!result?.error;
+ // This tool's own result is the source of truth for completion. The
+ // message-level toolCalling flag stays true while sibling tools are still
+ // running, so without this guard a finished tool flips back into "loading".
+ const hasFinishedResult =
+ hasError || (!!result && result.content !== LOADING_FLAT && !!result.content);
+ const looksLikeWaitingForToolResult = !hasError && !isArgumentsStreaming && !hasFinishedResult;
+ const isToolCallingFallback = looksLikeWaitingForToolResult && isAssistantMessageBusy;
+ const isToolCalling = !hasFinishedResult && (isToolCallingFromOperation || isToolCallingFallback);
+
+ const hasCustomRender = !!getBuiltinRender(identifier, apiName);
+ // Only allow toggle when has custom render and not in pending/reject/abort state
+ const canToggleCustomToolRender = hasCustomRender && !isPending && !isReject && !isAbort;
+
+ // Handle expand state changes
+ const handleExpand = (expand?: boolean) => {
+ // Block collapse action when alwaysExpand is set
+ if (isAlwaysExpand && expand === false) {
+ return;
}
+ // When collapsing, also turn off debug mode so the accordion can actually collapse
+ if (expand === false) {
+ setShowDebug(false);
+ }
+ setShowToolRender(!!expand);
+ };
- const hasStreamingRenderer = !!getBuiltinStreaming(identifier, apiName);
- const forceShowStreamingRender = isArgumentsStreaming && hasStreamingRenderer;
-
- // Get precise tool calling state from operation
- const isToolCallingFromOperation = useChatStore(
- operationSelectors.isMessageInToolCalling(assistantMessageId),
- );
-
- // Only treat "missing/placeholder result" as in-flight while this assistant
- // message still has a running operation. After the run ends, tools may
- // legitimately have no merged `result` — do not keep showing "executing".
- const isAssistantMessageBusy = useChatStore(
- operationSelectors.isMessageProcessing(assistantMessageId),
- );
-
- const hasError = !!result?.error;
- // This tool's own result is the source of truth for completion. The
- // message-level toolCalling flag stays true while sibling tools are still
- // running, so without this guard a finished tool flips back into "loading".
- const hasFinishedResult =
- hasError || (!!result && result.content !== LOADING_FLAT && !!result.content);
- const looksLikeWaitingForToolResult = !hasError && !isArgumentsStreaming && !hasFinishedResult;
- const isToolCallingFallback = looksLikeWaitingForToolResult && isAssistantMessageBusy;
- const isToolCalling =
- !hasFinishedResult && (isToolCallingFromOperation || isToolCallingFallback);
-
- const hasCustomRender = !!getBuiltinRender(identifier, apiName);
- // Only allow toggle when has custom render and not in pending/reject/abort state
- const canToggleCustomToolRender = hasCustomRender && !isPending && !isReject && !isAbort;
-
- // Handle expand state changes
- const handleExpand = (expand?: boolean) => {
- // Block collapse action when alwaysExpand is set
- if (isAlwaysExpand && expand === false) {
- return;
- }
- // When collapsing, also turn off debug mode so the accordion can actually collapse
- if (expand === false) {
- setShowDebug(false);
+ useEffect(() => {
+ if (needExpand) {
+ setTimeout(() => handleExpand(true), 100);
+ }
+ }, [needExpand]);
+
+ if (!tool) return null;
+
+ const isToolDetailExpand = forceShowStreamingRender || showToolRender || showDebug;
+
+ return (
+ <AccordionItem
+ expand={isToolDetailExpand}
+ hideIndicator={isAlwaysExpand}
+ itemKey={id}
+ paddingBlock={4}
+ paddingInline={4}
+ action={
+ !disableEditing && (
+ <Actions
+ assistantMessageId={assistantMessageId}
+ canToggleCustomToolRender={canToggleCustomToolRender}
+ identifier={identifier}
+ setShowCustomToolRender={setShowCustomToolRender}
+ setShowDebug={setShowDebug}
+ showCustomToolRender={showCustomToolRender}
+ showDebug={showDebug}
+ />
+ )
}
- setShowToolRender(!!expand);
- };
-
- useEffect(() => {
- if (needExpand) {
- setTimeout(() => handleExpand(true), 100);
+ title={
+ <Inspectors
+ apiName={apiName}
+ arguments={requestArgs}
+ identifier={identifier}
+ intervention={intervention}
+ isArgumentsStreaming={isArgumentsStreaming}
+ isToolCalling={isToolCalling}
+ result={result}
+ />
}
- }, [needExpand]);
-
- const isToolDetailExpand = forceShowStreamingRender || showToolRender || showDebug;
-
- return (
- <AccordionItem
- expand={isToolDetailExpand}
- hideIndicator={isAlwaysExpand}
- itemKey={id}
- paddingBlock={4}
- paddingInline={4}
- action={
- !disableEditing && (
- <Actions
- assistantMessageId={assistantMessageId}
- canToggleCustomToolRender={canToggleCustomToolRender}
- identifier={identifier}
- setShowCustomToolRender={setShowCustomToolRender}
- setShowDebug={setShowDebug}
- showCustomToolRender={showCustomToolRender}
- showDebug={showDebug}
- />
- )
- }
- title={
- <Inspectors
+ onExpandChange={handleExpand}
+ >
+ <Flexbox gap={8} paddingBlock={8}>
+ {showDebug && (
+ <Debug
+ apiName={apiName}
+ identifier={identifier}
+ intervention={intervention}
+ requestArgs={requestArgs}
+ result={result}
+ toolCallId={id}
+ type={type}
+ />
+ )}
+ <SafeBoundary alertTitle={`${identifier} / ${apiName}`} variant="alert">
+ <Detail
apiName={apiName}
arguments={requestArgs}
+ disableEditing={disableEditing}
identifier={identifier}
intervention={intervention}
isArgumentsStreaming={isArgumentsStreaming}
isToolCalling={isToolCalling}
+ messageId={assistantMessageId}
result={result}
+ showCustomToolRender={showCustomToolRender}
+ toolCallId={id}
+ toolMessageId={toolMessageId}
+ type={type}
/>
- }
- onExpandChange={handleExpand}
- >
- <Flexbox gap={8} paddingBlock={8}>
- {showDebug && (
- <Debug
- apiName={apiName}
- identifier={identifier}
- intervention={intervention}
- requestArgs={requestArgs}
- result={result}
- toolCallId={id}
- type={type}
- />
- )}
- <SafeBoundary alertTitle={`${identifier} / ${apiName}`} variant="alert">
- <Detail
- apiName={apiName}
- arguments={requestArgs}
- disableEditing={disableEditing}
- identifier={identifier}
- intervention={intervention}
- isArgumentsStreaming={isArgumentsStreaming}
- isToolCalling={isToolCalling}
- messageId={assistantMessageId}
- result={result}
- showCustomToolRender={showCustomToolRender}
- toolCallId={id}
- toolMessageId={toolMessageId}
- type={type}
- />
- </SafeBoundary>
- <Divider dashed style={{ marginBottom: 0, marginTop: 8 }} />
- </Flexbox>
- </AccordionItem>
- );
- },
-);
+ </SafeBoundary>
+ <Divider dashed style={{ marginBottom: 0, marginTop: 8 }} />
+ </Flexbox>
+ </AccordionItem>
+ );
+});
Tool.displayName = 'GroupTool';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
index 77479dfb086..abbb1228fd8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx
@@ -1,38 +1,36 @@
-import { type ChatToolPayloadWithResult } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
import { memo } from 'react';
+import { dataSelectors, useConversationStore } from '../../store';
import Tool from './Tool';
import { shouldRenderToolCall } from './toolRenderRules';
interface ToolsRendererProps {
disableEditing?: boolean;
messageId: string;
- tools: ChatToolPayloadWithResult[];
}
-export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId, tools }) => {
- if (!tools || tools.length === 0) return null;
+export const Tools = memo<ToolsRendererProps>(({ disableEditing, messageId }) => {
+ // Subscribe only to the visible tool ids of this block. Streaming chunks that
+ // change a single tool's args/result do not invalidate this string array, so
+ // sibling Tool components stay isolated and only the changed one re-renders.
+ const visibleToolCallIds = useConversationStore((s) => {
+ const tools = dataSelectors.getToolsInBlock(messageId)(s);
+ if (!tools || tools.length === 0) return [];
+ return tools.filter(shouldRenderToolCall).map((t) => t.id);
+ }, isEqual);
- const visibleTools = tools.filter(shouldRenderToolCall);
-
- if (visibleTools.length === 0) return null;
+ if (visibleToolCallIds.length === 0) return null;
return (
<Flexbox gap={8}>
- {visibleTools.map((tool) => (
+ {visibleToolCallIds.map((toolCallId) => (
<Tool
- apiName={tool.apiName}
- arguments={tool.arguments}
assistantMessageId={messageId}
disableEditing={disableEditing}
- id={tool.id}
- identifier={tool.identifier}
- intervention={tool.intervention}
- key={tool.id}
- result={tool.result}
- toolMessageId={tool.result_msg_id}
- type={tool.type}
+ id={toolCallId}
+ key={toolCallId}
/>
))}
</Flexbox>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
index 351efabcc20..6fbd0476af9 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.tsx
@@ -84,12 +84,7 @@ const ContentBlock = memo<ContentBlockProps>(
{showMessageContent && (
<SafeBoundary variant="alert">
- <MessageContent
- content={content}
- disableStreaming={disableMarkdownStreaming}
- hasTools={hasTools}
- id={id}
- />
+ <MessageContent disableStreaming={disableMarkdownStreaming} id={id} />
</SafeBoundary>
)}
@@ -101,7 +96,7 @@ const ContentBlock = memo<ContentBlockProps>(
{hasTools && (
<SafeBoundary>
- <Tools disableEditing={disableEditing} messageId={id} tools={tools} />
+ <Tools disableEditing={disableEditing} messageId={id} />
</SafeBoundary>
)}
</Flexbox>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx
index f0ee3742898..0d76e4c191d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.tsx
@@ -63,7 +63,7 @@ const ContentBlocksScroll = memo<ContentBlocksScrollProps>((props) => {
}, [assistantIdFromProps, blocksFromProps, messagesList]);
const list = (
- <Flexbox gap={8}>
+ <Flexbox>
{blocks.map((block) => (
<ContentBlock
key={block.renderKey ?? block.id}
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
index 12a038dc747..841c7d9be50 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
@@ -5,6 +5,7 @@ import { LOADING_FLAT } from '@/const/message';
import MarkdownMessage from '@/features/Conversation/Markdown';
import ContentLoading from '@/features/Conversation/Messages/components/ContentLoading';
+import { dataSelectors, useConversationStore } from '../../../store';
import { normalizeThinkTags, processWithArtifact } from '../../../utils/markdown';
import { useMarkdown } from '../useMarkdown';
@@ -15,15 +16,18 @@ const styles = createStaticStyles(({ css, cssVar }) => {
`,
};
});
-interface ContentBlockProps {
- content: string;
+interface MessageContentProps {
disableStreaming?: boolean;
- hasTools?: boolean;
id: string;
}
-const MessageContent = memo<ContentBlockProps>(({ content, disableStreaming, hasTools, id }) => {
- const message = normalizeThinkTags(processWithArtifact(content));
+const MessageContent = memo<MessageContentProps>(({ disableStreaming, id }) => {
+ // Subscribe to this block's content + hasTools directly so streaming chunks
+ // do not need to flow through ContentBlock's prop chain to reach us.
+ const content = useConversationStore(dataSelectors.getBlockContent(id));
+ const hasTools = useConversationStore(dataSelectors.getBlockHasTools(id));
+
+ const message = normalizeThinkTags(processWithArtifact(content ?? ''));
const markdownProps = useMarkdown(id, disableStreaming);
if (!content && !hasTools) return <ContentLoading id={id} />;
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
index 32823a23bbb..c4f61d3570f 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.tsx
@@ -3,7 +3,7 @@ import { Accordion, AccordionItem, ActionIcon, Block, Flexbox, Icon, Text } from
import { cssVar } from 'antd-style';
import { AlertTriangle, Check, HandIcon, Maximize2, Minimize2, X } from 'lucide-react';
import { AnimatePresence, m as motion } from 'motion/react';
-import { type Key, memo, useEffect, useMemo, useRef, useState } from 'react';
+import { type Key, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
@@ -298,17 +298,25 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
!pendingInterventionPresent &&
workingElapsedSeconds >= WORKFLOW_WORKING_ELAPSED_SHOW_AFTER_MS / TIME_MS_PER_SECOND;
- const handleExpandedChange = (keys: Key[]) => {
- const nowExpanded = keys.includes('workflow');
- if (forceExpanded && !nowExpanded) return;
-
- if (nowExpanded) {
- setExpandLevel('semi');
- userOpenedRef.current = true;
- } else {
- setExpandLevel('collapsed');
- }
- };
+ // Stable refs so the underlying Accordion's memoized contextValue can
+ // remain reference-stable across WorkflowCollapse re-renders — otherwise
+ // every nested AccordionItem (each GroupTool) re-renders due to "context
+ // changed" on every streaming chunk.
+ const handleExpandedChange = useCallback(
+ (keys: Key[]) => {
+ const nowExpanded = keys.includes('workflow');
+ if (forceExpanded && !nowExpanded) return;
+
+ if (nowExpanded) {
+ setExpandLevel('semi');
+ userOpenedRef.current = true;
+ } else {
+ setExpandLevel('collapsed');
+ }
+ },
+ [forceExpanded],
+ );
+ const expandedKeys = useMemo(() => (isExpanded ? ['workflow'] : []), [isExpanded]);
const constrained = expandLevel === 'semi';
const { ref: scrollRef, handleScroll: handleAutoScroll } = useAutoScroll<HTMLDivElement>({
@@ -460,7 +468,7 @@ const WorkflowCollapse = memo<WorkflowCollapseProps>(
return (
<Accordion
- expandedKeys={isExpanded ? ['workflow'] : []}
+ expandedKeys={expandedKeys}
variant="borderless"
onExpandedChange={handleExpandedChange}
>
diff --git a/src/features/Conversation/Messages/Supervisor/components/ContentBlock.tsx b/src/features/Conversation/Messages/Supervisor/components/ContentBlock.tsx
index a90d3d81d3b..72e9082bc2e 100644
--- a/src/features/Conversation/Messages/Supervisor/components/ContentBlock.tsx
+++ b/src/features/Conversation/Messages/Supervisor/components/ContentBlock.tsx
@@ -31,10 +31,10 @@ const ContentBlock = memo<ContentBlockProps>(
{showReasoning && <Reasoning {...reasoning} id={id} />}
{/* Content - markdown text */}
- <MessageContent content={content} hasTools={hasTools} id={id} />
+ <MessageContent id={id} />
{/* Tools */}
- {hasTools && <Tools disableEditing={disableEditing} messageId={id} tools={tools} />}
+ {hasTools && <Tools disableEditing={disableEditing} messageId={id} />}
</Flexbox>
);
},
diff --git a/src/features/Conversation/store/slices/data/action.test.ts b/src/features/Conversation/store/slices/data/action.test.ts
index 04bb009bd7e..13b677537c1 100644
--- a/src/features/Conversation/store/slices/data/action.test.ts
+++ b/src/features/Conversation/store/slices/data/action.test.ts
@@ -1,4 +1,4 @@
-import { type UIChatMessage } from '@lobechat/types';
+import type { UIChatMessage } from '@lobechat/types';
import { act, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
@@ -348,6 +348,53 @@ describe('DataSlice', () => {
expect(notFound).toBeUndefined();
});
+ it('getBlockContent should find assistant blocks in compressed messages', () => {
+ const store = createTestStore();
+
+ store.getState().replaceMessages([
+ {
+ id: 'compressed-group',
+ content: '',
+ role: 'compressedGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ compressedMessages: [
+ {
+ id: 'compressed-assistant',
+ content: 'Compressed assistant content',
+ role: 'assistant',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ },
+ {
+ id: 'compressed-assistant-group',
+ content: '',
+ role: 'assistantGroup',
+ createdAt: Date.now(),
+ updatedAt: Date.now(),
+ children: [
+ {
+ id: 'compressed-block',
+ content: 'Compressed block content',
+ tools: [{ id: 'compressed-tool' }],
+ },
+ ],
+ },
+ ],
+ },
+ ] as any);
+
+ expect(dataSelectors.getBlockContent('compressed-assistant')(store.getState())).toBe(
+ 'Compressed assistant content',
+ );
+ expect(dataSelectors.getBlockContent('compressed-block')(store.getState())).toBe(
+ 'Compressed block content',
+ );
+ expect(dataSelectors.getToolsInBlock('compressed-block')(store.getState())).toEqual([
+ { id: 'compressed-tool' },
+ ]);
+ });
+
it('getDbMessageById should find message from dbMessages', () => {
const store = createTestStore();
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 5df1794977e..7c88fcedcba 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -12,6 +12,7 @@ import { type Store as ConversationStore } from '../../action';
import { type MessageDispatch } from './reducer';
import { messagesReducer } from './reducer';
import { dataSelectors } from './selectors';
+import { stabilizeReferences } from './stabilizeReferences';
const log = debug('lobe-render:features:Conversation');
@@ -106,7 +107,7 @@ export const dataSlice: StateCreator<
metadata: { ...newDisplayMessages[index].metadata, ...payload.value },
};
- set({ displayMessages: newDisplayMessages }, false, {
+ set({ displayMessages: stabilizeReferences(displayMessages, newDisplayMessages) }, false, {
payload,
type: `dispatchMessage/${payload.type}`,
});
@@ -126,16 +127,19 @@ export const dataSlice: StateCreator<
// Re-parse for display order and grouping
const { flatList } = parse(newDbMessages);
+ // parse() rebuilds every message/block/tool reference, so pin unchanged
+ // subtrees back to their previous identity to preserve memo bailouts.
+ const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
log(
'[dispatchMessage] updated | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d',
contextKey,
dbMessages.length,
newDbMessages.length,
- flatList.length,
+ stableFlatList.length,
);
- set({ dbMessages: newDbMessages, displayMessages: flatList }, false, {
+ set({ dbMessages: newDbMessages, displayMessages: stableFlatList }, false, {
payload,
type: `dispatchMessage/${payload.type}`,
});
@@ -150,17 +154,18 @@ export const dataSlice: StateCreator<
// Parse messages using conversation-flow
const { flatList } = parse(messages);
+ const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
log(
'[replaceMessages] | contextKey=%s | prevCount=%d | newCount=%d | displayCount=%d | messageIds=%o',
contextKey,
prevDbMessages.length,
messages.length,
- flatList.length,
+ stableFlatList.length,
messages.slice(0, 5).map((m) => m.id),
);
- set({ dbMessages: messages, displayMessages: flatList }, false, 'replaceMessages');
+ set({ dbMessages: messages, displayMessages: stableFlatList }, false, 'replaceMessages');
// Sync changes to external store (ChatStore)
get().onMessagesChange?.(messages, get().context);
@@ -211,6 +216,7 @@ export const dataSlice: StateCreator<
// Parse messages using conversation-flow
const { flatList } = parse(mergedMessages);
+ const stableFlatList = stabilizeReferences(get().displayMessages, flatList);
log(
'[useFetchMessages] onData | requestContextKey=%s | storeContextKey=%s | prevCount=%d | fetchedCount=%d | displayCount=%d | messageIds=%o',
@@ -218,13 +224,13 @@ export const dataSlice: StateCreator<
storeContextKey,
prevDbMessages.length,
mergedMessages.length,
- flatList.length,
+ stableFlatList.length,
mergedMessages.slice(0, 5).map((m) => m.id),
);
set({
dbMessages: mergedMessages,
- displayMessages: flatList,
+ displayMessages: stableFlatList,
messagesInit: true,
});
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index fdc82e535b0..539a748cb53 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -1,4 +1,8 @@
-import { type AssistantContentBlock, type UIChatMessage } from '@lobechat/types';
+import type {
+ AssistantContentBlock,
+ ChatToolPayloadWithResult,
+ UIChatMessage,
+} from '@lobechat/types';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -124,6 +128,76 @@ const pendingInterventions = (s: State) => getPendingInterventions(s.displayMess
const isSecondLastMessageFromUser = (s: State) => s.displayMessages.at(-2)?.role === 'user';
+const toAssistantContentBlock = (message: UIChatMessage): AssistantContentBlock => ({
+ content: message.content,
+ error: message.error,
+ fileList: message.fileList,
+ id: message.id,
+ imageList: message.imageList,
+ metadata: message.metadata ?? undefined,
+ performance: message.performance,
+ reasoning: message.reasoning ?? undefined,
+ tasks: message.tasks as AssistantContentBlock['tasks'],
+ tools: message.tools as ChatToolPayloadWithResult[],
+ usage: message.usage,
+});
+
+/**
+ * Walk displayMessages (including compressed groups and agentCouncil members)
+ * to find an assistant content block by its id. Used to let tool subtrees
+ * self-subscribe to their own data instead of receiving it as props from the
+ * message-level renderer.
+ */
+const findBlockById = (
+ blockId: string,
+ messages: UIChatMessage[],
+): AssistantContentBlock | undefined => {
+ for (const message of messages) {
+ if (message.role === 'assistant' && message.id === blockId) {
+ return toAssistantContentBlock(message);
+ }
+ if (message.children) {
+ const block = message.children.find((child) => child.id === blockId);
+ if (block) return block;
+ }
+ if (message.compressedMessages) {
+ const inCompressedMessages = findBlockById(blockId, message.compressedMessages);
+ if (inCompressedMessages) return inCompressedMessages;
+ }
+ if (message.role === 'agentCouncil' && (message as any).members) {
+ const inMembers = findBlockById(blockId, (message as any).members);
+ if (inMembers) return inMembers;
+ }
+ }
+ return undefined;
+};
+
+const getToolsInBlock =
+ (blockId: string) =>
+ (s: State): ChatToolPayloadWithResult[] | undefined => {
+ const block = findBlockById(blockId, s.displayMessages);
+ return block?.tools;
+ };
+
+const getToolInBlock =
+ (blockId: string, toolCallId: string) =>
+ (s: State): ChatToolPayloadWithResult | undefined => {
+ const tools = getToolsInBlock(blockId)(s);
+ return tools?.find((t) => t.id === toolCallId);
+ };
+
+const getBlockContent =
+ (blockId: string) =>
+ (s: State): string | undefined =>
+ findBlockById(blockId, s.displayMessages)?.content;
+
+const getBlockHasTools =
+ (blockId: string) =>
+ (s: State): boolean => {
+ const tools = findBlockById(blockId, s.displayMessages)?.tools;
+ return !!tools && tools.length > 0;
+ };
+
export const dataSelectors = {
currentTopicSummary,
dbMessages,
@@ -132,8 +206,12 @@ export const dataSelectors = {
findLastMessageId,
getDbMessageById,
getDbMessageByToolCallId,
+ getBlockContent,
+ getBlockHasTools,
getDisplayMessageById,
getGroupLatestMessageWithoutTools,
+ getToolInBlock,
+ getToolsInBlock,
isSecondLastMessageFromUser,
messagesInit,
pendingInterventions,
diff --git a/src/features/Conversation/store/slices/data/stabilizeReferences.test.ts b/src/features/Conversation/store/slices/data/stabilizeReferences.test.ts
new file mode 100644
index 00000000000..37a252b53ae
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/stabilizeReferences.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+
+import { stabilizeReferences } from './stabilizeReferences';
+
+describe('stabilizeReferences', () => {
+ it('returns prev when deeply equal', () => {
+ const prev = { a: 1, b: { c: 2 } };
+ const next = { a: 1, b: { c: 2 } };
+ expect(stabilizeReferences(prev, next)).toBe(prev);
+ });
+
+ it('returns next for primitive replacement', () => {
+ expect(stabilizeReferences(1, 2)).toBe(2);
+ expect(stabilizeReferences('a', 'b')).toBe('b');
+ });
+
+ it('preserves unchanged sub-objects when sibling changes', () => {
+ const prevChild = { id: 'c1', value: 'same' };
+ const prev = { a: prevChild, b: { id: 'b', value: 1 } };
+ const next = { a: { id: 'c1', value: 'same' }, b: { id: 'b', value: 2 } };
+
+ const result = stabilizeReferences(prev, next);
+
+ expect(result).not.toBe(prev);
+ expect(result.a).toBe(prevChild);
+ expect(result.b).not.toBe(prev.b);
+ expect(result.b.value).toBe(2);
+ });
+
+ it('preserves unchanged array elements when siblings change', () => {
+ const stableTool = { id: 't1', args: '{}' };
+ const prev = [stableTool, { id: 't2', args: '{"k":1}' }];
+ const next = [
+ { id: 't1', args: '{}' },
+ { id: 't2', args: '{"k":2}' },
+ ];
+
+ const result = stabilizeReferences(prev, next);
+
+ expect(result[0]).toBe(stableTool);
+ expect(result[1]).not.toBe(prev[1]);
+ });
+
+ it('returns next when array length differs', () => {
+ const prev = [1, 2, 3];
+ const next = [1, 2];
+ expect(stabilizeReferences(prev, next)).toEqual(next);
+ });
+
+ it('returns next when object keys differ', () => {
+ const prev = { a: 1 };
+ const next = { a: 1, b: 2 };
+ expect(stabilizeReferences(prev, next)).toEqual(next);
+ });
+
+ it('returns next for changed non-plain objects', () => {
+ const prev = new Date('2026-01-01T00:00:00.000Z');
+ const next = new Date('2026-01-02T00:00:00.000Z');
+
+ expect(stabilizeReferences(prev, next)).toBe(next);
+ });
+
+ it('handles null and undefined safely', () => {
+ expect(stabilizeReferences(null, null)).toBe(null);
+ expect(stabilizeReferences(undefined, undefined)).toBe(undefined);
+ expect(stabilizeReferences(null, { a: 1 })).toEqual({ a: 1 });
+ expect(stabilizeReferences({ a: 1 }, null)).toBe(null);
+ });
+
+ it('handles array vs non-array shape change', () => {
+ expect(stabilizeReferences([1, 2], { 0: 1, 1: 2 } as any)).toEqual({ 0: 1, 1: 2 });
+ });
+
+ it('preserves deep tool tree across streaming-like updates', () => {
+ const finishedTool = {
+ id: 'tool-finished',
+ apiName: 'fetch',
+ arguments: '{"url":"https://x"}',
+ result: { id: 'r1', content: 'ok' },
+ };
+ const prev = {
+ id: 'msg',
+ children: [
+ {
+ id: 'block',
+ content: 'hello',
+ tools: [finishedTool, { id: 'tool-streaming', arguments: '{"u' }],
+ },
+ ],
+ };
+ const next = {
+ id: 'msg',
+ children: [
+ {
+ id: 'block',
+ content: 'hello world',
+ tools: [{ ...finishedTool }, { id: 'tool-streaming', arguments: '{"url":"https://y"}' }],
+ },
+ ],
+ };
+
+ const result = stabilizeReferences(prev, next);
+
+ // top-level changed because content changed
+ expect(result).not.toBe(prev);
+ // finished tool reference preserved despite outer message rebuild
+ expect(result.children[0].tools[0]).toBe(finishedTool);
+ // streaming tool changed
+ expect(result.children[0].tools[1]).not.toBe(prev.children[0].tools[1]);
+ });
+});
diff --git a/src/features/Conversation/store/slices/data/stabilizeReferences.ts b/src/features/Conversation/store/slices/data/stabilizeReferences.ts
new file mode 100644
index 00000000000..fb706d0bce8
--- /dev/null
+++ b/src/features/Conversation/store/slices/data/stabilizeReferences.ts
@@ -0,0 +1,15 @@
+import { replaceEqualDeep } from '@tanstack/react-query';
+
+/**
+ * Recursively replace references in `next` with references from `prev`
+ * where the values are deeply equal.
+ *
+ * Why: `parse()` from @lobechat/conversation-flow rebuilds the entire
+ * displayMessages tree on every dispatch (including streaming chunks), which
+ * gives every message / block / tool / result a fresh reference. That defeats
+ * `memo` and `useStore(selector, isEqual)` for unchanged subtrees and causes
+ * the assistant message subtree to re-render entirely on every chunk. Walking
+ * old vs new and pinning unchanged subtrees back to their previous reference
+ * preserves identity so React and Zustand can bail out as designed.
+ */
+export const stabilizeReferences = <T>(prev: T, next: T): T => replaceEqualDeep(prev, next);