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.

♻️ refactor: remove group orchestration task messages (#16931)

Arvin Xuc50b672999cc
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 9361319f3d9..73dadd742b1 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -17,6 +17,7 @@
"agentGroupManagement.executeTask.tokens": "Token Usage",
"agentGroupManagement.executeTasks.intervention.instructionPlaceholder": "Detailed instruction for the agent to perform this task...",
"agentGroupManagement.executeTasks.intervention.titlePlaceholder": "Task title...",
+ "agentGroupManagement.executeTasks.results": "Results",
"agentMarketplace.category.businessStrategy": "Business & Strategy",
"agentMarketplace.category.contentCreation": "Content Creation",
"agentMarketplace.category.creatorEconomy": "Creator Economy",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index aa818de2546..f1541f86908 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -17,6 +17,7 @@
"agentGroupManagement.executeTask.tokens": "令牌使用量",
"agentGroupManagement.executeTasks.intervention.instructionPlaceholder": "为代理执行此任务提供详细说明……",
"agentGroupManagement.executeTasks.intervention.titlePlaceholder": "任务标题……",
+ "agentGroupManagement.executeTasks.results": "执行结果",
"agentMarketplace.category.businessStrategy": "商业与战略",
"agentMarketplace.category.contentCreation": "内容创作",
"agentMarketplace.category.creatorEconomy": "创作者经济",
diff --git a/packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx b/packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx
index 3f39ba2e4c2..5a69dbcbe60 100644
--- a/packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx
+++ b/packages/builtin-tool-group-management/src/client/Render/ExecuteTasks/index.tsx
@@ -2,9 +2,10 @@
import { DEFAULT_AVATAR } from '@lobechat/const';
import type { AgentGroupMember, BuiltinRenderProps } from '@lobechat/types';
-import { Accordion, AccordionItem, Avatar, Block, Flexbox, Text } from '@lobehub/ui';
+import { Accordion, AccordionItem, Avatar, Block, Flexbox, Markdown, Text } from '@lobehub/ui';
import { createStaticStyles, useTheme } from 'antd-style';
import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import { useAgentGroupStore } from '@/store/agentGroup';
import { agentGroupSelectors } from '@/store/agentGroup/selectors';
@@ -37,6 +38,14 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
line-height: 1.6;
color: ${cssVar.colorTextSecondary};
`,
+ resultBox: css`
+ overflow: hidden;
+ `,
+ resultLabel: css`
+ padding-inline: 4px;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
taskTitle: css`
overflow: hidden;
@@ -50,65 +59,87 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
* ExecuteTasks Render component for Group Management tool
* Accordion-style task list with expandable instruction and assignee on the right
*/
-const ExecuteTasksRender = memo<BuiltinRenderProps<ExecuteTasksParams>>(({ args }) => {
- const theme = useTheme();
- const { tasks } = args || {};
+const ExecuteTasksRender = memo<BuiltinRenderProps<ExecuteTasksParams, unknown, string>>(
+ ({ args, content }) => {
+ const { t } = useTranslation('tool');
+ const theme = useTheme();
+ const { tasks } = args || {};
+ const resultContent = typeof content === 'string' ? content.trim() : '';
+
+ // Get active group ID and agents from store
+ const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
+ const groupAgents = useAgentGroupStore((s) =>
+ activeGroupId ? agentGroupSelectors.getGroupAgents(activeGroupId)(s) : [],
+ );
- // Get active group ID and agents from store
- const activeGroupId = useAgentGroupStore(agentGroupSelectors.activeGroupId);
- const groupAgents = useAgentGroupStore((s) =>
- activeGroupId ? agentGroupSelectors.getGroupAgents(activeGroupId)(s) : [],
- );
+ // Get agent details for each task
+ const tasksWithAgents = useMemo(() => {
+ if (!tasks?.length) return [];
+ return tasks.map((task) => ({
+ ...task,
+ agent: groupAgents.find((agent) => agent.id === task.agentId) as
+ AgentGroupMember | undefined,
+ }));
+ }, [tasks, groupAgents]);
- // Get agent details for each task
- const tasksWithAgents = useMemo(() => {
- if (!tasks?.length || !groupAgents.length) return [];
- return tasks.map((task) => ({
- ...task,
- agent: groupAgents.find((agent) => agent.id === task.agentId) as AgentGroupMember | undefined,
- }));
- }, [tasks, groupAgents]);
+ if (!tasksWithAgents.length && !resultContent) return null;
- if (!tasksWithAgents.length) return null;
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ {!!tasksWithAgents.length && (
+ <Accordion defaultExpandedKeys={[]} gap={0} variant={'borderless'}>
+ {tasksWithAgents.map((task, index) => (
+ <AccordionItem
+ itemKey={task.agentId || String(index)}
+ key={task.agentId || index}
+ paddingBlock={8}
+ paddingInline={4}
+ action={
+ <div className={styles.assignee}>
+ <Avatar
+ avatar={task.agent?.avatar || DEFAULT_AVATAR}
+ background={task.agent?.backgroundColor || theme.colorBgContainer}
+ shape={'circle'}
+ size={20}
+ />
+ <span>{task.agent?.title}</span>
+ </div>
+ }
+ title={
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <span className={styles.index}>{index + 1}.</span>
+ <Text className={styles.taskTitle} weight={500}>
+ {task.title || 'Task'}
+ </Text>
+ </Flexbox>
+ }
+ >
+ {task.instruction && (
+ <Block padding={12} style={{ marginTop: 8 }} variant={'filled'}>
+ <Text className={styles.instruction}>{task.instruction}</Text>
+ </Block>
+ )}
+ </AccordionItem>
+ ))}
+ </Accordion>
+ )}
- return (
- <Accordion className={styles.container} defaultExpandedKeys={[]} gap={0} variant={'borderless'}>
- {tasksWithAgents.map((task, index) => (
- <AccordionItem
- itemKey={task.agentId || String(index)}
- key={task.agentId || index}
- paddingBlock={8}
- paddingInline={4}
- action={
- <div className={styles.assignee}>
- <Avatar
- avatar={task.agent?.avatar || DEFAULT_AVATAR}
- background={task.agent?.backgroundColor || theme.colorBgContainer}
- shape={'circle'}
- size={20}
- />
- <span>{task.agent?.title}</span>
- </div>
- }
- title={
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <span className={styles.index}>{index + 1}.</span>
- <Text className={styles.taskTitle} weight={500}>
- {task.title || 'Task'}
- </Text>
- </Flexbox>
- }
- >
- {task.instruction && (
- <Block padding={12} style={{ marginTop: 8 }} variant={'filled'}>
- <Text className={styles.instruction}>{task.instruction}</Text>
+ {resultContent && (
+ <Flexbox gap={4}>
+ <Text className={styles.resultLabel}>
+ {t('agentGroupManagement.executeTasks.results')}
+ </Text>
+ <Block className={styles.resultBox} padding={12} variant={'filled'}>
+ <Markdown style={{ maxHeight: 320, overflow: 'auto' }} variant={'chat'}>
+ {resultContent}
+ </Markdown>
</Block>
- )}
- </AccordionItem>
- ))}
- </Accordion>
- );
-});
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
ExecuteTasksRender.displayName = 'ExecuteTasksRender';
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index ca1fe136e57..a8e02319395 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -19,6 +19,7 @@ export default {
'agentGroupManagement.executeTasks.intervention.instructionPlaceholder':
'Detailed instruction for the agent to perform this task...',
'agentGroupManagement.executeTasks.intervention.titlePlaceholder': 'Task title...',
+ 'agentGroupManagement.executeTasks.results': 'Results',
'agentMarketplace.category.businessStrategy': 'Business & Strategy',
'agentMarketplace.category.contentCreation': 'Content Creation',
'agentMarketplace.category.creatorEconomy': 'Creator Economy',
diff --git a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
index c5a4b04053e..cfb7dd782d6 100644
--- a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
+++ b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
@@ -155,7 +155,7 @@ describe('createGroupOrchestrationExecutors', () => {
expect((result.result?.payload as any).results[0].error).toBe('No valid context available');
});
- it('should create task messages for all tasks in parallel', async () => {
+ it('should reuse the source tool message for all tasks', async () => {
const mockStore = createMockStore();
// Mock execSubAgentTask to return success
@@ -197,44 +197,46 @@ describe('createGroupOrchestrationExecutors', () => {
createInitialState(),
);
- // Should create 2 task messages
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledTimes(2);
+ expect(mockStore.optimisticCreateMessage).not.toHaveBeenCalled();
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledTimes(2);
- // Verify first task message creation
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledWith(
expect.objectContaining({
agentId: TEST_IDS.AGENT_1_ID,
groupId: TEST_IDS.GROUP_ID,
- metadata: { instruction: 'Task 1', taskTitle: 'Task 1 Title' },
- parentId: TEST_IDS.TOOL_MESSAGE_ID,
- role: 'task',
+ instruction: 'Task 1',
+ parentMessageId: TEST_IDS.TOOL_MESSAGE_ID,
+ title: 'Task 1 Title',
topicId: TEST_IDS.TOPIC_ID,
}),
- expect.objectContaining({ operationId: TEST_IDS.OPERATION_ID }),
);
- // Verify second task message creation
- expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(
+ expect(aiAgentService.execSubAgentTask).toHaveBeenCalledWith(
expect.objectContaining({
agentId: TEST_IDS.AGENT_2_ID,
groupId: TEST_IDS.GROUP_ID,
- metadata: { instruction: 'Task 2', taskTitle: 'Task 2 Title' },
- parentId: TEST_IDS.TOOL_MESSAGE_ID,
- role: 'task',
+ instruction: 'Task 2',
+ parentMessageId: TEST_IDS.TOOL_MESSAGE_ID,
+ title: 'Task 2 Title',
topicId: TEST_IDS.TOPIC_ID,
}),
+ );
+
+ const updateContent = vi
+ .mocked(mockStore.optimisticUpdateMessageContent)
+ .mock.calls.at(-1)?.[1];
+ expect(updateContent).toContain('1. Task 1 Title\nTask completed');
+ expect(updateContent).toContain('2. Task 2 Title\nTask completed');
+ expect(mockStore.optimisticUpdateMessageContent).toHaveBeenCalledWith(
+ TEST_IDS.TOOL_MESSAGE_ID,
+ expect.any(String),
+ undefined,
expect.objectContaining({ operationId: TEST_IDS.OPERATION_ID }),
);
});
it('should call execSubAgentTask for each task', async () => {
const mockStore = createMockStore();
- let messageIdCounter = 0;
-
- vi.mocked(mockStore.optimisticCreateMessage).mockImplementation(async () => ({
- id: `msg_${++messageIdCounter}`,
- messages: [],
- }));
vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValue(
createMockExecResult({ threadId: 'thread-1' }),
@@ -281,6 +283,7 @@ describe('createGroupOrchestrationExecutors', () => {
agentId: TEST_IDS.AGENT_1_ID,
groupId: TEST_IDS.GROUP_ID,
instruction: 'Task 1',
+ parentMessageId: TEST_IDS.TOOL_MESSAGE_ID,
title: 'Task 1 Title',
topicId: TEST_IDS.TOPIC_ID,
}),
@@ -291,6 +294,7 @@ describe('createGroupOrchestrationExecutors', () => {
agentId: TEST_IDS.AGENT_2_ID,
groupId: TEST_IDS.GROUP_ID,
instruction: 'Task 2',
+ parentMessageId: TEST_IDS.TOOL_MESSAGE_ID,
title: 'Task 2 Title',
topicId: TEST_IDS.TOPIC_ID,
}),
@@ -351,65 +355,6 @@ describe('createGroupOrchestrationExecutors', () => {
});
});
- it('should handle task creation failure', async () => {
- const mockStore = createMockStore();
-
- // First task message creation fails
- vi.mocked(mockStore.optimisticCreateMessage)
- .mockResolvedValueOnce(undefined) // First task fails
- .mockResolvedValueOnce({ id: 'msg_2', messages: [] }); // Second task succeeds
-
- vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValue(
- createMockExecResult({ threadId: 'thread-2' }),
- );
-
- vi.mocked(aiAgentService.getSubAgentTaskStatus).mockResolvedValue({
- result: 'Task completed',
- status: 'completed',
- });
-
- const executors = createGroupOrchestrationExecutors({
- get: () => mockStore,
- messageContext: {
- agentId: TEST_IDS.GROUP_ID,
- groupId: TEST_IDS.GROUP_ID,
- scope: 'group',
- topicId: TEST_IDS.TOPIC_ID,
- },
- orchestrationOperationId: TEST_IDS.ORCHESTRATION_OPERATION_ID,
- supervisorAgentId: TEST_IDS.SUPERVISOR_AGENT_ID,
- });
-
- const batchExecTasksExecutor = executors.batch_exec_async_tasks!;
-
- const result = await batchExecTasksExecutor(
- {
- payload: {
- tasks: [
- { agentId: TEST_IDS.AGENT_1_ID, instruction: 'Task 1', title: 'Task 1 Title' },
- { agentId: TEST_IDS.AGENT_2_ID, instruction: 'Task 2', title: 'Task 2 Title' },
- ],
- toolMessageId: TEST_IDS.TOOL_MESSAGE_ID,
- },
- type: 'batch_exec_async_tasks',
- },
- createInitialState(),
- );
-
- expect(result.result?.type).toBe('tasks_completed');
- // First task should fail due to message creation failure
- expect((result.result?.payload as any).results[0]).toMatchObject({
- agentId: TEST_IDS.AGENT_1_ID,
- error: 'Failed to create task message',
- success: false,
- });
- // Second task should succeed
- expect((result.result?.payload as any).results[1]).toMatchObject({
- agentId: TEST_IDS.AGENT_2_ID,
- success: true,
- });
- });
-
it('should handle execSubAgentTask failure', async () => {
const mockStore = createMockStore();
@@ -564,12 +509,6 @@ describe('createGroupOrchestrationExecutors', () => {
it('should dispatch taskDetail update when task status includes taskDetail', async () => {
const mockStore = createMockStore();
- const messageId = 'msg_1';
-
- vi.mocked(mockStore.optimisticCreateMessage).mockResolvedValue({
- id: messageId,
- messages: [],
- });
vi.mocked(aiAgentService.execSubAgentTask).mockResolvedValue(
createMockExecResult({ threadId: 'thread-1' }),
@@ -615,7 +554,7 @@ describe('createGroupOrchestrationExecutors', () => {
// Should dispatch message update with taskDetail
expect(mockStore.internal_dispatchMessage).toHaveBeenCalledWith(
expect.objectContaining({
- id: messageId,
+ id: TEST_IDS.TOOL_MESSAGE_ID,
type: 'updateMessage',
value: { taskDetail },
}),
diff --git a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
index 8ec7f3b83ac..158bf733537 100644
--- a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
+++ b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
@@ -26,6 +26,38 @@ const sleep = (ms: number) =>
setTimeout(resolve, ms);
});
+interface GroupAsyncTaskResultContentItem {
+ agentId: string;
+ error?: string;
+ result?: string;
+ success: boolean;
+ title?: string;
+}
+
+const formatGroupAsyncTaskResultContent = (items: GroupAsyncTaskResultContentItem[]) =>
+ items
+ .map((item, index) => {
+ const title = item.title ?? item.agentId;
+ const content = item.success
+ ? (item.result ?? 'Completed successfully.')
+ : `Failed: ${item.error ?? 'Unknown error'}`;
+
+ return `${index + 1}. ${title}\n${content}`;
+ })
+ .join('\n\n');
+
+const toGroupAsyncTaskResultPayload = ({
+ agentId,
+ error,
+ result,
+ success,
+}: GroupAsyncTaskResultContentItem) => ({
+ agentId,
+ ...(error === undefined ? {} : { error }),
+ ...(result === undefined ? {} : { result }),
+ success,
+});
+
export interface GroupOrchestrationExecutorsContext {
get: () => ChatStore;
/**
@@ -360,10 +392,9 @@ export const createGroupOrchestrationExecutors = (
* Executes an async task for an agent using aiAgentService with polling (server-side)
*
* Flow:
- * 1. Create a task message (role: 'task') as placeholder
- * 2. Call execGroupSubAgentTask API (backend creates thread with sourceMessageId)
- * 3. Poll for task completion
- * 4. Update task message content with summary on completion
+ * 1. Call execGroupSubAgentTask API (backend creates thread with sourceMessageId)
+ * 2. Poll for task completion
+ * 3. Update the source tool message with summary on completion
*
* Returns: task_completed result
*/
@@ -395,50 +426,22 @@ export const createGroupOrchestrationExecutors = (
}
try {
- // 1. Create task message as placeholder
- const taskMessageResult = await get().optimisticCreateMessage(
- {
- agentId,
- content: '',
- groupId,
- metadata: { instruction, taskTitle: title },
- parentId: toolMessageId,
- role: 'task',
- topicId,
- },
- { operationId: state.operationId },
- );
-
- if (!taskMessageResult) {
- console.error(`[${sessionLogId}] Failed to create task message`);
- return {
- events: [] as GroupOrchestrationEvent[],
- newState: state,
- result: {
- payload: { agentId, error: 'Failed to create task message', success: false },
- type: 'task_completed',
- },
- };
- }
+ const resultMessageId = toolMessageId;
- const taskMessageId = taskMessageResult.id;
- log(`[${sessionLogId}] Created task message: ${taskMessageId}`);
-
- // 2. Create task via backend API (backend creates thread with sourceMessageId)
+ // 1. Create task via backend API (backend creates thread with sourceMessageId)
const createResult = await aiAgentService.execSubAgentTask({
agentId,
groupId,
instruction,
- parentMessageId: taskMessageId,
+ parentMessageId: resultMessageId,
title,
topicId,
});
if (!createResult.success) {
log(`[${sessionLogId}] Failed to create task: ${createResult.error}`);
- // Update task message with error
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
`Task creation failed: ${createResult.error}`,
undefined,
{ operationId: state.operationId },
@@ -455,7 +458,7 @@ export const createGroupOrchestrationExecutors = (
log(`[${sessionLogId}] Task created with threadId: ${createResult.threadId}`);
- // 3. Poll for task completion
+ // 2. Poll for task completion
const pollInterval = 3000; // 3 seconds
const maxWait = timeout || 1_800_000; // Default 30 minutes
const startTime = Date.now();
@@ -479,26 +482,31 @@ export const createGroupOrchestrationExecutors = (
threadId: createResult.threadId,
});
- // Update taskDetail in message if available
+ // Update taskDetail on the source tool message if available.
if (status.taskDetail) {
get().internal_dispatchMessage(
{
- id: taskMessageId,
+ id: resultMessageId,
type: 'updateMessage',
value: { taskDetail: status.taskDetail },
},
{ operationId: state.operationId },
);
- log(`[${sessionLogId}] Updated task message with taskDetail`);
+ log(`[${sessionLogId}] Updated source tool message with taskDetail`);
}
if (status.status === 'completed') {
log(`[${sessionLogId}] Task completed successfully`);
- // 4. Update task message with summary
+ // 3. Update the source tool message with summary.
if (status.result) {
- await get().optimisticUpdateMessageContent(taskMessageId, status.result, undefined, {
- operationId: state.operationId,
- });
+ await get().optimisticUpdateMessageContent(
+ resultMessageId,
+ status.result,
+ undefined,
+ {
+ operationId: state.operationId,
+ },
+ );
}
return {
events: [] as GroupOrchestrationEvent[],
@@ -512,9 +520,8 @@ export const createGroupOrchestrationExecutors = (
if (status.status === 'failed') {
console.error(`[${sessionLogId}] Task failed: ${status.error}`);
- // Update task message with error
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
`Task failed: ${status.error}`,
undefined,
{ operationId: state.operationId },
@@ -531,9 +538,8 @@ export const createGroupOrchestrationExecutors = (
if (status.status === 'cancel') {
log(`[${sessionLogId}] Task was cancelled`);
- // Update task message with cancelled status
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
'Task was cancelled',
undefined,
{ operationId: state.operationId },
@@ -554,9 +560,8 @@ export const createGroupOrchestrationExecutors = (
// Timeout reached
log(`[${sessionLogId}] Task timeout after ${maxWait}ms`);
- // Update task message with timeout error
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
`Task timeout after ${maxWait}ms`,
undefined,
{ operationId: state.operationId },
@@ -593,11 +598,10 @@ export const createGroupOrchestrationExecutors = (
* Used when task requires local tools like file system or shell commands
*
* Flow:
- * 1. Create a task message (role: 'task') as placeholder
- * 2. Create Thread via API (to get threadId for operation context)
- * 3. Execute using executeClientAgent (client-side with local tools access)
- * 4. Update Thread status via API on completion
- * 5. Update task message content with result
+ * 1. Create Thread via API (to get threadId for operation context)
+ * 2. Execute using executeClientAgent (client-side with local tools access)
+ * 3. Update Thread status via API on completion
+ * 4. Update the source tool message with result
*
* Returns: task_completed result
*/
@@ -627,41 +631,14 @@ export const createGroupOrchestrationExecutors = (
}
try {
- // 1. Create task message as placeholder
- const taskMessageResult = await get().optimisticCreateMessage(
- {
- agentId,
- content: '',
- groupId,
- metadata: { instruction, taskTitle: title },
- parentId: toolMessageId,
- role: 'task',
- topicId,
- },
- { operationId: state.operationId },
- );
-
- if (!taskMessageResult) {
- console.error(`[${sessionLogId}] Failed to create task message`);
- return {
- events: [] as GroupOrchestrationEvent[],
- newState: state,
- result: {
- payload: { agentId, error: 'Failed to create task message', success: false },
- type: 'task_completed',
- },
- };
- }
+ const resultMessageId = toolMessageId;
- const taskMessageId = taskMessageResult.id;
- log(`[${sessionLogId}] Created task message: ${taskMessageId}`);
-
- // 2. Create Thread via API first (to get threadId for operation context)
+ // 1. Create Thread via API first (to get threadId for operation context)
// Use Group-specific API that handles different agentIds in thread context
const threadResult = await aiAgentService.createClientGroupAgentTaskThread({
groupId: groupId!,
instruction,
- parentMessageId: taskMessageId,
+ parentMessageId: resultMessageId,
subAgentId: agentId,
title,
topicId,
@@ -670,7 +647,7 @@ export const createGroupOrchestrationExecutors = (
if (!threadResult.success) {
log(`[${sessionLogId}] Failed to create client task thread`);
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
'Failed to create task thread',
undefined,
{ operationId: state.operationId },
@@ -708,7 +685,7 @@ export const createGroupOrchestrationExecutors = (
metadata: {
startTime: Date.now(),
taskDescription: title,
- taskMessageId,
+ sourceMessageId: resultMessageId,
executionMode: 'client',
},
});
@@ -749,7 +726,7 @@ export const createGroupOrchestrationExecutors = (
log(`[${sessionLogId}] Client-side AgentRuntime execution completed`);
- // 7. Get execution result from sub-task messages
+ // 7. Get execution result from the isolated thread messages
const subMessageKey = messageMapKey(subContext);
const subTaskMessages = get().dbMessagesMap[subMessageKey] || [];
const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');
@@ -763,9 +740,9 @@ export const createGroupOrchestrationExecutors = (
// Get usage data from runtime result
const { usage, cost } = runtimeResult || {};
- // 8. Update task message with result
+ // 8. Update the source tool message with result
await get().optimisticUpdateMessageContent(
- taskMessageId,
+ resultMessageId,
resultContent,
{
metadata: {
@@ -825,10 +802,9 @@ export const createGroupOrchestrationExecutors = (
* Executes multiple async tasks for agents in parallel using aiAgentService with polling
*
* Flow:
- * 1. Create task messages (role: 'task') for each task as placeholders
- * 2. Call execSubAgentTask API for each task in parallel
- * 3. Poll for all tasks completion
- * 4. Update task messages with results on completion
+ * 1. Call execSubAgentTask API for each task in parallel
+ * 2. Poll for all tasks completion
+ * 3. Update the source tool message once with aggregated results
*
* Returns: tasks_completed result
*/
@@ -862,14 +838,13 @@ export const createGroupOrchestrationExecutors = (
};
}
- // Track all tasks with their messages and thread IDs
+ // Track all tasks with their thread IDs
interface TaskTracker {
agentId: string;
error?: string;
instruction: string;
result?: string;
status: 'pending' | 'running' | 'completed' | 'failed';
- taskMessageId?: string;
threadId?: string;
timeout: number;
title?: string;
@@ -883,45 +858,32 @@ export const createGroupOrchestrationExecutors = (
title: t.title,
}));
- // 1. Create task messages for all tasks in parallel
- await Promise.all(
- taskTrackers.map(async (tracker, index) => {
- const taskLogId = `${sessionLogId}:task-${index}`;
- try {
- const taskMessageResult = await get().optimisticCreateMessage(
- {
- agentId: tracker.agentId,
- content: '',
- createdAt: Date.now() + index,
- groupId,
- metadata: { instruction: tracker.instruction, taskTitle: tracker.title },
- parentId: toolMessageId,
- role: 'task',
- topicId,
- },
- { operationId: state.operationId },
- );
+ const toTaskResults = (runningError?: string): GroupAsyncTaskResultContentItem[] =>
+ taskTrackers.map((tracker) => {
+ const error = tracker.status === 'running' ? runningError : tracker.error;
- if (taskMessageResult) {
- tracker.taskMessageId = taskMessageResult.id;
- log(`[${taskLogId}] Created task message: ${tracker.taskMessageId}`);
- } else {
- tracker.status = 'failed';
- tracker.error = 'Failed to create task message';
- console.error(`[${taskLogId}] Failed to create task message`);
- }
- } catch (error) {
- tracker.status = 'failed';
- tracker.error = error instanceof Error ? error.message : 'Unknown error';
- console.error(`[${taskLogId}] Error creating task message: ${error}`);
- }
- }),
- );
+ return {
+ agentId: tracker.agentId,
+ ...(error === undefined ? {} : { error }),
+ ...(tracker.result === undefined ? {} : { result: tracker.result }),
+ success: tracker.status === 'completed',
+ ...(tracker.title === undefined ? {} : { title: tracker.title }),
+ };
+ });
- // 2. Start all tasks in parallel via backend API
+ const updateBatchResultMessage = async (items: GroupAsyncTaskResultContentItem[]) => {
+ await get().optimisticUpdateMessageContent(
+ toolMessageId,
+ formatGroupAsyncTaskResultContent(items),
+ undefined,
+ { operationId: state.operationId },
+ );
+ };
+
+ // 1. Start all tasks in parallel via backend API
await Promise.all(
taskTrackers.map(async (tracker, index) => {
- if (tracker.status === 'failed' || !tracker.taskMessageId) return;
+ if (tracker.status === 'failed') return;
const taskLogId = `${sessionLogId}:task-${index}`;
try {
@@ -929,7 +891,7 @@ export const createGroupOrchestrationExecutors = (
agentId: tracker.agentId,
groupId,
instruction: tracker.instruction,
- parentMessageId: tracker.taskMessageId,
+ parentMessageId: toolMessageId,
title: tracker.title,
topicId,
});
@@ -942,13 +904,6 @@ export const createGroupOrchestrationExecutors = (
tracker.status = 'failed';
tracker.error = createResult.error;
log(`[${taskLogId}] Failed to start task: ${createResult.error}`);
- // Update task message with error
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- `Task creation failed: ${createResult.error}`,
- undefined,
- { operationId: state.operationId },
- );
}
} catch (error) {
tracker.status = 'failed';
@@ -958,7 +913,7 @@ export const createGroupOrchestrationExecutors = (
}),
);
- // 3. Poll for all tasks completion
+ // 2. Poll for all tasks completion
const pollInterval = 3000; // 3 seconds
const startTime = Date.now();
const maxTimeout = Math.max(...taskTrackers.map((t) => t.timeout));
@@ -968,17 +923,15 @@ export const createGroupOrchestrationExecutors = (
const currentOperation = get().operations[state.operationId];
if (currentOperation?.status === 'cancelled') {
console.warn(`[${sessionLogId}] Operation cancelled, stopping polling`);
+ const results = toTaskResults('Operation cancelled');
+ await updateBatchResultMessage(results);
+
return {
events: [] as GroupOrchestrationEvent[],
newState: { ...state, status: 'done' },
result: {
payload: {
- results: taskTrackers.map((t) => ({
- agentId: t.agentId,
- error: t.status === 'running' ? 'Operation cancelled' : t.error,
- result: t.result,
- success: t.status === 'completed',
- })),
+ results: results.map(toGroupAsyncTaskResultPayload),
},
type: 'tasks_completed',
},
@@ -994,7 +947,7 @@ export const createGroupOrchestrationExecutors = (
await Promise.all(
runningTasks.map(async (tracker, index) => {
- if (!tracker.threadId || !tracker.taskMessageId) return;
+ if (!tracker.threadId) return;
const taskLogId = `${sessionLogId}:task-${index}`;
try {
@@ -1002,11 +955,11 @@ export const createGroupOrchestrationExecutors = (
threadId: tracker.threadId,
});
- // Update taskDetail in message if available
+ // Update taskDetail on the source tool message if available.
if (status.taskDetail) {
get().internal_dispatchMessage(
{
- id: tracker.taskMessageId,
+ id: toolMessageId,
type: 'updateMessage',
value: { taskDetail: status.taskDetail },
},
@@ -1019,14 +972,6 @@ export const createGroupOrchestrationExecutors = (
tracker.status = 'completed';
tracker.result = status.result;
log(`[${taskLogId}] Task completed successfully`);
- if (status.result) {
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- status.result,
- undefined,
- { operationId: state.operationId },
- );
- }
break;
}
@@ -1034,12 +979,6 @@ export const createGroupOrchestrationExecutors = (
tracker.status = 'failed';
tracker.error = status.error;
console.error(`[${taskLogId}] Task failed: ${status.error}`);
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- `Task failed: ${status.error}`,
- undefined,
- { operationId: state.operationId },
- );
break;
}
@@ -1047,12 +986,6 @@ export const createGroupOrchestrationExecutors = (
tracker.status = 'failed';
tracker.error = 'Task was cancelled';
log(`[${taskLogId}] Task was cancelled`);
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- 'Task was cancelled',
- undefined,
- { operationId: state.operationId },
- );
break;
}
@@ -1064,12 +997,6 @@ export const createGroupOrchestrationExecutors = (
tracker.status = 'failed';
tracker.error = `Task timeout after ${tracker.timeout}ms`;
log(`[${taskLogId}] Task timeout`);
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- `Task timeout after ${tracker.timeout}ms`,
- undefined,
- { operationId: state.operationId },
- );
}
} catch (error) {
console.error(`[${taskLogId}] Error polling task status: ${error}`);
@@ -1083,31 +1010,22 @@ export const createGroupOrchestrationExecutors = (
// Mark any remaining running tasks as timed out
for (const tracker of taskTrackers) {
- if (tracker.status === 'running' && tracker.taskMessageId) {
+ if (tracker.status === 'running') {
tracker.status = 'failed';
tracker.error = `Task timeout after ${tracker.timeout}ms`;
- await get().optimisticUpdateMessageContent(
- tracker.taskMessageId,
- `Task timeout after ${tracker.timeout}ms`,
- undefined,
- { operationId: state.operationId },
- );
}
}
log(`[${sessionLogId}] All tasks completed`);
+ const results = toTaskResults();
+ await updateBatchResultMessage(results);
return {
events: [] as GroupOrchestrationEvent[],
newState: state,
result: {
payload: {
- results: taskTrackers.map((t) => ({
- agentId: t.agentId,
- error: t.error,
- result: t.result,
- success: t.status === 'completed',
- })),
+ results: results.map(toGroupAsyncTaskResultPayload),
},
type: 'tasks_completed',
},