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.

✨ feat(chat): forward topics and messages to agents (#17039)

Arvin Xu3ebd73acf47a
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index ac39e7cb1db..0c3b6218533 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -373,6 +373,21 @@ Re-tested end-to-end against the running dev server. The previous claim ("blocks
## C. Probing app / store runtime state
+### C0. A picker backed by a list store may need fixture hydration after direct-route entry
+
+- **Situation**: a modal reads candidate entities from a list store, while the test enters a
+ detail route directly. The detail route can render from its own entity/config store without
+ ever mounting the list fetcher, so the picker correctly renders an empty candidate list even
+ though fixture rows exist in the database.
+- **Doesn't work**: inserting database rows alone, or refreshing the detail store. Neither
+ hydrates a separate list store that has not mounted its fetch hook.
+- **Works**: first enter the canonical list/home surface and let its real fetch settle. If the
+ fixture deliberately bypasses normal creation and the list API still does not expose it,
+ use the existing C1b dev-only `setState` exposer to hydrate the list store with the exact
+ fixture shape, then exercise the real picker component and remove the exposer patch after
+ capture. Keep the report explicit that fixture hydration was test setup; validate the actual
+ mutation and created entity through the database or network boundary.
+
### C1. `window.__LOBE_STORES.<name>` has no `.getState` — CALL it instead
- **Doesn't work**: `window.__LOBE_STORES.page.getState()`. The exposed value is neither the
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 12d80563232..c98cfad3be9 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -499,6 +499,7 @@
"messageForward.deleteConfirm.success": "Deleted {{count}} messages",
"messageForward.deleteConfirm.title": "Delete messages",
"messageForward.empty": "Select at least one message to forward",
+ "messageForward.failed": "Some messages could not be forwarded",
"messageForward.modal.empty": "No other agents available",
"messageForward.modal.moreMessages": "+{{count}} more messages",
"messageForward.modal.noRecipients": "Pick agents on the left to forward to",
@@ -513,6 +514,11 @@
"messageForward.role.user": "User",
"messageForward.success": "Forwarded to {{title}}",
"messageForward.successMulti": "Forwarded to {{count}} agents",
+ "messageForward.topic.context": "Topic context",
+ "messageForward.topic.description": "The user and assistant messages in this topic will be sent as context. Tool messages are excluded.",
+ "messageForward.topic.header": "The following topic was forwarded from another conversation. Please use it as context and continue:",
+ "messageForward.topic.loadFailed": "Could not load this topic for forwarding",
+ "messageForward.topic.modalTitle": "Forward topic to Agent",
"messageForward.transcript.header": "The following {{count}} messages were forwarded from another conversation. Please use them as context and continue:",
"messageLink.openInSideBrowser": "Open in side browser",
"messageLongCollapse.collapse": "Show less",
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 594aac12e44..69bc8e46ca3 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -20,6 +20,7 @@
"actions.duplicate": "Duplicate",
"actions.export": "Export Topics",
"actions.favorite": "Favorite",
+ "actions.forwardToAgent": "Forward to another agent",
"actions.import": "Import Topics",
"actions.markCompleted": "Archive",
"actions.moveToAgent": "Move to another agent",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 9ad96d3652e..45e31372061 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -499,6 +499,7 @@
"messageForward.deleteConfirm.success": "已删除 {{count}} 条消息",
"messageForward.deleteConfirm.title": "删除消息",
"messageForward.empty": "请至少选择一条消息进行转发",
+ "messageForward.failed": "部分消息转发失败",
"messageForward.modal.empty": "没有可转发的其他智能体",
"messageForward.modal.moreMessages": "还有 +{{count}} 条消息",
"messageForward.modal.noRecipients": "从左侧选择要转发到的智能体",
@@ -513,6 +514,11 @@
"messageForward.role.user": "用户",
"messageForward.success": "已转发给 {{title}}",
"messageForward.successMulti": "已转发给 {{count}} 个智能体",
+ "messageForward.topic.context": "话题上下文",
+ "messageForward.topic.description": "该话题中的用户和助手消息将作为上下文发送,工具消息不会被转发。",
+ "messageForward.topic.header": "以下话题转发自另一段对话,请将其作为上下文并继续处理:",
+ "messageForward.topic.loadFailed": "无法加载该话题进行转发",
+ "messageForward.topic.modalTitle": "转发话题给助手",
"messageForward.transcript.header": "以下 {{count}} 条消息转发自另一段对话,请将其作为上下文并继续处理:",
"messageLink.openInSideBrowser": "在侧边浏览器中打开",
"messageLongCollapse.collapse": "收起",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index cb878e7755c..b9d62ba5556 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -20,6 +20,7 @@
"actions.duplicate": "复制",
"actions.export": "导出话题",
"actions.favorite": "收藏",
+ "actions.forwardToAgent": "转发给其他助手",
"actions.import": "导入对话",
"actions.markCompleted": "归档",
"actions.moveToAgent": "移动到其他助手",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 865dca2b0a1..581f4f7cb8e 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -484,6 +484,7 @@ export default {
'messageForward.deleteConfirm.success': 'Deleted {{count}} messages',
'messageForward.deleteConfirm.title': 'Delete messages',
'messageForward.empty': 'Select at least one message to forward',
+ 'messageForward.failed': 'Some messages could not be forwarded',
'messageForward.modal.empty': 'No other agents available',
'messageForward.modal.moreMessages': '+{{count}} more messages',
'messageForward.modal.noRecipients': 'Pick agents on the left to forward to',
@@ -500,6 +501,13 @@ export default {
'messageForward.successMulti': 'Forwarded to {{count}} agents',
'messageForward.transcript.header':
'The following {{count}} messages were forwarded from another conversation. Please use them as context and continue:',
+ 'messageForward.topic.context': 'Topic context',
+ 'messageForward.topic.description':
+ 'The user and assistant messages in this topic will be sent as context. Tool messages are excluded.',
+ 'messageForward.topic.header':
+ 'The following topic was forwarded from another conversation. Please use it as context and continue:',
+ 'messageForward.topic.loadFailed': 'Could not load this topic for forwarding',
+ 'messageForward.topic.modalTitle': 'Forward topic to Agent',
'messageLongCollapse.collapse': 'Show less',
'messageLongCollapse.expand': 'Show more',
'messages.dm.sentTo': 'Visible only to {{name}}',
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index f382d2e3737..cc3edf37e24 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -20,6 +20,7 @@ export default {
'actions.copyWorkingDirectorySuccess': 'Working directory copied',
'actions.duplicate': 'Duplicate',
'actions.moveToAgent': 'Move to another agent',
+ 'actions.forwardToAgent': 'Forward to another agent',
'actions.favorite': 'Favorite',
'actions.unfavorite': 'Unfavorite',
'actions.markCompleted': 'Archive',
diff --git a/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx b/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx
new file mode 100644
index 00000000000..48461c97242
--- /dev/null
+++ b/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx
@@ -0,0 +1,168 @@
+'use client';
+
+import { Flexbox, SearchBar, Text, TextArea } from '@lobehub/ui';
+import { Button, useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import AgentAvatar from '@/routes/(main)/home/_layout/Body/Agent/List/AgentItem/Avatar';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+import SelectCircle from '../SelectCircle';
+import type { ForwardTarget } from '../useForwardMessages';
+import { useForwardTopic } from '../useForwardTopic';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ block-size: 460px;
+ `,
+ context: css`
+ flex: 1;
+
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ divider: css`
+ align-self: stretch;
+ inline-size: 1px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+ list: css`
+ overflow-y: auto;
+ flex: 1;
+ `,
+ row: css`
+ cursor: pointer;
+
+ min-block-size: 44px;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadiusLG};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ selected: css`
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+export interface TopicForwardContentProps {
+ sourceAgentId: string;
+ topicId: string;
+ topicTitle: string;
+}
+
+export const TopicForwardContent = ({
+ sourceAgentId,
+ topicId,
+ topicTitle,
+}: TopicForwardContentProps) => {
+ const { t } = useTranslation('chat');
+ const { close } = useModalContext();
+ const [keyword, setKeyword] = useState('');
+ const [note, setNote] = useState('');
+ const [selectedIds, setSelectedIds] = useState<string[]>([]);
+ const agents = useHomeStore(homeAgentListSelectors.allAgents);
+ const forwardTopic = useForwardTopic({ agentId: sourceAgentId, topicId });
+
+ useFetchAgentList();
+
+ const candidates = useMemo(() => {
+ const query = keyword.trim().toLowerCase();
+ return agents
+ .filter((agent) => agent.type === 'agent' && agent.id !== sourceAgentId)
+ .filter((agent) => !query || (agent.title || '').toLowerCase().includes(query));
+ }, [agents, keyword, sourceAgentId]);
+
+ const handleForward = () => {
+ const targets: ForwardTarget[] = selectedIds
+ .map((id) => agents.find((agent) => agent.id === id))
+ .filter((agent): agent is NonNullable<typeof agent> => !!agent)
+ .map((agent) => ({ id: agent.id, title: agent.title }));
+ if (targets.length === 0) return;
+
+ forwardTopic(targets, note);
+ close();
+ };
+
+ return (
+ <Flexbox horizontal className={styles.body} gap={16}>
+ <Flexbox flex={1} gap={8} style={{ minWidth: 0 }}>
+ <SearchBar
+ allowClear
+ placeholder={t('messageForward.modal.searchPlaceholder')}
+ value={keyword}
+ onChange={(event) => setKeyword(event.target.value)}
+ />
+ <Flexbox className={styles.list} gap={4}>
+ {candidates.length === 0 ? (
+ <Flexbox align={'center'} justify={'center'} padding={24}>
+ <Text type={'secondary'}>{t('messageForward.modal.empty')}</Text>
+ </Flexbox>
+ ) : (
+ candidates.map((agent) => {
+ const selected = selectedIds.includes(agent.id);
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.row, selected && styles.selected)}
+ gap={8}
+ key={agent.id}
+ onClick={() =>
+ setSelectedIds((ids) =>
+ selected ? ids.filter((id) => id !== agent.id) : [...ids, agent.id],
+ )
+ }
+ >
+ <AgentAvatar
+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}
+ />
+ <Text ellipsis style={{ flex: 1 }}>
+ {agent.title || t('untitledAgent')}
+ </Text>
+ <SelectCircle checked={selected} />
+ </Flexbox>
+ );
+ })
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ <div className={styles.divider} />
+
+ <Flexbox flex={1} gap={12} style={{ minWidth: 0 }}>
+ <Text type={'secondary'}>{t('messageForward.topic.context')}</Text>
+ <Flexbox className={styles.context} gap={8}>
+ <Text ellipsis strong>
+ {topicTitle}
+ </Text>
+ <Text type={'secondary'}>{t('messageForward.topic.description')}</Text>
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 4, minRows: 2 }}
+ placeholder={t('messageForward.modal.notePlaceholder')}
+ resize={false}
+ value={note}
+ onChange={(event) => setNote(event.target.value)}
+ />
+ <Flexbox horizontal gap={8} justify={'flex-end'}>
+ <Button onClick={close}>{t('messageForward.bar.cancel')}</Button>
+ <Button disabled={selectedIds.length === 0} type={'primary'} onClick={handleForward}>
+ {selectedIds.length > 0
+ ? t('messageForward.modal.sendCount', { count: selectedIds.length })
+ : t('messageForward.bar.forward')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+};
diff --git a/src/features/Conversation/MessageForward/TopicForwardModal/index.tsx b/src/features/Conversation/MessageForward/TopicForwardModal/index.tsx
new file mode 100644
index 00000000000..6db3c55aa5d
--- /dev/null
+++ b/src/features/Conversation/MessageForward/TopicForwardModal/index.tsx
@@ -0,0 +1,17 @@
+'use client';
+
+import { createModal } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
+
+import type { TopicForwardContentProps } from './Content';
+import { TopicForwardContent } from './Content';
+
+export const createTopicForwardModal = (props: TopicForwardContentProps) =>
+ createModal({
+ content: <TopicForwardContent {...props} />,
+ footer: null,
+ maskClosable: true,
+ styles: { content: { overflow: 'hidden', padding: 16 } },
+ title: t('messageForward.topic.modalTitle', { ns: 'chat' }),
+ width: 'min(90%, 760px)',
+ });
diff --git a/src/features/Conversation/MessageForward/forwardDispatch.test.ts b/src/features/Conversation/MessageForward/forwardDispatch.test.ts
index 916b68a7d7f..5ec305a5937 100644
--- a/src/features/Conversation/MessageForward/forwardDispatch.test.ts
+++ b/src/features/Conversation/MessageForward/forwardDispatch.test.ts
@@ -94,22 +94,27 @@ describe('forwardDispatch', () => {
);
});
- it('flattens assistantGroup child blocks into one block', () => {
+ it('flattens assistantGroup child text without serializing tool payloads', () => {
const content = buildForwardedContent(
[
msg({
children: [
- { content: 'part one' },
+ { content: 'part one', tools: [{ id: 'tool-1' }] },
{ content: 'part two' },
] as UIChatMessage['children'],
content: '',
role: 'assistantGroup',
}),
+ msg({ content: 'tool output', role: 'tool' }),
+ msg({ content: 'kept', role: 'assistant' }),
],
{ header: 'H', roleLabel },
);
- expect(content).toBe('H\n\n---\n\n**Assistant**\n\npart one\n\npart two');
+ expect(content).toBe(
+ 'H\n\n---\n\n**Assistant**\n\npart one\n\npart two\n\n---\n\n**Assistant**\n\nkept',
+ );
+ expect(content).not.toContain('tool-1');
});
it('skips messages with empty content', () => {
diff --git a/src/features/Conversation/MessageForward/forwardDispatch.ts b/src/features/Conversation/MessageForward/forwardDispatch.ts
index 6c99d98533d..c53b541add2 100644
--- a/src/features/Conversation/MessageForward/forwardDispatch.ts
+++ b/src/features/Conversation/MessageForward/forwardDispatch.ts
@@ -1,4 +1,4 @@
-import { type UIChatMessage } from '@lobechat/types';
+export { buildForwardedContent } from '@/store/chat/slices/forward/helpers';
/**
* A forward request parked in {@link useForwardDispatchStore} while we navigate
@@ -48,36 +48,3 @@ export const canConsumePendingForward = ({
return !isAgentConfigLoading && isNewConversation;
};
-
-const blockText = (label: string, body: string) => `**${label}**\n\n${body.trim()}`;
-
-/**
- * Render selected messages into a single Markdown transcript. The result is sent
- * as one user turn to the target agent, so it reads the forwarded exchange as
- * context and continues from there.
- */
-export const buildForwardedContent = (
- messages: UIChatMessage[],
- options: { header: string; roleLabel: (role: string) => string },
-): string => {
- const { header, roleLabel } = options;
-
- const blocks = messages
- .map((message) => {
- // AssistantGroup messages keep their text in child content blocks.
- const body =
- message.role === 'assistantGroup' && message.children?.length
- ? message.children
- .map((child) => child.content)
- .filter(Boolean)
- .join('\n\n')
- : message.content;
-
- if (!body || !body.trim()) return undefined;
-
- return blockText(roleLabel(message.role), body);
- })
- .filter((block): block is string => !!block);
-
- return [header, ...blocks].join('\n\n---\n\n');
-};
diff --git a/src/features/Conversation/MessageForward/useForwardMessages.ts b/src/features/Conversation/MessageForward/useForwardMessages.ts
index af3f9f2f637..2d7ef1b0ea7 100644
--- a/src/features/Conversation/MessageForward/useForwardMessages.ts
+++ b/src/features/Conversation/MessageForward/useForwardMessages.ts
@@ -1,34 +1,28 @@
-import { nanoid } from '@lobechat/utils';
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import { App } from 'antd';
import isEqual from 'fast-deep-equal';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigateToAgent } from '@/hooks/useNavigateToAgent';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { useChatStore } from '@/store/chat';
+import type { ForwardTarget } from '@/store/chat/slices/forward/action';
import { useConversationStore } from '../store';
-import { buildForwardedContent } from './forwardDispatch';
-import { useForwardDispatchStore } from './forwardDispatchStore';
-export interface ForwardTarget {
- id: string;
- title?: string | null;
-}
+export type { ForwardTarget } from '@/store/chat/slices/forward/action';
/**
* Returns a callback that forwards the currently-selected messages to one or
- * more target agents. The transcript is serialised once, then:
- * - the first (primary) target is parked + navigated to, so the user lands in
- * it and {@link ForwardMessageDispatcher} sends the opening turn;
- * - any additional targets are sent in the background via the global chat store
- * (isolated new topic each), so "分别发送" reaches every recipient.
+ * more target agents. The chat store serialises and sends the transcript into
+ * one isolated topic per target; this hook owns only selection UX and navigation.
*/
export const useForwardMessages = () => {
const { t } = useTranslation('chat');
const { message } = App.useApp();
- const navigateToAgent = useNavigateToAgent();
- const setPendingForward = useForwardDispatchStore((s) => s.setPendingForward);
+ const navigate = useWorkspaceAwareNavigate();
+ const forwardMessages = useChatStore((s) => s.forwardMessages);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
const exitSelectionMode = useConversationStore((s) => s.exitSelectionMode);
// The conversation store is context-scoped (no global getState), so read the
@@ -39,54 +33,39 @@ export const useForwardMessages = () => {
}, isEqual);
return useCallback(
- (targets: ForwardTarget[], note?: string) => {
+ async (targets: ForwardTarget[], note?: string) => {
if (selectedMessages.length === 0) {
message.warning(t('messageForward.empty'));
return;
}
if (targets.length === 0) return;
- const transcript = buildForwardedContent(selectedMessages, {
+ const primaryTarget = targets[0];
+ exitSelectionMode();
+
+ void forwardMessages({
header: t('messageForward.transcript.header', { count: selectedMessages.length }),
+ messages: selectedMessages,
+ note,
+ onTopicCreated: (target, topicId) => {
+ if (target.id !== primaryTarget.id) return;
+ clearPortalStack();
+ navigate(AGENT_CHAT_TOPIC_URL(target.id, topicId));
+ },
roleLabel: (role) =>
role === 'user' ? t('messageForward.role.user') : t('messageForward.role.assistant'),
+ targets,
+ }).then((result) => {
+ if (result.succeeded.length > 0) {
+ message.success(
+ targets.length === 1
+ ? t('messageForward.success', { title: primaryTarget.title || '' })
+ : t('messageForward.successMulti', { count: result.succeeded.length }),
+ );
+ }
+ if (result.failed.length > 0) message.error(t('messageForward.failed'));
});
- // Append the user's optional note as the actual instruction after the
- // forwarded context.
- const content = note?.trim() ? `${transcript}\n\n${note.trim()}` : transcript;
-
- const [primary, ...rest] = targets;
-
- // Primary: park the transcript so the post-navigation dispatcher sends it.
- setPendingForward({
- content,
- dispatchId: nanoid(),
- messageCount: selectedMessages.length,
- targetAgentId: primary.id,
- });
-
- // Additional recipients: fire-and-forget background sends into an isolated
- // new topic each (no navigation, no hijacking the active topic).
- for (const target of rest) {
- void useChatStore
- .getState()
- .sendMessage({
- context: { agentId: target.id, isNew: true, isolatedTopic: true, scope: 'main' },
- message: content,
- messages: [],
- })
- .catch(() => {});
- }
-
- exitSelectionMode();
- navigateToAgent(primary.id);
-
- message.success(
- targets.length === 1
- ? t('messageForward.success', { title: primary.title || '' })
- : t('messageForward.successMulti', { count: targets.length }),
- );
},
- [t, message, navigateToAgent, setPendingForward, exitSelectionMode, selectedMessages],
+ [t, message, navigate, clearPortalStack, forwardMessages, exitSelectionMode, selectedMessages],
);
};
diff --git a/src/features/Conversation/MessageForward/useForwardTopic.ts b/src/features/Conversation/MessageForward/useForwardTopic.ts
new file mode 100644
index 00000000000..9694d8760c8
--- /dev/null
+++ b/src/features/Conversation/MessageForward/useForwardTopic.ts
@@ -0,0 +1,55 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import { App } from 'antd';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
+import type { ForwardTarget } from '@/store/chat/slices/forward/action';
+
+interface ForwardTopicSource {
+ agentId: string;
+ topicId: string;
+}
+
+export const useForwardTopic = ({ agentId, topicId }: ForwardTopicSource) => {
+ const { t } = useTranslation('chat');
+ const { message } = App.useApp();
+ const navigate = useWorkspaceAwareNavigate();
+ const forwardTopic = useChatStore((s) => s.forwardTopic);
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+
+ return useCallback(
+ (targets: ForwardTarget[], note?: string) => {
+ if (targets.length === 0) return;
+
+ const primaryTarget = targets[0];
+ void forwardTopic({
+ header: t('messageForward.topic.header'),
+ note,
+ onTopicCreated: (target, createdTopicId) => {
+ if (target.id !== primaryTarget.id) return;
+ clearPortalStack();
+ navigate(AGENT_CHAT_TOPIC_URL(target.id, createdTopicId));
+ },
+ roleLabel: (role) =>
+ role === 'user' ? t('messageForward.role.user') : t('messageForward.role.assistant'),
+ sourceAgentId: agentId,
+ targets,
+ topicId,
+ })
+ .then((result) => {
+ if (result.succeeded.length > 0) {
+ message.success(
+ targets.length === 1
+ ? t('messageForward.success', { title: primaryTarget.title || '' })
+ : t('messageForward.successMulti', { count: result.succeeded.length }),
+ );
+ }
+ if (result.failed.length > 0) message.error(t('messageForward.failed'));
+ })
+ .catch(() => message.error(t('messageForward.topic.loadFailed')));
+ },
+ [agentId, clearPortalStack, forwardTopic, message, navigate, t, topicId],
+ );
+};
diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.test.tsx
index c15bda53a48..fa217eef693 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Actions/index.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.test.tsx
@@ -53,14 +53,11 @@ describe('GroupActionsBar — hetero (assistantGroup) forward/select gating', ()
expect(bar).toHaveAttribute('data-menu', '');
});
- it('finished but last block is a tool call → exposes share + select (forward entry) + delete', () => {
+ it('finished but last block is a tool call → exposes share, select, and delete', () => {
storeMock.isGenerating = false;
renderBar({ contentId: undefined });
const bar = screen.getByTestId('action-bar');
- // This is the heterogeneous-agent gap: a completed CC/Codex turn that ends on
- // a tool block used to fall into the delete-only "in progress" bar, hiding the
- // forward (`select`) and `share` entries. It must now surface them.
const menu = bar.getAttribute('data-menu') ?? '';
expect(menu.split(',')).toContain('select');
expect(menu.split(',')).toContain('share');
@@ -68,7 +65,7 @@ describe('GroupActionsBar — hetero (assistantGroup) forward/select gating', ()
expect(bar).toHaveAttribute('data-bar', 'delAndRegenerate');
});
- it('finished with a trailing text block → full menu (unchanged native behavior)', () => {
+ it('finished with a trailing text block → full menu', () => {
storeMock.isGenerating = false;
renderBar({ contentId: 'block-text' });
diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
index 0517b178a15..bdd97793ab7 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx
@@ -29,7 +29,8 @@ const IN_PROGRESS_BAR: MessageActionSlot[] = ['del'];
// Finished turn whose last child block is a tool call (typical for heterogeneous
// CC/Codex turns, which end on a Bash/Read/Edit/Task block with no trailing text).
// There's no text block to edit/copy, but the turn IS complete — it can still be
-// shared and, crucially, multi-selected/forwarded like a native reply.
+// shared and multi-selected/forwarded as one aggregated assistant reply. The
+// forward serializer keeps child text while excluding child tool payloads.
const NO_TEXT_BLOCK_BAR: MessageActionSlot[] = ['delAndRegenerate'];
const NO_TEXT_BLOCK_MENU: MessageActionSlot[] = ['share', 'select', 'divider', 'del'];
@@ -59,7 +60,7 @@ export const GroupActionsBar = memo<GroupActionsProps>(
return <MessageActionBar bar={IN_PROGRESS_BAR} ctx={ctx} />;
}
// Finished, but the turn ends on a tool-call block — no text to edit/copy,
- // yet it's a complete reply that can be shared and multi-selected/forwarded.
+ // yet it's a complete reply that can still be shared and selected.
return <MessageActionBar bar={NO_TEXT_BLOCK_BAR} ctx={ctx} menu={NO_TEXT_BLOCK_MENU} />;
}
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
index df78713f5f1..eb1db4db8a8 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/useDropdownMenu.tsx
@@ -8,6 +8,7 @@ import {
ArchiveRestore,
ExternalLink,
FolderInput,
+ Forward,
Hash,
Link2,
LucideCopy,
@@ -25,6 +26,7 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import { openRenameModal } from '@/components/RenameModal';
import { isDesktop } from '@/const/version';
import { createMoveTopicsModal } from '@/features/AgentTopicManager/MoveTopicsModal';
+import { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';
import { confirmRemoveTopic } from '@/features/DeleteTopicConfirm';
import { openShareModal } from '@/features/ShareModal';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
@@ -204,6 +206,16 @@ export const useTopicItemDropdownMenu = ({
duplicateTopic(id);
},
},
+ {
+ disabled: !canCreateTopic || !activeAgentId,
+ icon: <Icon icon={Forward} />,
+ key: 'forwardToAgent',
+ label: t('actions.forwardToAgent'),
+ onClick: () => {
+ if (!activeAgentId) return;
+ createTopicForwardModal({ sourceAgentId: activeAgentId, topicId: id, topicTitle: title });
+ },
+ },
{
disabled: !canEditTopic,
icon: <Icon icon={FolderInput} />,
diff --git a/src/store/chat/slices/forward/action.test.ts b/src/store/chat/slices/forward/action.test.ts
new file mode 100644
index 00000000000..b46e036fd24
--- /dev/null
+++ b/src/store/chat/slices/forward/action.test.ts
@@ -0,0 +1,112 @@
+import type { UIChatMessage } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { messageService } from '@/services/message';
+import { useAgentStore } from '@/store/agent';
+
+import { ChatForwardActionImpl } from './action';
+
+const message = (role: UIChatMessage['role'], content: string): UIChatMessage =>
+ ({ content, id: `${role}-${content}`, role }) as UIChatMessage;
+
+describe('ChatForwardAction', () => {
+ beforeEach(() => {
+ useAgentStore.setState({ agentMap: {} });
+ vi.spyOn(agentService, 'getAgentConfigById').mockImplementation(
+ async (id) => ({ id }) as never,
+ );
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('forwards only user and assistant text into isolated topics', async () => {
+ const onTopicCreated = vi.fn();
+ const sendMessage = vi
+ .fn()
+ .mockImplementationOnce(async ({ onTopicCreated: notifyTopicCreated }) => {
+ notifyTopicCreated('topic-a');
+ return { createdTopicId: 'topic-a' };
+ })
+ .mockRejectedValueOnce(new Error('failed'));
+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);
+
+ const result = await action.forwardMessages({
+ header: 'Forwarded',
+ messages: [
+ message('user', 'question'),
+ message('tool', 'private tool output'),
+ message('assistant', 'answer'),
+ ],
+ onTopicCreated,
+ roleLabel: (role) => role,
+ targets: [{ id: 'agent-a' }, { id: 'agent-b' }],
+ });
+
+ expect(sendMessage).toHaveBeenCalledTimes(2);
+ expect(agentService.getAgentConfigById).toHaveBeenCalledTimes(2);
+ expect(sendMessage.mock.calls[0][0].message).toBe(
+ 'Forwarded\n\n---\n\n**user**\n\nquestion\n\n---\n\n**assistant**\n\nanswer',
+ );
+ expect(sendMessage.mock.calls[0][0].message).not.toContain('private tool output');
+ expect(onTopicCreated).toHaveBeenCalledWith({ id: 'agent-a' }, 'topic-a');
+ expect(result.succeeded).toEqual([{ agentId: 'agent-a', topicId: 'topic-a' }]);
+ expect(result.failed).toHaveLength(1);
+ expect(result.failed[0].agentId).toBe('agent-b');
+ });
+
+ it('treats a send without a created topic as a failure', async () => {
+ const sendMessage = vi.fn().mockResolvedValue(undefined);
+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);
+
+ const result = await action.forwardMessages({
+ header: 'Forwarded',
+ messages: [message('user', 'question')],
+ roleLabel: (role) => role,
+ targets: [{ id: 'agent-a' }],
+ });
+
+ expect(result.succeeded).toEqual([]);
+ expect(result.failed).toHaveLength(1);
+ });
+
+ it('treats a missing target agent as a failure without sending', async () => {
+ vi.mocked(agentService.getAgentConfigById).mockResolvedValueOnce(null);
+ const sendMessage = vi.fn();
+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);
+
+ const result = await action.forwardMessages({
+ header: 'Forwarded',
+ messages: [message('user', 'question')],
+ roleLabel: (role) => role,
+ targets: [{ id: 'missing-agent' }],
+ });
+
+ expect(sendMessage).not.toHaveBeenCalled();
+ expect(result.succeeded).toEqual([]);
+ expect(result.failed).toHaveLength(1);
+ expect(result.failed[0].agentId).toBe('missing-agent');
+ });
+
+ it('loads topic messages before forwarding them', async () => {
+ vi.spyOn(messageService, 'getMessages').mockResolvedValue([message('user', 'from topic')]);
+ const sendMessage = vi.fn().mockResolvedValue({ createdTopicId: 'new-topic' });
+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);
+
+ const result = await action.forwardTopic({
+ header: 'Forwarded topic',
+ roleLabel: (role) => role,
+ sourceAgentId: 'source-agent',
+ targets: [{ id: 'target-agent' }],
+ topicId: 'source-topic',
+ });
+
+ expect(messageService.getMessages).toHaveBeenCalledWith({
+ agentId: 'source-agent',
+ topicId: 'source-topic',
+ });
+ expect(result.succeeded).toEqual([{ agentId: 'target-agent', topicId: 'new-topic' }]);
+ });
+});
diff --git a/src/store/chat/slices/forward/action.ts b/src/store/chat/slices/forward/action.ts
new file mode 100644
index 00000000000..dcfd572d2fb
--- /dev/null
+++ b/src/store/chat/slices/forward/action.ts
@@ -0,0 +1,109 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+import { agentService } from '@/services/agent';
+import { messageService } from '@/services/message';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import type { ChatStore } from '@/store/chat/store';
+import type { StoreSetter } from '@/store/types';
+
+import type { ForwardContentOptions } from './helpers';
+import { buildForwardedContent } from './helpers';
+
+export interface ForwardTarget {
+ id: string;
+ title?: string | null;
+}
+
+export interface ForwardResultItem {
+ agentId: string;
+ error?: unknown;
+ topicId?: string;
+}
+
+export interface ForwardResult {
+ failed: ForwardResultItem[];
+ succeeded: ForwardResultItem[];
+}
+
+export interface ForwardMessagesParams extends ForwardContentOptions {
+ messages: UIChatMessage[];
+ note?: string;
+ onTopicCreated?: (target: ForwardTarget, topicId: string) => void;
+ targets: ForwardTarget[];
+}
+
+export interface ForwardTopicParams extends Omit<ForwardMessagesParams, 'messages'> {
+ sourceAgentId: string;
+ topicId: string;
+}
+
+type Setter = StoreSetter<ChatStore>;
+
+export class ChatForwardActionImpl {
+ readonly #get: () => ChatStore;
+
+ constructor(_set: Setter, get: () => ChatStore, _api?: unknown) {
+ void _set;
+ void _api;
+ this.#get = get;
+ }
+
+ forwardMessages = async ({
+ header,
+ messages,
+ note,
+ onTopicCreated,
+ roleLabel,
+ targets,
+ }: ForwardMessagesParams): Promise<ForwardResult> => {
+ if (targets.length === 0) return { failed: [], succeeded: [] };
+
+ const transcript = buildForwardedContent(messages, { header, roleLabel });
+ const content = note?.trim() ? `${transcript}\n\n${note.trim()}` : transcript;
+ const settled = await Promise.allSettled(
+ targets.map(async (target) => {
+ const { id } = target;
+ if (!agentSelectors.getAgentConfigById(id)(getAgentStoreState())) {
+ const config = await agentService.getAgentConfigById(id);
+ if (!config) throw new Error(`Forwarding target agent not found: ${id}`);
+
+ getAgentStoreState().internal_dispatchAgentMap(id, config);
+ }
+
+ const result = await this.#get().sendMessage({
+ context: { agentId: id, isNew: true, isolatedTopic: true, scope: 'main' },
+ message: content,
+ messages: [],
+ onTopicCreated: (topicId) => onTopicCreated?.(target, topicId),
+ });
+ if (!result?.createdTopicId) throw new Error(`Forwarding did not create a topic for ${id}`);
+
+ return { agentId: id, topicId: result.createdTopicId };
+ }),
+ );
+
+ return settled.reduce<ForwardResult>(
+ (result, item, index) => {
+ if (item.status === 'fulfilled') {
+ result.succeeded.push(item.value);
+ } else {
+ result.failed.push({ agentId: targets[index].id, error: item.reason });
+ }
+ return result;
+ },
+ { failed: [], succeeded: [] },
+ );
+ };
+
+ forwardTopic = async ({
+ sourceAgentId,
+ topicId,
+ ...params
+ }: ForwardTopicParams): Promise<ForwardResult> => {
+ const messages = await messageService.getMessages({ agentId: sourceAgentId, topicId });
+ return this.forwardMessages({ ...params, messages });
+ };
+}
+
+export type ChatForwardAction = Pick<ChatForwardActionImpl, keyof ChatForwardActionImpl>;
diff --git a/src/store/chat/slices/forward/helpers.ts b/src/store/chat/slices/forward/helpers.ts
new file mode 100644
index 00000000000..56965efe23c
--- /dev/null
+++ b/src/store/chat/slices/forward/helpers.ts
@@ -0,0 +1,36 @@
+import type { UIChatMessage } from '@lobechat/types';
+
+export interface ForwardContentOptions {
+ header: string;
+ roleLabel: (role: 'assistant' | 'user') => string;
+}
+
+export const getForwardableMessages = (messages: UIChatMessage[]): UIChatMessage[] =>
+ messages.filter(
+ (message) =>
+ ((message.role === 'user' || message.role === 'assistant') && !!message.content?.trim()) ||
+ (message.role === 'assistantGroup' &&
+ !!message.children?.some((child) => !!child.content?.trim())),
+ );
+
+const blockText = (label: string, body: string) => `**${label}**\n\n${body.trim()}`;
+
+export const buildForwardedContent = (
+ messages: UIChatMessage[],
+ options: ForwardContentOptions,
+): string => {
+ const blocks = getForwardableMessages(messages).map((message) => {
+ const content =
+ message.role === 'assistantGroup'
+ ? message.children
+ ?.map((child) => child.content?.trim())
+ .filter(Boolean)
+ .join('\n\n') || ''
+ : message.content;
+ const role = message.role === 'user' ? 'user' : 'assistant';
+
+ return blockText(options.roleLabel(role), content);
+ });
+
+ return [options.header, ...blocks].join('\n\n---\n\n');
+};
diff --git a/src/store/chat/store.ts b/src/store/chat/store.ts
index 09ce26a2ac3..d341b7cfbc1 100644
--- a/src/store/chat/store.ts
+++ b/src/store/chat/store.ts
@@ -16,6 +16,7 @@ import { type ChatAIAgentAction } from './slices/aiAgent/actions';
import { chatAiAgent } from './slices/aiAgent/actions';
import { type ChatBuiltinToolAction } from './slices/builtinTool/actions';
import { chatToolSlice } from './slices/builtinTool/actions';
+import { type ChatForwardAction, ChatForwardActionImpl } from './slices/forward/action';
import { type ChatMessageAction } from './slices/message/actions';
import { chatMessage } from './slices/message/actions';
import { type OperationActions } from './slices/operation/actions';
@@ -34,6 +35,7 @@ import { type ChatTTSAction } from './slices/tts/action';
import { ChatTTSActionImpl } from './slices/tts/action';
export type ChatStoreAction = ChatMessageAction &
+ ChatForwardAction &
ChatThreadAction &
ChatAgentRunAction &
ChatTopicAction &
@@ -61,6 +63,7 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (
...initialState,
...(flattenActions<ChatStoreAction>([
chatMessage(...params),
+ new ChatForwardActionImpl(...params),
new ChatThreadActionImpl(...params),
chatAgentRun(...params),
new ChatTopicActionImpl(...params),