🤯 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
:bug: fix: fix async task and improve tool style
arvinxx1aa1c04a8d22
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsxindex f5f490aa0ce..5428c35db39 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/index.tsx@@ -26,16 +26,9 @@ export interface GroupToolProps {apiName: string;arguments?: string;assistantMessageId: string;- expand?: boolean;- handleExpand?: (expand?: boolean) => void;id: string;identifier: string;intervention?: ToolIntervention;- /**- * Callback to register whether this tool can be collapsed- * Used by parent Accordion to prevent collapsing when alwaysExpand is set- */- onCollapsibleChange?: (canCollapse: boolean) => void;result?: ChatToolResult;toolMessageId?: string;type?: string;@@ -49,11 +42,9 @@ const Tool = memo<GroupToolProps>(id,intervention,identifier,- onCollapsibleChange,result,type,toolMessageId,- handleExpand,}) => {// Get renderDisplayControl from manifestconst renderDisplayControl = useToolStore(@@ -80,40 +71,30 @@ const Tool = memo<GroupToolProps>(const hasStreamingRenderer = !!getBuiltinStreaming(identifier, apiName);const forceShowStreamingRender = isArgumentsStreaming && hasStreamingRenderer;- // Check if tool has custom render - if not, disable expand- // Custom render exists when: builtin render exists OR plugin type is not 'default'- const hasCustomRender = !!getBuiltinRender(identifier, apiName) || (!!type && type !== 'default');+ const hasCustomRender = !!getBuiltinRender(identifier, apiName);- // Wrap handleExpand to prevent collapsing when alwaysExpand is set- const wrappedHandleExpand = (expand?: boolean) => {+ // Handle expand state changes with showPluginRender+ const handleExpand = (expand?: boolean) => {// Block collapse action when alwaysExpand is setif (isAlwaysExpand && expand === false) {return;}- handleExpand?.(expand);+ setShowPluginRender(!!expand);};useEffect(() => {if (needExpand) {- setTimeout(() => wrappedHandleExpand(true), 100);+ setTimeout(() => handleExpand(true), 100);}}, [needExpand]);- // Notify parent about collapsibility- useEffect(() => {- onCollapsibleChange?.(!isAlwaysExpand);- }, [isAlwaysExpand, onCollapsibleChange]);-- useEffect(() => {- handleExpand?.(forceShowStreamingRender);- }, [forceShowStreamingRender]);-+ const isToolRenderExpand = forceShowStreamingRender || showPluginRender;return (<AccordionItemaction={<ActionsassistantMessageId={assistantMessageId}- handleExpand={wrappedHandleExpand}+ handleExpand={handleExpand}identifier={identifier}setShowDebug={setShowDebug}setShowPluginRender={setShowPluginRender}@@ -123,6 +104,7 @@ const Tool = memo<GroupToolProps>(/>}allowExpand={hasCustomRender}+ expand={isToolRenderExpand}itemKey={id}paddingBlock={4}paddingInline={4}diff --git a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx b/src/features/Conversation/Messages/AssistantGroup/Tools.tsxindex 3dd28b7b569..4bc2f1c3d10 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tools.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Tools.tsx@@ -1,6 +1,6 @@import { type ChatToolPayloadWithResult } from '@lobechat/types';-import { Accordion } from '@lobehub/ui';-import { type Key, memo, useCallback, useRef, useState } from 'react';+import { Flexbox } from '@lobehub/ui';+import { memo } from 'react';import Tool from './Tool';@@ -10,67 +10,24 @@ interface ToolsRendererProps {}export const Tools = memo<ToolsRendererProps>(({ messageId, tools }) => {- const [showToolContents, setShowToolDetails] = useState<Key[]>([]);- // Track which tools cannot be collapsed (alwaysExpand)- const nonCollapsibleToolsRef = useRef<Set<string>>(new Set());-- const handleExpandedChange = useCallback((keys: Key[]) => {- setShowToolDetails((prev) => {- // Ensure non-collapsible tools stay expanded- const newKeys = new Set(keys);- for (const toolId of nonCollapsibleToolsRef.current) {- newKeys.add(toolId);- }- // Only update if different from previous- const newKeysArray = [...newKeys];- if (newKeysArray.length === prev.length && newKeysArray.every((k) => prev.includes(k))) {- return prev;- }- return newKeysArray;- });- }, []);-if (!tools || tools.length === 0) return null;return (- <Accordion expandedKeys={showToolContents} gap={8} onExpandedChange={handleExpandedChange}>- {tools.map((tool) => {- return (- <Tool- apiName={tool.apiName}- arguments={tool.arguments}- assistantMessageId={messageId}- expand={showToolContents.includes(tool.id)}- handleExpand={(expand?: boolean) => {- setShowToolDetails((prev = []) => {- if (expand) {- if (!prev.includes(tool.id)) {- return [...prev, tool.id];- } else {- return prev;- }- } else {- return prev.filter((key) => key !== tool.id);- }- });- }}- id={tool.id}- identifier={tool.identifier}- intervention={tool.intervention}- key={tool.id}- onCollapsibleChange={(canCollapse) => {- if (canCollapse) {- nonCollapsibleToolsRef.current.delete(tool.id);- } else {- nonCollapsibleToolsRef.current.add(tool.id);- }- }}- result={tool.result}- toolMessageId={tool.result_msg_id}- type={tool.type}- />- );- })}- </Accordion>+ <Flexbox gap={8}>+ {tools.map((tool) => (+ <Tool+ apiName={tool.apiName}+ arguments={tool.arguments}+ assistantMessageId={messageId}+ id={tool.id}+ identifier={tool.identifier}+ intervention={tool.intervention}+ key={tool.id}+ result={tool.result}+ toolMessageId={tool.result_msg_id}+ type={tool.type}+ />+ ))}+ </Flexbox>);});diff --git a/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts b/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.tsindex 63e70e937f9..01e6c85a606 100644--- a/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts+++ b/src/server/routers/lambda/__tests__/aiAgent.execGroupSubAgentTask.test.ts@@ -194,20 +194,6 @@ describe('aiAgentRouter.execSubAgentTask', () => {).rejects.toThrow();});- it('should reject when groupId is missing', async () => {- const caller = aiAgentRouter.createCaller(createTestContext());-- await expect(- caller.execSubAgentTask({- agentId: testAgentId,- groupId: undefined,- instruction: 'Test instruction',- parentMessageId: 'parent-msg-1',- topicId: testTopicId,- } as any),- ).rejects.toThrow();- });-it('should reject when instruction is missing', async () => {const caller = aiAgentRouter.createCaller(createTestContext());diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex 9458c6dc149..48d66d67158 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -460,7 +460,6 @@ export const aiAgentRouter = router({}}),-getOperationStatus: aiAgentProcedure.input(GetOperationStatusSchema).query(async ({ input, ctx }) => {@@ -482,8 +481,7 @@ export const aiAgentRouter = router({return operationStatus;}),--getPendingInterventions: aiAgentProcedure+ getPendingInterventions: aiAgentProcedure.input(GetPendingInterventionsSchema).query(async ({ input, ctx }) => {const { operationId, userId } = input;@@ -513,7 +511,7 @@ getPendingInterventions: aiAgentProcedure* As a workaround, this endpoint also updates Thread metadata from Redis* when real-time status is available.*/-getSubAgentTaskStatus: aiAgentProcedure+ getSubAgentTaskStatus: aiAgentProcedure.input(z.object({/** Thread ID */@@ -663,6 +661,7 @@ getSubAgentTaskStatus: aiAgentProcedure// Tool message means tool has returned resultcurrentActivity = {apiName: lastMessage.plugin?.apiName ?? undefined,+ contentPreview: lastMessage.content?.slice(0, 100),identifier: lastMessage.plugin?.identifier ?? undefined,type: 'tool_result',};diff --git a/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.tsnew file mode 100644index 00000000000..8817519bfd6--- /dev/null+++ b/src/server/services/aiAgent/__tests__/execAgent.threadId.test.ts@@ -0,0 +1,225 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++// Mock MessageModel to capture create calls+const mockMessageCreate = vi.fn();++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: mockMessageCreate,+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++// Mock AgentModel+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ files: [],+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ })),+}));++// Mock PluginModel+vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock TopicModel+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ })),+}));++// Mock ThreadModel+vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => ({+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ })),+}));++// Mock AgentRuntimeService+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ })),+}));++// Mock Mecha modules+vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),+}));++// Mock model-bank+vi.mock('model-bank', () => ({+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, video: false, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+}));++describe('AiAgentService.execAgent - threadId handling', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();++ // Setup default mock responses+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });++ service = new AiAgentService(mockDb, userId);+ });++ describe('when threadId is provided in appContext', () => {+ it('should pass threadId when creating user message', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ threadId: 'thread-123',+ topicId: 'topic-1',+ },+ prompt: 'Test prompt',+ });++ // Find the user message creation call+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');++ expect(userMessageCall).toBeDefined();+ expect(userMessageCall![0]).toMatchObject({+ content: 'Test prompt',+ role: 'user',+ threadId: 'thread-123',+ topicId: 'topic-1',+ });+ });++ it('should pass threadId when creating assistant message', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ threadId: 'thread-123',+ topicId: 'topic-1',+ },+ prompt: 'Test prompt',+ });++ // Find the assistant message creation call+ const assistantMessageCall = mockMessageCreate.mock.calls.find(+ (call) => call[0].role === 'assistant',+ );++ expect(assistantMessageCall).toBeDefined();+ expect(assistantMessageCall![0]).toMatchObject({+ role: 'assistant',+ threadId: 'thread-123',+ topicId: 'topic-1',+ });+ });+ });++ describe('when threadId is not provided in appContext', () => {+ it('should create user message without threadId', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ topicId: 'topic-1',+ },+ prompt: 'Test prompt',+ });++ // Find the user message creation call+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');++ expect(userMessageCall).toBeDefined();+ expect(userMessageCall![0].threadId).toBeUndefined();+ });++ it('should create assistant message without threadId', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ topicId: 'topic-1',+ },+ prompt: 'Test prompt',+ });++ // Find the assistant message creation call+ const assistantMessageCall = mockMessageCreate.mock.calls.find(+ (call) => call[0].role === 'assistant',+ );++ expect(assistantMessageCall).toBeDefined();+ expect(assistantMessageCall![0].threadId).toBeUndefined();+ });+ });++ describe('when appContext is undefined', () => {+ it('should create messages without threadId', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Test prompt',+ });++ // Check all message creation calls+ for (const call of mockMessageCreate.mock.calls) {+ expect(call[0].threadId).toBeUndefined();+ }+ });+ });++ describe('SubAgent task scenario', () => {+ it('should ensure messages are isolated in Thread context', async () => {+ const threadId = 'isolated-thread-456';++ await service.execAgent({+ agentId: 'agent-1',+ appContext: {+ groupId: 'group-1',+ threadId,+ topicId: 'topic-1',+ },+ prompt: 'SubAgent task instruction',+ });++ // Verify both user and assistant messages have the correct threadId+ const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');+ const assistantMessageCall = mockMessageCreate.mock.calls.find(+ (call) => call[0].role === 'assistant',+ );++ expect(userMessageCall![0].threadId).toBe(threadId);+ expect(assistantMessageCall![0].threadId).toBe(threadId);++ // Verify groupId is passed to AgentRuntimeService (checked in appContext)+ // This is handled by the createOperation call+ });+ });+});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 5aa9ff2e7ca..3ab59f9a02a 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -195,15 +195,18 @@ export class AiAgentService {}// 7. Create user message in database+ // Include threadId if provided (for SubAgent task execution in isolated Thread)const userMessageRecord = await this.messageModel.create({agentId: resolvedAgentId,content: prompt,role: 'user',+ threadId: appContext?.threadId ?? undefined,topicId,});log('execAgent: created user message %s', userMessageRecord.id);// 8. Create assistant message placeholder in database+ // Include threadId if provided (for SubAgent task execution in isolated Thread)const assistantMessageRecord = await this.messageModel.create({agentId: resolvedAgentId,content: LOADING_FLAT,@@ -211,6 +214,7 @@ export class AiAgentService {parentId: userMessageRecord.id,provider,role: 'assistant',+ threadId: appContext?.threadId ?? undefined,topicId,});log('execAgent: created assistant message %s', assistantMessageRecord.id);diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex dd4d3111fb1..bf7cf149749 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -941,11 +941,6 @@ export const streamingExecutor: StateCreator<// Create a new array to avoid modifying the original messageslet messages = [...originalMessages];- console.log('[internal_execAgentRuntime] Context scope:', {- scope: context.scope,- agentId: effectiveAgentId,- });-// Use effectiveAgentId to get agent config (subAgentId in group orchestration, agentId otherwise)// resolveAgentConfig handles:// - Builtin agent runtime config merging