🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: fix favorite refresh bug and group topic refresh issue (#11745)
Arvin Xu5d115ef3cb5d
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 107540d0a86..65d32fede46 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -177,6 +177,9 @@"builtins.lobe-user-memory.apiName.searchUserMemory": "Search memory","builtins.lobe-user-memory.apiName.updateIdentityMemory": "Update identity memory","builtins.lobe-user-memory.inspector.noResults": "No results",+ "builtins.lobe-user-memory.render.contexts": "Contexts",+ "builtins.lobe-user-memory.render.experiences": "Experiences",+ "builtins.lobe-user-memory.render.preferences": "Preferences","builtins.lobe-user-memory.title": "Memory","builtins.lobe-web-browsing.apiName.crawlMultiPages": "Read multiple pages","builtins.lobe-web-browsing.apiName.crawlSinglePage": "Read page content",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex a6f74b63138..a3b22ce2e69 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -177,6 +177,9 @@"builtins.lobe-user-memory.apiName.searchUserMemory": "搜索记忆","builtins.lobe-user-memory.apiName.updateIdentityMemory": "更新身份记忆","builtins.lobe-user-memory.inspector.noResults": "无结果",+ "builtins.lobe-user-memory.render.contexts": "情境",+ "builtins.lobe-user-memory.render.experiences": "经验",+ "builtins.lobe-user-memory.render.preferences": "偏好","builtins.lobe-user-memory.title": "记忆","builtins.lobe-web-browsing.apiName.crawlMultiPages": "读取多个页面内容","builtins.lobe-web-browsing.apiName.crawlSinglePage": "读取页面内容",diff --git a/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsxindex 8395c8dc244..b1e9c4bdbdf 100644--- a/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx+++ b/packages/builtin-tool-memory/src/client/Render/SearchUserMemory/index.tsx@@ -6,8 +6,6 @@ import { createStaticStyles } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import { highlightTextStyles } from '@/styles';-import type { SearchMemoryParams, SearchUserMemoryState } from '../../../types';const styles = createStaticStyles(({ css, cssVar }) => ({@@ -120,9 +118,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, SearcpaddingInline={12}title={<Text className={styles.sectionHeader}>- <span className={highlightTextStyles.info}>- {t('builtins.lobe-user-memory.render.contexts' as any)}- </span>+ <span>{t('builtins.lobe-user-memory.render.contexts')}</span><Text as={'span'} type={'secondary'}>{' '}({contexts.length})@@ -152,9 +148,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, SearcpaddingInline={12}title={<Text className={styles.sectionHeader}>- <span className={highlightTextStyles.gold}>- {t('builtins.lobe-user-memory.render.experiences' as any)}- </span>+ <span>{t('builtins.lobe-user-memory.render.experiences')}</span><Text as={'span'} type={'secondary'}>{' '}({experiences.length})@@ -184,9 +178,7 @@ const SearchUserMemoryRender = memo<BuiltinRenderProps<SearchMemoryParams, SearcpaddingInline={12}title={<Text className={styles.sectionHeader}>- <span className={highlightTextStyles.warning}>- {t('builtins.lobe-user-memory.render.preferences' as any)}- </span>+ <span>{t('builtins.lobe-user-memory.render.preferences')}</span><Text as={'span'} type={'secondary'}>{' '}({preferences.length})diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.tsindex 8682f146574..84e8926f7e9 100644--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts@@ -9,7 +9,6 @@ import {GroupMessageFlattenProcessor,GroupOrchestrationFilterProcessor,GroupRoleTransformProcessor,- HistoryTruncateProcessor,InputTemplateProcessor,MessageCleanupProcessor,MessageContentProcessor,@@ -113,8 +112,6 @@ export class MessagesEngine {provider,systemRole,inputTemplate,- enableHistoryCount,- historyCount,historySummary,formatHistorySummary,knowledge,@@ -145,16 +142,6 @@ export class MessagesEngine {const isGTDTodoEnabled = gtd?.enabled && gtd?.todos;return [- // =============================================- // Phase 1: History Management- // =============================================-- // 1. History truncation (MUST be first, before any message injection)- new HistoryTruncateProcessor({- enableHistoryCount,- historyCount,- }),-// =============================================// Phase 2: System Role Injection// =============================================diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.tsindex 746a8503a6f..2718fa9d1a7 100644--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts@@ -113,31 +113,6 @@ describe('MessagesEngine', () => {expect(result.messages[0].content).toBe(systemRole);});- it('should truncate history when enabled', async () => {- const messages: UIChatMessage[] = [];- for (let i = 0; i < 20; i++) {- messages.push({- content: `Message ${i}`,- createdAt: Date.now(),- id: `msg-${i}`,- role: i % 2 === 0 ? 'user' : 'assistant',- updatedAt: Date.now(),- } as UIChatMessage);- }-- const params = createBasicParams({- enableHistoryCount: true,- historyCount: 5,- messages,- });- const engine = new MessagesEngine(params);-- const result = await engine.process();-- // Should have truncated to 5 messages- expect(result.messages.length).toBeLessThanOrEqual(5);- });-it('should inject history summary when provided', async () => {const historySummary = 'We discussed AI and machine learning';const params = createBasicParams({ historySummary });diff --git a/packages/database/src/models/__tests__/topics/topic.create.test.ts b/packages/database/src/models/__tests__/topics/topic.create.test.tsindex fce6a74c10a..3fee147facb 100644--- a/packages/database/src/models/__tests__/topics/topic.create.test.ts+++ b/packages/database/src/models/__tests__/topics/topic.create.test.ts@@ -1,4 +1,4 @@-import { eq, inArray } from 'drizzle-orm';+import { asc, eq, inArray } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../../core/getTestDB';@@ -188,12 +188,12 @@ describe('TopicModel - Create', () => {userId,});- const items = await serverDB.select().from(topics);+ const items = await serverDB.select().from(topics).orderBy(asc(topics.title));expect(items).toHaveLength(2);expect(items[0]).toMatchObject({ title: 'Topic 1', favorite: true, sessionId, userId });expect(items[1]).toMatchObject({ title: 'Topic 2', favorite: false, sessionId, userId });- const updatedMessages = await serverDB.select().from(messages);+ const updatedMessages = await serverDB.select().from(messages).orderBy(asc(messages.id));expect(updatedMessages).toHaveLength(3);expect(updatedMessages[0].topicId).toBe(createdTopics[0].id);expect(updatedMessages[1].topicId).toBe(createdTopics[0].id);diff --git a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsxindex b8eeed77294..785844f63ec 100644--- a/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/app/[variants]/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx@@ -110,6 +110,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) =>fill={fav ? cssVar.colorWarning : 'transparent'}icon={Star}onClick={(e) => {+ e.preventDefault();e.stopPropagation();favoriteTopic(id, !fav);}}diff --git a/src/app/[variants]/(main)/agent/features/Conversation/ConversationArea.tsx b/src/app/[variants]/(main)/agent/features/Conversation/ConversationArea.tsxindex 19491e78551..f201c4935c8 100644--- a/src/app/[variants]/(main)/agent/features/Conversation/ConversationArea.tsx+++ b/src/app/[variants]/(main)/agent/features/Conversation/ConversationArea.tsx@@ -1,6 +1,7 @@'use client';import { Flexbox } from '@lobehub/ui';+import debug from 'debug';import { Suspense, memo, useMemo } from 'react';import ChatMiniMap from '@/features/ChatMiniMap';@@ -18,6 +19,8 @@ import ThreadHydration from './ThreadHydration';import { useActionsBarConfig } from './useActionsBarConfig';import { useAgentContext } from './useAgentContext';+const log = debug('lobe-render:agent:ConversationArea');+/*** ConversationArea*@@ -35,6 +38,7 @@ const Conversation = memo(() => {);const replaceMessages = useChatStore((s) => s.replaceMessages);const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);+ log('contextKey %s: %o', chatKey, messages);// Get operation state from ChatStore for reactive updatesconst operationState = useOperationState(context);diff --git a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsxindex 326b4293c68..b9edc24266e 100644--- a/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx+++ b/src/app/[variants]/(main)/group/_layout/Sidebar/Topic/List/Item/index.tsx@@ -111,6 +111,7 @@ const TopicItem = memo<TopicItemProps>(({ id, title, fav, active, threadId }) =>fill={fav ? cssVar.colorWarning : 'transparent'}icon={Star}onClick={(e) => {+ e.preventDefault();e.stopPropagation();favoriteTopic(id, !fav);}}diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsxindex ad7fa25b11d..76521a77cb4 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/AgentItem/index.tsx@@ -106,7 +106,7 @@ const AgentItem = memo<AgentItemProps>(({ item, style, className }) => {return (<>- <Link aria-label={id} to={agentUrl}>+ <Link aria-label={displayTitle} to={agentUrl}><NavItemactions={<Actions dropdownMenu={dropdownMenu} />}className={className}diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/InboxItem.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/InboxItem.tsxindex 2eb61e73fce..3877eec82d4 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/InboxItem.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/InboxItem.tsx@@ -2,8 +2,8 @@import { DEFAULT_INBOX_AVATAR, SESSION_CHAT_URL } from '@lobechat/const';import { Avatar } from '@lobehub/ui';-import { type CSSProperties, memo, useCallback } from 'react';-import { useNavigate } from 'react-router-dom';+import { type CSSProperties, memo } from 'react';+import { Link } from 'react-router-dom';import NavItem from '@/features/NavPanel/components/NavItem';import { useAgentStore } from '@/store/agent';@@ -17,38 +17,28 @@ interface InboxItemProps {}const InboxItem = memo<InboxItemProps>(({ className, style }) => {- const navigate = useNavigate();-const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);- const activeAgentId = useAgentStore((s) => s.activeAgentId);- const isActive = !!inboxAgentId && activeAgentId === inboxAgentId;- const isLoading = useChatStore(- useCallback(- (s) => (isActive ? operationSelectors.isAgentRuntimeRunning(s) : false),- [isActive],- ),- );+ const isLoading = useChatStore(operationSelectors.isAgentRuntimeRunning);const inboxAgentTitle = 'Lobe AI';- const handleClick = useCallback(() => {- if (inboxAgentId) {- navigate(SESSION_CHAT_URL(inboxAgentId, false));- }- }, [inboxAgentId, navigate]);-return (- <NavItem- active={isActive}- className={className}- icon={- <Avatar avatar={DEFAULT_INBOX_AVATAR} emojiScaleWithBackground shape={'square'} size={24} />- }- loading={isLoading}- onClick={handleClick}- style={style}- title={inboxAgentTitle}- />+ <Link aria-label={inboxAgentTitle} to={SESSION_CHAT_URL(inboxAgentId, false)}>+ <NavItem+ className={className}+ icon={+ <Avatar+ avatar={DEFAULT_INBOX_AVATAR}+ emojiScaleWithBackground+ shape={'square'}+ size={24}+ />+ }+ loading={isLoading}+ style={style}+ title={inboxAgentTitle}+ />+ </Link>);});diff --git a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/List.tsx b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/List.tsxindex fc22caef9e7..3014139b848 100644--- a/src/app/[variants]/(main)/home/_layout/Body/Agent/List/List.tsx+++ b/src/app/[variants]/(main)/home/_layout/Body/Agent/List/List.tsx@@ -4,6 +4,7 @@ import { MoreHorizontal } from 'lucide-react';import { type CSSProperties, memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';import NavItem from '@/features/NavPanel/components/NavItem';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';@@ -11,7 +12,6 @@ import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';import { SessionDefaultGroup } from '@/types/session';-import EmptyNavItem from '../../../../../../../../features/NavPanel/components/EmptyNavItem';import { useCreateMenuItems } from '../../../hooks';import GroupItem from './AgentGroupItem';import AgentItem from './AgentItem';diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex fffbde9fcd1..62bf1ea6e54 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -178,6 +178,9 @@ export default {'builtins.lobe-user-memory.apiName.searchUserMemory': 'Search memory','builtins.lobe-user-memory.apiName.updateIdentityMemory': 'Update identity memory','builtins.lobe-user-memory.inspector.noResults': 'No results',+ 'builtins.lobe-user-memory.render.contexts': 'Contexts',+ 'builtins.lobe-user-memory.render.experiences': 'Experiences',+ 'builtins.lobe-user-memory.render.preferences': 'Preferences','builtins.lobe-user-memory.title': 'Memory','builtins.lobe-web-browsing.apiName.crawlMultiPages': 'Read multiple pages','builtins.lobe-web-browsing.apiName.crawlSinglePage': 'Read page content',diff --git a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsindex d785e3c6d29..dc060557af1 100644--- a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts+++ b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -68,31 +68,6 @@ describe('serverMessagesEngine', () => {});});- describe('history truncation', () => {- it('should truncate history when enabled', async () => {- const messages: UIChatMessage[] = [];- for (let i = 0; i < 20; i++) {- messages.push({- content: `Message ${i}`,- createdAt: Date.now(),- id: `msg-${i}`,- role: i % 2 === 0 ? 'user' : 'assistant',- updatedAt: Date.now(),- } as UIChatMessage);- }-- const result = await serverMessagesEngine({- enableHistoryCount: true,- historyCount: 5,- messages,- model: 'gpt-4',- provider: 'openai',- });-- expect(result.length).toBeLessThanOrEqual(5);- });- });-describe('knowledge injection', () => {it('should inject file contents', async () => {const messages = createBasicMessages();diff --git a/src/services/chat/chat.test.ts b/src/services/chat/chat.test.tsindex 93e74836c39..cd64658a476 100644--- a/src/services/chat/chat.test.ts+++ b/src/services/chat/chat.test.ts@@ -155,7 +155,7 @@ describe('ChatService', () => {]),messages: expect.anything(),}),- undefined,+ expect.anything(),);});@@ -185,7 +185,7 @@ describe('ChatService', () => {type: 'enabled',},}),- undefined,+ expect.anything(),);});@@ -214,7 +214,7 @@ describe('ChatService', () => {type: 'disabled',},}),- undefined,+ expect.anything(),);});@@ -244,7 +244,7 @@ describe('ChatService', () => {type: 'enabled',},}),- undefined,+ expect.anything(),);});@@ -270,7 +270,7 @@ describe('ChatService', () => {expect.objectContaining({reasoning_effort: 'high',}),- undefined,+ expect.anything(),);});@@ -296,7 +296,7 @@ describe('ChatService', () => {expect.objectContaining({thinkingBudget: 5000,}),- undefined,+ expect.anything(),);});});@@ -370,7 +370,7 @@ describe('ChatService', () => {enabledSearch: undefined,tools: undefined,},- undefined,+ expect.anything(),);});@@ -396,7 +396,7 @@ describe('ChatService', () => {stream: true,tools: undefined,},- undefined,+ expect.anything(),);});});@@ -494,7 +494,7 @@ describe('ChatService', () => {enabledSearch: undefined,tools: undefined,},- undefined,+ expect.anything(),);});@@ -583,7 +583,7 @@ describe('ChatService', () => {enabledSearch: undefined,tools: undefined,},- undefined,+ expect.anything(),);});@@ -781,7 +781,7 @@ describe('ChatService', () => {{ content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },],},- undefined,+ expect.anything(),);});@@ -888,7 +888,7 @@ describe('ChatService', () => {{ content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },],},- undefined,+ expect.anything(),);});@@ -926,7 +926,7 @@ describe('ChatService', () => {{ content: 'https://vercel.com/ 请分析 chatGPT 关键词\n\n', role: 'user' },],},- undefined,+ expect.anything(),);});});@@ -985,7 +985,7 @@ describe('ChatService', () => {}),]),}),- undefined,+ expect.anything(),);});@@ -1036,7 +1036,7 @@ describe('ChatService', () => {expect.objectContaining({enabledSearch: true,}),- undefined,+ expect.anything(),);});@@ -1087,7 +1087,7 @@ describe('ChatService', () => {expect.objectContaining({enabledSearch: undefined,}),- undefined,+ expect.anything(),);});});@@ -1385,7 +1385,7 @@ describe('ChatService private methods', () => {expect.objectContaining({enabledContextCaching: false,}),- undefined,+ expect.anything(),);});@@ -1438,7 +1438,7 @@ describe('ChatService private methods', () => {expect.objectContaining({reasoning_effort: 'high',}),- undefined,+ expect.anything(),);});@@ -1464,7 +1464,7 @@ describe('ChatService private methods', () => {expect.objectContaining({thinkingBudget: 5000,}),- undefined,+ expect.anything(),);});});diff --git a/src/services/chat/index.ts b/src/services/chat/index.tsindex 5c74d6b7005..3ac8b8e0668 100644--- a/src/services/chat/index.ts+++ b/src/services/chat/index.ts@@ -284,7 +284,7 @@ class ChatService {stream: chatConfig.enableStreaming !== false,tools,},- options,+ { ...options, agentId: targetAgentId, topicId },);};@@ -314,7 +314,7 @@ class ChatService {};getChatCompletion = async (params: Partial<ChatStreamPayload>, options?: FetchOptions) => {- const { signal, responseAnimation } = options ?? {};+ const { agentId, signal, responseAnimation, topicId } = options ?? {};const { provider = ModelProvider.OpenAI, ...res } = params;@@ -401,7 +401,12 @@ class ChatService {const traceHeader = createTraceHeader({ ...options?.trace });const headers = await createHeaderWithAuth({- headers: { 'Content-Type': 'application/json', ...traceHeader },+ headers: {+ 'Content-Type': 'application/json',+ ...traceHeader,+ ...(agentId && { 'x-agent-id': agentId }),+ ...(topicId && { 'x-topic-id': topicId }),+ },provider,});diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.tsindex 3b7cfbe9b7e..f2d94fd71c5 100644--- a/src/services/chat/mecha/agentConfigResolver.test.ts+++ b/src/services/chat/mecha/agentConfigResolver.test.ts@@ -48,6 +48,31 @@ describe('resolveAgentConfig', () => {expect(result.isBuiltinAgent).toBe(false);});+ it('should treat agent with non-builtin slug as regular agent', () => {+ // Agent has a random slug that is NOT a valid builtin agent slug+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(+ () => 'sister-religious-mostly-effort',+ );++ const result = resolveAgentConfig({ agentId: 'test-agent' });++ expect(result.isBuiltinAgent).toBe(false);+ expect(result.slug).toBeUndefined();+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ });++ it('should treat agent with random slug as regular agent', () => {+ // Another example of random/custom slug+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(+ () => 'my-custom-agent-slug',+ );++ const result = resolveAgentConfig({ agentId: 'test-agent' });++ expect(result.isBuiltinAgent).toBe(false);+ expect(result.slug).toBeUndefined();+ });+it('should return empty array when agent config has no plugins', () => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentConfigById').mockReturnValue(() =>@@ -668,6 +693,29 @@ describe('resolveAgentConfig', () => {expect(result.agentConfig.systemRole.trim()).toBe('You are a helpful assistant');expect(result.chatConfig.enableHistoryCount).toBe(false);});++ it('should not duplicate injection when page-agent itself is used in page scope', () => {+ // page-agent is a builtin agent with slug 'page-agent'+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(+ () => 'page-agent',+ );++ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({+ plugins: [PageAgentIdentifier],+ systemRole: 'Page agent system prompt',+ });++ const result = resolveAgentConfig({+ agentId: 'page-agent-id',+ scope: 'page',+ });++ // page-agent should NOT have its tools/systemRole injected again+ expect(result.plugins.filter((p) => p === PageAgentIdentifier)).toHaveLength(1);+ expect(result.agentConfig.systemRole).toBe('Page agent system prompt');+ expect(result.isBuiltinAgent).toBe(true);+ expect(result.slug).toBe('page-agent');+ });});describe('supervisor agent (detected via groupId)', () => {@@ -695,13 +743,11 @@ describe('resolveAgentConfig', () => {});describe('supervisor with own slug (priority check)', () => {- // This tests the fix for LOBE-4127: When supervisor agent has its own slug,- // it should still use 'group-supervisor' slug when in group scope-+ // When supervisor agent has its own slug, it should still use 'group-supervisor' slug when in group scopeit('should use group-supervisor slug even when agent has its own slug in group scope', () => {// Supervisor agent has its own slug (e.g., from being a builtin agent)vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-agent-slug',+ () => 'agent-builder',);// Mock: groupById returns the group@@ -734,54 +780,6 @@ describe('resolveAgentConfig', () => {expect(result.slug).toBe('group-supervisor');expect(result.plugins).toContain(GroupManagementIdentifier);});-- it('should use agent own slug when scope is not group', () => {- // Supervisor agent has its own slug- vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-agent-slug',- );-- // Mock: groupById returns the group- vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(- () => mockGroupWithSupervisor as any,- );-- vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({- plugins: ['agent-specific-plugin'],- systemRole: 'Agent specific system role',- });-- const result = resolveAgentConfig({- agentId: 'supervisor-agent-id',- groupId: 'group-123',- scope: 'main', // Not 'group' scope- });-- // Should use agent's own slug since scope is not 'group'- expect(result.isBuiltinAgent).toBe(true);- expect(result.slug).toBe('some-agent-slug');- });-- it('should use agent own slug when groupId is not provided', () => {- // Supervisor agent has its own slug- vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-agent-slug',- );-- vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({- plugins: ['agent-specific-plugin'],- systemRole: 'Agent specific system role',- });-- const result = resolveAgentConfig({- agentId: 'supervisor-agent-id',- scope: 'group', // Even with group scope, no groupId- });-- // Should use agent's own slug since no groupId- expect(result.isBuiltinAgent).toBe(true);- expect(result.slug).toBe('some-agent-slug');- });});it('should detect supervisor agent using groupId for direct lookup', () => {@@ -872,6 +870,25 @@ describe('resolveAgentConfig', () => {expect(result.plugins).toEqual(['plugin-a', 'plugin-b']); // Falls back to agent config plugins});+ it('should treat as regular agent when scope is not group even with groupId', () => {+ // Mock: groupById returns the group (supervisor agent exists)+ vi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(+ () => mockGroupWithSupervisor as any,+ );++ // groupId is provided but scope is 'main', not 'group'+ const result = resolveAgentConfig({+ agentId: 'supervisor-agent-id',+ groupId: 'group-123',+ scope: 'main', // Not 'group' scope+ });++ // Should NOT be identified as group-supervisor because scope !== 'group'+ expect(result.isBuiltinAgent).toBe(false);+ expect(result.slug).toBeUndefined();+ expect(result.plugins).toEqual(['plugin-a', 'plugin-b']);+ });+it('should treat as regular agent when agentId does not match group supervisorAgentId', () => {// Mock: groupById returns the groupvi.spyOn(agentGroupSelectors.agentGroupByIdSelectors, 'groupById').mockReturnValue(@@ -1016,7 +1033,7 @@ describe('resolveAgentConfig', () => {it('should filter lobe-gtd for builtin agent when isSubTask is true', () => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-builtin-slug',+ () => 'agent-builder',);vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({plugins: ['lobe-gtd', 'runtime-plugin'],@@ -1034,7 +1051,7 @@ describe('resolveAgentConfig', () => {it('should keep lobe-gtd for builtin agent when isSubTask is false', () => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-builtin-slug',+ () => 'agent-builder',);vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({plugins: ['lobe-gtd', 'runtime-plugin'],@@ -1089,7 +1106,7 @@ describe('resolveAgentConfig', () => {it('should return empty plugins for builtin agent when disableTools is true', () => {vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(- () => 'some-builtin-slug',+ () => 'agent-builder',);vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({plugins: ['runtime-plugin-1', 'runtime-plugin-2'],diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.tsindex ae0bfaa6653..267d8af670e 100644--- a/src/services/chat/mecha/agentConfigResolver.ts+++ b/src/services/chat/mecha/agentConfigResolver.ts@@ -1,4 +1,8 @@-import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';+import {+ BUILTIN_AGENT_SLUGS,+ type BuiltinAgentSlug,+ getAgentRuntimeConfig,+} from '@lobechat/builtin-agents';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import {type LobeAgentChatConfig,@@ -15,6 +19,18 @@ import { agentGroupByIdSelectors, agentGroupSelectors } from '@/store/agentGroupconst log = debug('mecha:agentConfigResolver');+/**+ * Set of valid builtin agent slugs for O(1) lookup+ */+const VALID_BUILTIN_SLUGS = new Set<string>(Object.values(BUILTIN_AGENT_SLUGS));++/**+ * Check if a slug is a valid builtin agent slug+ */+const isBuiltinAgentSlug = (slug: string): slug is BuiltinAgentSlug => {+ return VALID_BUILTIN_SLUGS.has(slug);+};+/*** Applies params adjustments based on chatConfig settings.*@@ -187,12 +203,20 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge// If not identified as supervisor, check agent store for slugif (!slug) {- slug = agentSelectors.getAgentSlugById(agentId)(agentStoreState) ?? undefined;- log('slug from agentStore: %s (agentId: %s)', slug, agentId);+ const storeSlug = agentSelectors.getAgentSlugById(agentId)(agentStoreState) ?? undefined;+ log('slug from agentStore: %s (agentId: %s)', storeSlug, agentId);++ // Only use the slug if it's a valid builtin agent slug+ // Regular agents may have random slugs that should be ignored+ if (storeSlug && isBuiltinAgentSlug(storeSlug)) {+ slug = storeSlug;+ } else if (storeSlug) {+ log('slug %s is not a valid builtin agent slug, treating as regular agent', storeSlug);+ }}if (!slug) {- log('agentId %s is not a builtin agent (no slug found)', agentId);+ log('agentId %s is not a builtin agent (no valid builtin slug found)', agentId);// Regular agent - use provided plugins if available, fallback to agent's pluginsconst finalPlugins = plugins && plugins.length > 0 ? plugins : basePlugins;diff --git a/src/services/chat/mecha/contextEngineering.test.ts b/src/services/chat/mecha/contextEngineering.test.tsindex db1502a0d49..c58dc60fa10 100644--- a/src/services/chat/mecha/contextEngineering.test.ts+++ b/src/services/chat/mecha/contextEngineering.test.ts@@ -583,7 +583,7 @@ describe('contextEngineering', () => {});describe('Message preprocessing processors', () => {- it('should truncate message history when enabled', async () => {+ it('should keep all messages (no history truncation)', async () => {const messages: UIChatMessage[] = [{role: 'user',@@ -626,13 +626,12 @@ describe('contextEngineering', () => {messages,model: 'gpt-4',provider: 'openai',- enableHistoryCount: true,- historyCount: 4, // Should keep last 2 messages});- // Should only keep the last 2 messages- expect(result).toHaveLength(4);+ // Should keep all messages+ expect(result).toHaveLength(5);expect(result).toEqual([+ { content: 'Message 1', role: 'user' },{ content: 'Response 1', role: 'assistant' },{ content: 'Message 2', role: 'user' },{ content: 'Response 2', role: 'assistant' },@@ -704,7 +703,7 @@ describe('contextEngineering', () => {]);});- it('should combine all preprocessing steps correctly', async () => {+ it('should combine system role and input template correctly', async () => {const messages: UIChatMessage[] = [{role: 'user',@@ -735,16 +734,18 @@ describe('contextEngineering', () => {provider: 'openai',systemRole: 'System instructions.',inputTemplate: 'Processed: {{text}}',- enableHistoryCount: true,- historyCount: 2, // Should keep last 1 message});- // System role should be first+ // System role should be first, followed by all messages with input template applied to user messagesexpect(result).toEqual([{content: 'System instructions.',role: 'system',},+ {+ content: 'Processed: Old message 1',+ role: 'user',+ },{role: 'assistant',content: 'Old response',@@ -782,7 +783,7 @@ describe('contextEngineering', () => {]);});- it('should handle history truncation with system role injection correctly', async () => {+ it('should handle system role injection with all messages (no history truncation)', async () => {const messages: UIChatMessage[] = [{role: 'user',@@ -812,18 +813,24 @@ describe('contextEngineering', () => {model: 'gpt-4',provider: 'openai',systemRole: 'System role here.',- enableHistoryCount: true,- historyCount: 1, // Should keep only 1 message});- // Should have system role + 1 truncated message+ // Should have system role + all messagesexpect(result).toEqual([{content: 'System role here.',role: 'system',},{- content: 'Message 3', // Only the last message should remain+ content: 'Message 1',+ role: 'user',+ },+ {+ content: 'Message 2',+ role: 'user',+ },+ {+ content: 'Message 3',role: 'user',},]);diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.tsindex c65d8a0d1c0..4592c7e5d65 100644--- a/src/services/chat/mecha/contextEngineering.ts+++ b/src/services/chat/mecha/contextEngineering.ts@@ -394,6 +394,18 @@ export const contextEngineering = async ({...(gtdConfig && { gtd: gtdConfig }),});+ log('Input messages count: %d', messages.length);+const result = await engine.process();++ log('Output messages count: %d', result.messages.length);++ if (messages.length > 0 && result.messages.length === 0) {+ log(+ 'WARNING: Messages were reduced to 0! Input messages: %o',+ messages.map((m) => ({ id: m.id, role: m.role })),+ );+ }+return result.messages;};diff --git a/src/services/chat/types.ts b/src/services/chat/types.tsindex ca37787bdc7..e1292bf66b4 100644--- a/src/services/chat/types.ts+++ b/src/services/chat/types.ts@@ -1,12 +1,18 @@import { type FetchSSEOptions } from '@lobechat/fetch-sse';-import { type RuntimeInitialContext, type RuntimeStepContext, type TracePayload } from '@lobechat/types';+import {+ type RuntimeInitialContext,+ type RuntimeStepContext,+ type TracePayload,+} from '@lobechat/types';export interface FetchOptions extends FetchSSEOptions {+ agentId?: string;historySummary?: string;/** Initial context for page editor (captured at operation start) */initialContext?: RuntimeInitialContext;signal?: AbortSignal | undefined;/** Step context for page editor (updated each step) */stepContext?: RuntimeStepContext;+ topicId?: string;trace?: TracePayload;}diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 61eba233860..3988845a2a7 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -22,10 +22,9 @@ import type { ChatToolPayload, ConversationContext, CreateMessageParams } from 'import debug from 'debug';import pMap from 'p-map';-import type { ResolvedAgentConfig } from '@/services/chat/mecha';-import { LOADING_FLAT } from '@/const/message';import { aiAgentService } from '@/services/aiAgent';+import type { ResolvedAgentConfig } from '@/services/chat/mecha';import { agentByIdSelectors } from '@/store/agent/selectors';import { getAgentStoreState } from '@/store/agent/store';import type { ChatStore } from '@/store/chat/store';@@ -96,7 +95,12 @@ export const createAgentExecutors = (context: {const llmPayload = (instruction as AgentInstructionCallLlm).payload as GeneralAgentCallLLMInstructionPayload;- log(`${stagePrefix} Starting session`);+ log(+ `${stagePrefix} Starting session. Input: state.messages=%d, llmPayload.messages=%d, messageKey=%s`,+ state.messages.length,+ llmPayload.messages.length,+ context.messageKey,+ );let assistantMessageId: string;@@ -184,6 +188,12 @@ export const createAgentExecutors = (context: {// Get latest messages from store (already updated by internal_fetchAIChatMessage)const latestMessages = context.get().dbMessagesMap[context.messageKey] || [];+ log(+ `${stagePrefix} After fetch: dbMessagesMap[${context.messageKey}]=%d messages, available keys=%o`,+ latestMessages.length,+ Object.keys(context.get().dbMessagesMap),+ );+// Get updated assistant message to extract usage/cost informationconst assistantMessage = latestMessages.find((m) => m.id === assistantMessageId);@@ -206,10 +216,11 @@ export const createAgentExecutors = (context: {}log(- '[%s:%d] call_llm completed, finishType: %s',+ '[%s:%d] call_llm completed, finishType: %s, outputMessages: %d',state.operationId,state.stepCount,finishType,+ latestMessages.length,);// Accumulate usage and cost to statediff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex df3b4a2ca8c..981b5fc10b0 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -259,6 +259,7 @@ export const conversationLifecycle: StateCreator<if (data?.topics) {const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());get().internal_updateTopics(operationContext.agentId, {+ groupId: operationContext.groupId,items: data.topics.items,pageSize,total: data.topics.total,diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 487a288d1a1..72d2ab9c157 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -757,20 +757,24 @@ export const streamingExecutor: StateCreator<nextContext = { ...nextContext, stepContext };log(- '[internal_execAgentRuntime][step-%d]: phase=%s, status=%s, stepContext=%O',+ '[internal_execAgentRuntime][step-%d]: phase=%s, status=%s, state.messages=%d, dbMessagesMap[%s]=%d, stepContext=%O',stepCount,nextContext.phase,state.status,+ state.messages.length,+ messageKey,+ currentDBMessages.length,stepContext,);const result = await runtime.step(state, nextContext);log(- '[internal_execAgentRuntime] Step %d completed, events: %d, newStatus=%s',+ '[internal_execAgentRuntime] Step %d completed, events: %d, newStatus=%s, newState.messages=%d',stepCount,result.events.length,result.newState.status,+ result.newState.messages.length,);// After parallel tool batch completes, refresh messages to ensure all tool results are synced