🤯 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
✨ feat(topic): fork a new topic from an assistant message (#20610)
Arvin Xu16d9e3b52720
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex ad792313d44..027b497ad7c 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -461,6 +461,33 @@ export const topicRouter = router({return data.topic.id;}),+ /**+ * Fork a topic from one of its messages: copy the conversation prefix+ * (first message → `messageId`) into a brand new topic and return its id.+ *+ * Shares `cloneTopic`'s guards: a fork writes a new topic and copies content+ * out of the source, so it needs the same `topic:create` capability and the+ * same refusal to lift a visitor topic's content into creator scope.+ */+ forkTopic: topicProcedure+ .use(withScopedPermission('topic:create'))+ .input(+ z.object({+ id: z.string(),+ messageId: z.string(),+ newTitle: z.string().optional(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);+ const data = await ctx.topicModel.duplicate(input.id, input.newTitle, {+ upToMessageId: input.messageId,+ });++ return data.topic.id;+ }),+countTopics: topicProcedure.input(zdiff --git a/locales/en-US/common.json b/locales/en-US/common.jsonindex cb8ca2aceb3..e8715ffcd86 100644--- a/locales/en-US/common.json+++ b/locales/en-US/common.json@@ -240,6 +240,8 @@"footer.star.desc": "If you like {{appName}}, a GitHub star helps a lot. Thank you.","footer.star.title": "Star us on GitHub","footer.title": "Like Our Product?",+ "forkRequiresSavedTopic": "Current topic is not saved. Save it first to fork a new topic",+ "forkTopic": "Continue in new topic","fullscreen": "Full Screen Mode","generation.hero.taglinePrefix": "Start Creating with","generation.promptModeration.blocked": "Content policy check failed. Please revise your prompt.",diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 4b19fb91b33..66da00e2714 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -80,6 +80,10 @@"filter.sort": "Sort by","filter.sortBy.createdAt": "Created time","filter.sortBy.updatedAt": "Updated time",+ "forkFailed": "Failed to fork the topic",+ "forkLoading": "Creating a new topic...",+ "forkSuccess": "Forked to a new topic",+ "forkTitle": "{{title}} (Branch)","groupTitle.byAgent.unknown": "Unknown agent","groupTitle.byProject.noProject": "No directory","groupTitle.byStatus.active": "Active",diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.jsonindex b90771c2d32..524ffc9b41c 100644--- a/locales/zh-CN/common.json+++ b/locales/zh-CN/common.json@@ -240,6 +240,8 @@"footer.star.desc": "如果你喜欢我们的产品,可以去 GitHub 给我们点一颗星。这个小动作对我们意义重大,能激励我们持续改进","footer.star.title": "在 GitHub 为我们点亮星标","footer.title": "喜欢我们的产品?",+ "forkRequiresSavedTopic": "当前话题未保存。保存后即可创建新会话",+ "forkTopic": "在新会话中继续","fullscreen": "全屏模式","generation.hero.taglinePrefix": "即刻创作","generation.promptModeration.blocked": "内容政策检查未通过。请修改您的提示。",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex e364ca1e328..71453e0f9c6 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -80,6 +80,10 @@"filter.sort": "排序","filter.sortBy.createdAt": "按创建时间","filter.sortBy.updatedAt": "按更新时间",+ "forkFailed": "创建新会话失败",+ "forkLoading": "正在创建新会话…",+ "forkSuccess": "已创建新会话",+ "forkTitle": "{{title}} 的分支","groupTitle.byAgent.unknown": "未知 Agent","groupTitle.byProject.noProject": "无目录","groupTitle.byStatus.active": "活跃",diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 128850191ee..ba061dfe0d1 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1633,6 +1633,141 @@ describe('TopicModel', () => {it('throws when the source topic does not exist', async () => {await expect(topicModel.duplicate('nope')).rejects.toThrow('not found');});++ it('copies only the ancestor chain when forking up to a message', async () => {+ const topic = await topicModel.create({ title: 'fork source' });+ await serverDB.insert(messages).values([+ { content: 'q1', id: 'fork-m1', role: 'user', topicId: topic.id, userId },+ {+ content: 'a1',+ id: 'fork-m2',+ parentId: 'fork-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ {+ content: 'q2',+ id: 'fork-m3',+ parentId: 'fork-m2',+ role: 'user',+ topicId: topic.id,+ userId,+ },+ ]);++ const { topic: forked, messages: forkedMessages } = await topicModel.duplicate(+ topic.id,+ 'forked',+ { upToMessageId: 'fork-m2' },+ );++ // only the selected prefix is copied, in root → selected order+ expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'a1']);+ expect(forkedMessages.every((m) => m.topicId === forked.id)).toBe(true);++ // the chain is re-parented inside the fork: root stays root, child points at the copy+ const [root, child] = forkedMessages;+ expect(root.parentId).toBeNull();+ expect(child.parentId).toBe(root.id);++ // the unselected tail stays behind in the source topic+ const sourceMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, topic.id));+ expect(sourceMessages.map((m) => m.id).sort()).toEqual(['fork-m1', 'fork-m2', 'fork-m3']);+ });++ it('leaves sibling branches out of the fork', async () => {+ const topic = await topicModel.create({ title: 'branched source' });+ await serverDB.insert(messages).values([+ { content: 'q1', id: 'br-m1', role: 'user', topicId: topic.id, userId },+ {+ content: 'draft',+ id: 'br-m2a',+ parentId: 'br-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ {+ content: 'regenerated',+ id: 'br-m2b',+ parentId: 'br-m1',+ role: 'assistant',+ topicId: topic.id,+ userId,+ },+ ]);++ const { messages: forkedMessages } = await topicModel.duplicate(topic.id, 'forked', {+ upToMessageId: 'br-m2b',+ });++ expect(forkedMessages.map((m) => m.content)).toEqual(['q1', 'regenerated']);+ });++ it('throws when the fork anchor message is not in the topic', async () => {+ const topic = await topicModel.create({ title: 'no anchor' });++ await expect(+ topicModel.duplicate(topic.id, 'forked', { upToMessageId: 'missing' }),+ ).rejects.toThrow('not found in topic');+ });++ it('stamps the copy with fresh activity time instead of inheriting the source date', async () => {+ const sourceDate = new Date('2020-01-02T03:04:05Z');+ const topic = await topicModel.create({ title: 'stale source' });+ await serverDB.insert(messages).values([+ {+ content: 'old q',+ createdAt: sourceDate,+ id: 'stale-m1',+ role: 'user',+ topicId: topic.id,+ updatedAt: sourceDate,+ userId,+ },+ {+ content: 'old a',+ createdAt: new Date(sourceDate.getTime() + 1000),+ id: 'stale-m2',+ parentId: 'stale-m1',+ role: 'assistant',+ topicId: topic.id,+ updatedAt: new Date(sourceDate.getTime() + 1000),+ userId,+ },+ ]);++ const before = Date.now();+ const { topic: cloned, messages: clonedMessages } = await topicModel.duplicate(+ topic.id,+ 'fresh copy',+ { upToMessageId: 'stale-m2' },+ );++ // A copy is new activity: its own row and every copied message carry the+ // copy moment. The sidebar keys topics by the newest message activity, so+ // inheriting the source's 2020 timestamps would re-file the copy under the+ // source's date group instead of today.+ expect(new Date(cloned.createdAt).getTime()).toBeGreaterThanOrEqual(before - 1000);+ for (const message of clonedMessages) {+ expect(new Date(message.updatedAt).getTime()).toBeGreaterThanOrEqual(before - 1000);+ }++ // The retained order survives retiming: rows still increase root → leaf.+ const [root, child] = clonedMessages;+ expect(new Date(root.createdAt).getTime()).toBeLessThan(new Date(child.createdAt).getTime());++ // The source keeps its own timestamps untouched.+ const sourceMessages = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, topic.id));+ expect(sourceMessages.every((m) => new Date(m.updatedAt).getTime() < before)).toBe(true);+ });});describe('batchMoveToAgent', () => {diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 3b25258b9e4..4361d369183 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1584,7 +1584,14 @@ export class TopicModel {});};- duplicate = async (topicId: string, newTitle?: string) => {+ /**+ * Copy a topic into a new one.+ *+ * `options.upToMessageId` narrows the copy to the ancestor chain ending at+ * that message (first message → that message) — the "fork from here" path.+ * Without it the whole topic is copied, matching the duplicate action.+ */+ duplicate = async (topicId: string, newTitle?: string, options?: { upToMessageId?: string }) => {return this.db.transaction(async (tx) => {// find original topicconst originalTopic = await tx.query.topics.findFirst({@@ -1595,6 +1602,13 @@ export class TopicModel {throw new Error(`Topic with id ${topicId} not found`);}+ // A copy is a brand-new topic: stamp its own timestamps instead of+ // inheriting the source's. The sidebar sorts and groups by the latest+ // activity time (`topicActivityAt`, i.e. the newest message), so a copy+ // that kept the source's date would re-file itself under the source's+ // original day instead of showing up as what it is — activity now.+ const copiedAt = new Date();+// copy topicconst [duplicatedTopic] = await tx.insert(topics)@@ -1605,20 +1619,47 @@ export class TopicModel {...originalTopic,...COPIED_TOPIC_USAGE_RESET,clientId: null,+ createdAt: copiedAt,id: this.genId(),title: newTitle || originalTopic?.title,+ updatedAt: copiedAt,},),).returning();// Find messages associated with the original topic, ordered by createdAt- const originalMessages = await tx+ const topicMessages = await tx.select().from(messages).where(and(eq(messages.topicId, topicId), this.messageOwnership())).orderBy(messages.createdAt);+ // A fork copies only the selected prefix of the conversation (first+ // message → `upToMessageId`), so sibling branches left behind by+ // regenerate stay in the source topic; a duplicate copies the whole topic.+ let originalMessages = topicMessages;+ if (options?.upToMessageId) {+ const byId = new Map(topicMessages.map((message) => [message.id, message]));+ const selected = byId.get(options.upToMessageId);+ if (!selected) {+ throw new Error(`Message with id ${options.upToMessageId} not found in topic ${topicId}`);+ }++ // Walk up to the root, then reverse back to root → selected so parents+ // are inserted before their children.+ const chain: typeof topicMessages = [];+ const visited = new Set<string>();+ let cursor: (typeof topicMessages)[number] | undefined = selected;+ while (cursor && !visited.has(cursor.id)) {+ visited.add(cursor.id);+ chain.push(cursor);+ cursor = cursor.parentId ? byId.get(cursor.parentId) : undefined;+ }++ originalMessages = chain.reverse();+ }+// Find all messagePlugins for this topicconst messageIds = originalMessages.map((m) => m.id);const originalPlugins =@@ -1646,10 +1687,16 @@ export class TopicModel {// copy messages sequentially to respect foreign key constraintsconst duplicatedMessages: DBMessageItem[] = [];- for (const message of originalMessages) {+ for (const [index, message] of originalMessages.entries()) {const newId = idMap.get(message.id)!;const newParentId = message.parentId ? idMap.get(message.parentId) || null : null;+ // Retime the copy to the copy moment while preserving its internal+ // order (monotonic, 1ms apart, ending at `copiedAt`). The sidebar's+ // activity key is the newest message time, so carrying the source's+ // timestamps would keep the new topic in the source's date group.+ const messageAt = new Date(copiedAt.getTime() - (originalMessages.length - 1 - index));+// Update tool IDs in tools arraylet newTools = message.tools;if (newTools && Array.isArray(newTools)) {@@ -1664,6 +1711,7 @@ export class TopicModel {.values({...message,clientId: null,+ createdAt: messageAt,id: newId,// A duplicate consumed no tokens: mark it so usage reports do not// count the source's generation twice (the figures themselves stay@@ -1672,6 +1720,7 @@ export class TopicModel {parentId: newParentId,tools: newTools,topicId: duplicatedTopic.id,+ updatedAt: messageAt,}).returning()) as DBMessageItem[];diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.tsindex fa9c983e04e..7afaddee22a 100644--- a/packages/locales/src/default/common.ts+++ b/packages/locales/src/default/common.ts@@ -51,6 +51,8 @@ export default {'branching': 'Create Subtopic','branchingRequiresSavedTopic':'Current topic is not saved, please save it first to use subtopic feature',+ 'forkRequiresSavedTopic': 'Current topic is not saved. Save it first to fork a new topic',+ 'forkTopic': 'Continue in new topic','viewExecutionDetails': 'View execution details','cancel': 'Cancel','changelog': 'Changelog',diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex fbf082eb9f3..4e1f60e4a5f 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -84,6 +84,10 @@ export default {'duplicateSuccess': 'Topic Copied Successfully','failedStatusTip': 'This run hit an error — open it to take a look.','favorite': 'Favorite',+ 'forkFailed': 'Failed to fork the topic',+ 'forkLoading': 'Creating a new topic...',+ 'forkSuccess': 'Forked to a new topic',+ 'forkTitle': '{{title}} (Branch)','metaCard.ci.failure': 'CI failed','metaCard.ci.none': 'No CI checks','metaCard.ci.pending': 'CI running',diff --git a/src/features/Conversation/Messages/Assistant/Actions/index.tsx b/src/features/Conversation/Messages/Assistant/Actions/index.tsxindex 74d64258628..ae3603f570d 100644--- a/src/features/Conversation/Messages/Assistant/Actions/index.tsx+++ b/src/features/Conversation/Messages/Assistant/Actions/index.tsx@@ -25,6 +25,7 @@ const DEFAULT_MENU: MessageActionSlot[] = ['edit','copy','comments',+ 'fork','branching','collapse','divider',diff --git a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsxindex 8c06ba8d32d..70bafad596b 100644--- a/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/Actions/index.tsx@@ -17,6 +17,7 @@ const DEFAULT_MENU: MessageActionSlot[] = ['copy','copyOperationId','comments',+ 'fork','branching','collapse','divider',diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.test.tsnew file mode 100644index 00000000000..c3f18568232--- /dev/null+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.test.ts@@ -0,0 +1,126 @@+/**+ * @vitest-environment happy-dom+ */+import type { UIChatMessage } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { MessageActionContext } from '../types';+import { forkAction } from './fork';++const mocks = vi.hoisted(() => ({+ activeTopicId: 'tpc-source' as string | undefined,+ forkTopic: vi.fn(),+ isGroupSession: false,+ isThreadMode: false,+}));++vi.mock('@lobehub/ui/base-ui', () => ({+ toast: { warning: vi.fn() },+}));++vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (s: unknown) => unknown) =>+ selector({ activeTopicId: mocks.activeTopicId, forkTopic: mocks.forkTopic }),+}));++vi.mock('@/store/session', () => ({+ useSessionStore: (selector: (s: unknown) => unknown) => selector({}),+}));++vi.mock('@/store/session/selectors', () => ({+ sessionSelectors: { isCurrentSessionGroupSession: () => mocks.isGroupSession },+}));++vi.mock('../../../../store', () => ({+ useConversationStore: (selector: (s: unknown) => unknown) => selector({}),+ messageStateSelectors: { isThreadMode: () => mocks.isThreadMode },+}));++// A group's id IS its head child's id — the assistantGroup bubble is a virtual+// message built from the run's first assistant row. Fixtures mirror that.+const build = (+ data: Partial<UIChatMessage>,+ role: MessageActionContext['role'] = 'group',+ id = 'msg-head',+) =>+ renderHook(() => forkAction.useBuild({ data: data as UIChatMessage, id, role })).result.current;++describe('forkAction', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.activeTopicId = 'tpc-source';+ mocks.isGroupSession = false;+ mocks.isThreadMode = false;+ });++ it('anchors a multi-step group reply on its tail row, not the group head', async () => {+ // The verified shape: head assistant row → tool result → final text row.+ // Anchoring on the head (the group's own id) would cut the fork off before+ // the tool result and the answer the user actually selected.+ const data = {+ children: [+ { id: 'msg-head', tools: [{ result_msg_id: 'msg-tool-result' }] },+ { content: 'STUB TURN DONE', id: 'msg-final' },+ ],+ id: 'msg-head',+ role: 'assistantGroup',+ } as unknown as UIChatMessage;++ const action = build(data);+ await act(async () => {+ await action!.handleClick!();+ });++ expect(mocks.forkTopic).toHaveBeenCalledWith('msg-final');+ });++ it('anchors on the trailing tool result when the reply ends on a tool step', async () => {+ const data = {+ children: [+ { content: 'done', id: 'msg-head' },+ { id: 'msg-step2', tools: [{ result_msg_id: 'msg-tool-2' }] },+ ],+ id: 'msg-head',+ role: 'assistantGroup',+ } as unknown as UIChatMessage;++ const action = build(data);+ await act(async () => {+ await action!.handleClick!();+ });++ expect(mocks.forkTopic).toHaveBeenCalledWith('msg-tool-2');+ });++ it('forks a plain assistant message by its own id', async () => {+ const data = { content: 'hi', id: 'msg-1', role: 'assistant' } as unknown as UIChatMessage;++ const action = build(data, 'assistant', 'msg-1');+ await act(async () => {+ await action!.handleClick!();+ });++ expect(mocks.forkTopic).toHaveBeenCalledWith('msg-1');+ });++ it('is hidden inside a thread, where the copied rows would render nowhere', () => {+ mocks.isThreadMode = true;++ expect(build({ id: 'msg-1', role: 'assistant' } as unknown as UIChatMessage, 'assistant')).toBe(+ null,+ );+ });++ it('is hidden in an agent-group session, matching the context menu', () => {+ mocks.isGroupSession = true;++ expect(build({ id: 'msg-1', role: 'assistant' } as unknown as UIChatMessage, 'assistant')).toBe(+ null,+ );+ });++ it('is hidden for user messages', () => {+ expect(build({ id: 'msg-1', role: 'user' } as unknown as UIChatMessage, 'user')).toBeNull();+ });+});diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.tsnew file mode 100644index 00000000000..66c93809bfd--- /dev/null+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/fork.ts@@ -0,0 +1,64 @@+import { toast } from '@lobehub/ui/base-ui';+import { GitFork } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { useChatStore } from '@/store/chat';+import { useSessionStore } from '@/store/session';+import { sessionSelectors } from '@/store/session/selectors';++import { messageStateSelectors, useConversationStore } from '../../../../store';+import { findLastMessageIdRecursive } from '../../../../store/slices/data/selectors';+import { defineAction } from '../defineAction';++/**+ * Fork the conversation up to this message into a separate new topic.+ *+ * Assistant-only: the fork copies a conversation prefix, so the anchor has to+ * be a reply that already has context behind it. `group` is the aggregated+ * form of the same reply (several assistant blocks rendered as one turn), so it+ * gets the entry too. This is deliberately separate from `branching` — that one+ * opens a thread *inside* the current topic, while this one produces a+ * standalone topic in the sidebar.+ */+export const forkAction = defineAction({+ key: 'fork',+ useBuild: (ctx) => {+ const { t } = useTranslation('common');++ const [topic, forkTopic] = useChatStore((s) => [s.activeTopicId, s.forkTopic]);+ // A thread portal has nowhere standalone to copy into: the copied rows keep+ // their `threadId`, while switching topic clears `activeThreadId`, so the new+ // topic would open with the exchange hidden. The context menu already keeps+ // Fork out of thread and group sessions — the action bar has to agree.+ const inThread = useConversationStore(messageStateSelectors.isThreadMode);+ const isGroupSession = useSessionStore(sessionSelectors.isCurrentSessionGroupSession);+ const isAssistant = ctx.role === 'assistant' || ctx.role === 'group';+ // A `group` context id is the aggregated turn's FIRST row, but the reply the+ // user picked runs on past it (tool results, final text). Anchor the fork on+ // the turn's real tail so the copy carries the whole reply; for a plain+ // assistant message the message itself is already the tail.+ const anchorId =+ ctx.role === 'group' ? (findLastMessageIdRecursive(ctx.data) ?? ctx.id) : ctx.id;++ return useMemo(+ () =>+ isAssistant && !inThread && !isGroupSession+ ? {+ handleClick: async () => {+ if (!topic) {+ toast.warning(t('forkRequiresSavedTopic'));+ return;+ }++ await forkTopic(anchorId);+ },+ icon: GitFork,+ key: 'fork',+ label: t('forkTopic'),+ }+ : null,+ [isAssistant, inThread, isGroupSession, t, anchorId, topic, forkTopic],+ );+ },+});diff --git a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.tsindex 02ca862dda0..c8bf26d5d15 100644--- a/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts+++ b/src/features/Conversation/Messages/components/MessageActionBar/useBuildActions.ts@@ -11,6 +11,7 @@ import { copyOperationIdAction } from './actions/copyOperationId';import { delAction } from './actions/del';import { delAndRegenerateAction } from './actions/delAndRegenerate';import { editAction } from './actions/edit';+import { forkAction } from './actions/fork';import { regenerateAction } from './actions/regenerate';import { restoreToInputAction } from './actions/restoreToInput';import { saveAsEvalCaseAction } from './actions/saveAsEvalCase';@@ -32,7 +33,7 @@ export const useBuildActions = (ctx: MessageActionContext,): Record<string, MessageActionItem | null> => {// View-only General access on the conversation's agent/group: mutating- // actions (send/regenerate/edit/delete/translate/branch) don't apply —+ // actions (send/regenerate/edit/delete/translate/branch/fork) don't apply —// same "absent when not applicable" rule as the role checks above.const { canUseResource } = useConversationResourceAccess();@@ -48,6 +49,7 @@ export const useBuildActions = (del: delAction.useBuild(ctx),delAndRegenerate: delAndRegenerateAction.useBuild(ctx),edit: editAction.useBuild(ctx),+ fork: forkAction.useBuild(ctx),regenerate: regenerateAction.useBuild(ctx),restoreToInput: restoreToInputAction.useBuild(ctx),saveAsEvalCase: saveAsEvalCaseAction.useBuild(ctx),@@ -63,6 +65,7 @@ export const useBuildActions = ('del','delAndRegenerate','edit',+ 'fork','regenerate','translate',]) {diff --git a/src/features/Conversation/hooks/useChatItemContextMenu.tsx b/src/features/Conversation/hooks/useChatItemContextMenu.tsxindex 1d1ba1a560b..b4b205e917a 100644--- a/src/features/Conversation/hooks/useChatItemContextMenu.tsx+++ b/src/features/Conversation/hooks/useChatItemContextMenu.tsx@@ -15,6 +15,7 @@ import { resolveHeteroErroredStepId } from '@/features/Conversation/Error/heteroimport { usePermission } from '@/hooks/usePermission';import { showContextMenu } from '@/libs/contextMenu';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';+import { useChatStore } from '@/store/chat';import { useSessionStore } from '@/store/session';import { sessionSelectors } from '@/store/session/selectors';import { useUserStore } from '@/store/user';@@ -68,6 +69,7 @@ export const useChatItemContextMenu = ({const selectedTextRef = useRef<string | undefined>(undefined);const storeApi = useConversationStoreApi();+ const forkTopic = useChatStore((s) => s.forkTopic);const [role, error, isCollapsed, hasThread, isRegenerating] = useConversationStore((s) => {const item = dataSelectors.getDisplayMessageById(id)(s);@@ -131,6 +133,7 @@ export const useChatItemContextMenu = ({divider,edit,expand,+ fork,regenerate,share,translate,@@ -143,7 +146,7 @@ export const useChatItemContextMenu = ({if ('type' in item && item.type === 'divider') return item;if (['edit', 'del'].includes(String(item.key))) return { ...item, disabled: !canEdit };if (- ['branching', 'delAndRegenerate', 'regenerate', 'translate'].includes(+ ['branching', 'delAndRegenerate', 'fork', 'regenerate', 'translate'].includes(String(item.key),)) {@@ -162,6 +165,9 @@ export const useChatItemContextMenu = ({const collapseAction = isCollapsed ? expand : collapse;const list: MenuItem[] = [edit, copy, collapseAction];+ // Forking a message into a standalone topic is GA; the in-topic thread+ // creator (`branching`) is still gated behind dev mode.+ if (!inThread && !isGroupSession) list.push(fork);if (!inThread && !isGroupSession && isDevMode) list.push(branching);list.push(divider, translate, divider, share, divider, regenerate, delAndRegenerate, del);@@ -250,6 +256,15 @@ export const useChatItemContextMenu = ({toggleMessageCollapsed(id);break;}+ case 'fork': {+ if (!canCreate) break;+ if (!topic) {+ toast.warning(t('forkRequiresSavedTopic'));+ break;+ }+ await forkTopic(id);+ break;+ }case 'branching': {if (!canCreate) break;if (!topic) {@@ -311,6 +326,7 @@ export const useChatItemContextMenu = ({deleteMessage,delAndRegenerateMessage,delAndResendThreadMessage,+ forkTopic,getMessage,handleShare,id,diff --git a/src/features/Conversation/hooks/useChatListActionsBar.tsx b/src/features/Conversation/hooks/useChatListActionsBar.tsxindex dcb8a8acd70..18d4b3d878f 100644--- a/src/features/Conversation/hooks/useChatListActionsBar.tsx+++ b/src/features/Conversation/hooks/useChatListActionsBar.tsx@@ -6,6 +6,7 @@ import {Copy,DownloadIcon,Edit,+ GitFork,LanguagesIcon,ListChevronsDownUp,ListChevronsUpDown,@@ -40,6 +41,7 @@ interface ChatListActionsBar {edit: ActionBarItem;expand: ActionBarItem;export: ActionBarItem;+ fork: ActionBarItem;regenerate: ActionBarItem;share: ActionBarItem;translate: ActionBarItem;@@ -117,6 +119,11 @@ export const useChatListActionsBar = ({label: 'Export as PDF',sfSymbol: 'square.and.arrow.up',},+ fork: {+ icon: GitFork,+ key: 'fork',+ label: t('forkTopic'),+ },regenerate: {disabled: isRegenerating,icon: RotateCcw,diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.tsindex 26652a1dca6..4e38ff177f4 100644--- a/src/features/Conversation/store/slices/data/selectors.ts+++ b/src/features/Conversation/store/slices/data/selectors.ts@@ -76,7 +76,7 @@ const findLastBlockId = (block: AssistantContentBlock | undefined): string | und* Recursively finds the last message ID in a message tree* Priority: children > tools > self*/-const findLastMessageIdRecursive = (node: UIChatMessage | undefined): string | undefined => {+export const findLastMessageIdRecursive = (node: UIChatMessage | undefined): string | undefined => {if (!node) return undefined;// Priority 1: Dive into children recursivelydiff --git a/src/libs/i18n/serverTranslation.test.ts b/src/libs/i18n/serverTranslation.test.tsindex 382ccc4e814..4638779d75e 100644--- a/src/libs/i18n/serverTranslation.test.ts+++ b/src/libs/i18n/serverTranslation.test.ts@@ -1,4 +1,11 @@// @vitest-environment node+// Vitest 5 races the first dynamic import inside `translation()` against+// `vi.mock` registration (vitest#7040). Resolving the mocked default modules+// here — at module scope, after `vi.mock` hoisting and before any test runs —+// makes the loader hit the mock instead of the real locale file.+import '@/locales/default/models';+import '@/locales/default/providers';+import { cookies } from 'next/headers';import { beforeEach, describe, expect, it, vi } from 'vitest';diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex adafec3c0a5..c2a8210ab5d 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -64,6 +64,10 @@ export class TopicService {return lambdaClient.topic.cloneTopic.mutate({ id, newTitle });};+ forkTopic = (params: { id: string; messageId: string; newTitle?: string }): Promise<string> => {+ return lambdaClient.topic.forkTopic.mutate(params);+ };+batchMoveTopics = (topicIds: string[], targetAgentId: string) => {return lambdaClient.topic.batchMoveTopics.mutate({ targetAgentId, topicIds });};diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 5f4cdce4d7e..4004cdf8bb2 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -69,6 +69,7 @@ vi.mock('@/services/topic', () => ({removeTopic: vi.fn(),cloneTopic: vi.fn(),createTopic: vi.fn(),+ forkTopic: vi.fn(),updateTopicFavorite: vi.fn(),updateTopicMetadata: vi.fn(),updateTopicModel: vi.fn(),@@ -4441,6 +4442,62 @@ describe('topic action', () => {expect(switchTopicSpy).toHaveBeenCalledWith(newTopicId);});});+ describe('forkTopic', () => {+ it('should fork the active topic up to a message and switch to the new topic', async () => {+ const { result } = renderHook(() => useChatStore());+ const topicId = 'topic-1';+ const newTopicId = 'forked-topic-id';+ const topics = [{ id: topicId, title: 'Original Topic' }] as ChatTopic[];++ await act(async () => {+ useChatStore.setState({+ activeAgentId: 'abc',+ activeTopicId: topicId,+ topicDataMap: {+ [topicMapKey({ agentId: 'abc' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ });+ });++ const forkTopicSpy = vi.spyOn(topicService, 'forkTopic').mockResolvedValue(newTopicId);+ const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');+ const switchTopicSpy = vi.spyOn(result.current, 'switchTopic');++ await act(async () => {+ await result.current.forkTopic('msg-2');+ });++ expect(forkTopicSpy).toHaveBeenCalledWith({+ id: topicId,+ messageId: 'msg-2',+ newTitle: 'forkTitle_Original Topic',+ });+ expect(refreshTopicSpy).toHaveBeenCalled();+ expect(switchTopicSpy).toHaveBeenCalledWith(newTopicId);+ });++ it('should not fork when there is no active topic', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ useChatStore.setState({ activeTopicId: undefined });+ });++ const forkTopicSpy = vi.spyOn(topicService, 'forkTopic');++ await act(async () => {+ await result.current.forkTopic('msg-2');+ });++ expect(forkTopicSpy).not.toHaveBeenCalled();+ });+ });describe('autoRenameTopicTitle', () => {it('should auto-rename the topic title based on the messages', async () => {const { result } = renderHook(() => useChatStore());diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex 4f69aa508de..e4290994484 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -423,6 +423,39 @@ export class ChatTopicActionImpl {await switchTopic(newTopicId);};+ /**+ * Fork the active topic from one of its messages: copy the conversation+ * prefix (first message → `messageId`) into a separate new topic, then switch+ * to it. The source topic keeps its full history untouched.+ */+ forkTopic = async (messageId: string): Promise<string | undefined> => {+ const { activeTopicId, refreshTopic, switchTopic } = this.#get();+ if (!activeTopicId) return;++ const topic = topicSelectors.getTopicById(activeTopicId)(this.#get());++ const loadingToast = toast.loading(t('forkLoading', { ns: 'topic' }));++ try {+ const newTopicId = await topicService.forkTopic({+ id: activeTopicId,+ messageId,+ newTitle: t('forkTitle', { ns: 'topic', title: topic?.title ?? '' }),+ });++ await refreshTopic();+ await switchTopic(newTopicId);+ toast.success(t('forkSuccess', { ns: 'topic' }));++ return newTopicId;+ } catch (error) {+ console.error('[forkTopic] Failed to fork topic:', error);+ toast.error(t('forkFailed', { ns: 'topic' }));+ } finally {+ loadingToast.close();+ }+ };+importTopic = async (data: string): Promise<string | undefined> => {const { activeAgentId, activeGroupId, refreshTopic, switchTopic } = this.#get();