🤯 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(codex): edit and resend Codex user messages in a branched topic (#20467)
Nekoa02b8af7ccda
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 027b497ad7c..11c73fda2e0 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -29,6 +29,7 @@ import { TopicShareModel } from '@/database/models/topicShare';import { WorkspaceAuditLogModel } from '@/database/models/workspaceAuditLog';import { AgentMigrationRepo } from '@/database/repositories/agentMigration';import { HeteroSessionImporterRepo } from '@/database/repositories/heteroSessionImporter';+import { TopicRepository } from '@/database/repositories/topic';import { TopicImporterRepo } from '@/database/repositories/topicImporter';import { chatGroups } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -84,6 +85,7 @@ const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =>messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),topicImporterRepo: new TopicImporterRepo(ctx.serverDB, ctx.userId, wsId),topicModel: new TopicModel(ctx.serverDB, ctx.userId, wsId),+ topicRepo: new TopicRepository(ctx.serverDB, ctx.userId, wsId),topicShareModel: new TopicShareModel(ctx.serverDB, ctx.userId, wsId),trashService: new TrashService(ctx.serverDB, ctx.userId, wsId),},@@ -488,6 +490,33 @@ export const topicRouter = router({return data.topic.id;}),+ /**+ * Edit-and-resend for runtimes whose native history cannot be rewound+ * (Codex): copies the conversation up to one user message into a new topic+ * with the edited content. The source topic is left as it was.+ */+ branchTopicAtMessage: topicProcedure+ .use(withScopedPermission('topic:create'))+ .input(+ z.object({+ content: z.string(),+ editorData: z.record(z.string(), z.any()).nullish(),+ messageId: z.string(),+ title: z.string().optional(),+ topicId: z.string(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const { topicId, messageId, ...edit } = input;+ await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);+ // Same visitor guard as `cloneTopic` above.+ await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);+ const branch = await ctx.topicRepo.branchAtMessage(topicId, messageId, edit);+ if (!branch) throw new TRPCError({ code: 'NOT_FOUND', message: 'User message not found' });++ return { messageId: branch.messageId, topicId: branch.topic.id };+ }),+countTopics: topicProcedure.input(zdiff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 1885b91b6de..68438394326 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1481,6 +1481,12 @@"mention.category.workspaceAgents": "Workspace","mention.title": "Mention Members","messageAction.advanced": "Advanced",+ "messageAction.codexEdit.alreadySubmitting": "This edit is already being submitted",+ "messageAction.codexEdit.branchFailed": "Could not create the new topic. Your edit is kept; try sending again.",+ "messageAction.codexEdit.branchNotice": "Sends in a new topic; the original stays as it is. Files Codex already changed are not reverted.",+ "messageAction.codexEdit.cannotSubmit": "This conversation cannot accept an edited message right now",+ "messageAction.codexEdit.prepareFailed": "Could not load the new topic. Your edit is kept; try sending again.",+ "messageAction.codexEdit.sourceUnavailable": "The source conversation or agent is unavailable","messageAction.collapse": "Collapse Message","messageAction.continueGeneration": "Continue Generating","messageAction.continueGenerationUnsupported": "The current model doesn’t support continuing an assistant message. Try regenerating instead.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex f707dd81bfd..437a04cfb0b 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1481,6 +1481,12 @@"mention.category.workspaceAgents": "工作区","mention.title": "提及成员","messageAction.advanced": "高级操作",+ "messageAction.codexEdit.alreadySubmitting": "正在提交此次编辑,请稍候",+ "messageAction.codexEdit.branchFailed": "无法创建新话题。编辑内容已保留,请重新发送。",+ "messageAction.codexEdit.branchNotice": "将在新话题中发送,原对话保持不变。Codex 已修改的文件不会被还原。",+ "messageAction.codexEdit.cannotSubmit": "此对话暂时无法提交编辑后的消息",+ "messageAction.codexEdit.prepareFailed": "无法加载新话题。编辑内容已保留,请重新发送。",+ "messageAction.codexEdit.sourceUnavailable": "原对话或助手不可用","messageAction.collapse": "收起消息","messageAction.continueGeneration": "继续生成","messageAction.continueGenerationUnsupported": "当前模型不支持继续生成助理消息,请尝试重新生成。",diff --git a/packages/database/src/repositories/topic/__tests__/index.test.ts b/packages/database/src/repositories/topic/__tests__/index.test.tsnew file mode 100644index 00000000000..8252f79a7d4--- /dev/null+++ b/packages/database/src/repositories/topic/__tests__/index.test.ts@@ -0,0 +1,257 @@+// @vitest-environment node+import { eq, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { TopicModel } from '../../../models/topic';+import { files, messageGroups, messages, messagesFiles, topics, users } from '../../../schemas';+import { TopicRepository } from '../index';++const serverDB = await getTestDB();+const userId = 'topic-repository-test-user';+const otherUserId = 'topic-repository-test-other-user';+const topicModel = new TopicModel(serverDB, userId);+const topicRepo = new TopicRepository(serverDB, userId);++/** @example Edit/resend copies a scoped ancestry and leaves the source unchanged. */+describe('TopicRepository', () => {+ beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ });+ afterEach(async () => {+ await serverDB.delete(users);+ });+ /** @example The edit boundary preserves its scoped source and copied context. */+ describe('branchAtMessage', () => {+ const seedConversation = async () => {+ const topic = await topicModel.create({+ metadata: {+ heteroEffort: 'high',+ heteroSessionId: 'codex-thread-source',+ runningOperation: {+ operationId: 'op-source',+ assistantMessageId: 'br-a2',+ startedAt: '2026-10-07T00:00:00Z',+ },+ workingDirectory: '/repo',+ },+ title: 'source',+ });+ const row = (id: string, role: string, content: string, parentId?: string) => ({+ content,+ id,+ parentId,+ role,+ topicId: topic.id,+ userId,+ });+ await serverDB+ .insert(messages)+ .values([+ row('br-u0', 'user', 'first question'),+ { ...row('br-a0', 'assistant', '', 'br-u0'), tools: [{ id: 'c1' }, { id: 'c2' }] },+ row('br-a0-old', 'assistant', 'superseded attempt', 'br-u0'),+ row('br-t1', 'tool', 'result one', 'br-a0'),+ row('br-t2', 'tool', 'result two', 'br-a0'),+ row('br-a1', 'assistant', 'first answer', 'br-t1'),+ row('br-u1', 'user', 'typo prompt', 'br-a1'),+ row('br-a2', 'assistant', 'reply to typo', 'br-u1'),+ row('br-u2', 'user', 'later turn', 'br-a2'),+ ]);+ await serverDB.insert(files).values({+ fileType: 'image/png',+ id: 'br-file',+ name: 'shot.png',+ size: 1,+ url: 'files/shot.png',+ userId,+ });+ await serverDB+ .insert(messagesFiles)+ .values({ fileId: 'br-file', messageId: 'br-u1', userId });+ return topic;+ };++ /** @example The edit boundary preserves its scoped source and copied context. */+ it('copies only the ancestry of the edited message into a fresh-session topic', async () => {+ const topic = await seedConversation();++ const result = await topicRepo.branchAtMessage(topic.id, 'br-u1', {+ content: 'fixed prompt',+ title: 'fixed prompt',+ });++ const copied = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result!.topic.id));+ const byContent = new Map(copied.map((m) => [m.content, m]));+ // Later turns and the sibling attempt stay in the source.+ expect([...byContent.keys()].sort()).toEqual(+ ['', 'first answer', 'first question', 'fixed prompt', 'result one', 'result two'].sort(),+ );+ const edited = byContent.get('fixed prompt')!;+ expect(edited.id).toBe(result!.messageId);+ expect(edited.parentId).toBe(byContent.get('first answer')!.id);+ expect(byContent.get('result two')!.parentId).toBe(byContent.get('')!.id);++ const [link] = await serverDB+ .select()+ .from(messagesFiles)+ .where(eq(messagesFiles.messageId, edited.id));+ expect(link?.fileId).toBe('br-file');++ // Run configuration survives; the source's native session does not.+ // The marker is what lets the fresh local run replay the copied history.+ expect(result!.topic.metadata).toEqual({+ editedFrom: { messageId: 'br-u1', topicId: topic.id },+ heteroEffort: 'high',+ workingDirectory: '/repo',+ });+ expect(result!.topic.title).toBe('fixed prompt');++ const source = await serverDB.select().from(messages).where(eq(messages.topicId, topic.id));+ expect(source).toHaveLength(9);+ expect(source.find((m) => m.id === 'br-u1')?.content).toBe('typo prompt');+ });++ /** @example A retained nested message keeps its group ancestors; unrelated groups stay behind. */+ it('keeps the ancestor closure of referenced message groups', async () => {+ // ROOT CAUSE:+ // Pruning groups without directly attached messages deleted empty parents.+ // Their cascading foreign keys then deleted retained child groups/messages.+ const source = await topicModel.create({ title: 'nested groups' });+ await serverDB.insert(messageGroups).values([+ { id: 'nested-root', topicId: source.id, type: 'compression', userId },+ {+ id: 'nested-child',+ parentGroupId: 'nested-root',+ topicId: source.id,+ type: 'parallel',+ userId,+ },+ { id: 'unrelated-group', topicId: source.id, type: 'compression', userId },+ ]);+ await serverDB.insert(messages).values([+ {+ id: 'nested-history',+ content: 'retained history',+ messageGroupId: 'nested-child',+ role: 'assistant',+ topicId: source.id,+ userId,+ },+ {+ id: 'nested-edit',+ content: 'original',+ parentId: 'nested-history',+ role: 'user',+ topicId: source.id,+ userId,+ },+ ]);+ const result = await topicRepo.branchAtMessage(source.id, 'nested-edit', {+ content: 'edited',+ });+ const copied = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.topicId, result!.topic.id));+ /** @example Both the edited boundary and grouped ancestor survive the pruning transaction. */+ expect(copied.map((row) => row.content).sort()).toEqual(['edited', 'retained history']);+ const groups = await serverDB+ .select()+ .from(messageGroups)+ .where(eq(messageGroups.topicId, result!.topic.id));+ /** @example The empty root is retained, while the unrelated group is removed. */+ expect(groups).toHaveLength(2);+ const child = groups.find((group) => group.type === 'parallel')!;+ /** @example The copied child refers to its new root and the retained message refers to that child. */+ expect(child.parentGroupId).toBe(groups.find((group) => group.type === 'compression')!.id);+ /** @example Copying does not leave message references pointing into the source group tree. */+ expect(copied.find((row) => row.content === 'retained history')?.messageGroupId).toBe(+ child.id,+ );+ const originals = await serverDB+ .select()+ .from(messageGroups)+ .where(eq(messageGroups.topicId, source.id));+ /** @example Source groups are never pruned as a side effect of edit/resend. */+ expect(originals).toHaveLength(3);+ });++ /** @example An out-of-topic parent must never copy another user's message into this scope. */+ it('stops before an ancestor outside the authorized source topic', async () => {+ // ROOT CAUSE:+ // Adding an unknown parent ID before checking the source-topic map let+ // copyMessagesInDatabase read that message globally and change its owner.+ const foreign = await new TopicModel(serverDB, otherUserId).create({ title: 'private' });+ const source = await topicModel.create({ title: 'source' });+ await serverDB.insert(messages).values([+ {+ id: 'foreign-parent',+ content: 'private foreign content',+ role: 'user',+ topicId: foreign.id,+ userId: otherUserId,+ },+ {+ id: 'scoped-edit',+ content: 'original',+ role: 'user',+ parentId: 'foreign-parent',+ topicId: source.id,+ userId,+ },+ ]);+ const result = await topicRepo.branchAtMessage(source.id, 'scoped-edit', {+ content: 'edited',+ });+ const owned = await serverDB.select().from(messages).where(eq(messages.userId, userId));+ expect(owned.map((row) => row.content).sort()).toEqual(['edited', 'original']);+ expect(owned.find((row) => row.id === result!.messageId)?.parentId).toBeNull();+ const [original] = await serverDB+ .select()+ .from(messages)+ .where(eq(messages.id, 'foreign-parent'));+ expect(original.userId).toBe(otherUserId);+ expect(original.topicId).toBe(foreign.id);+ });++ /** @example A rejected edited message rolls back the new topic and every copied row. */+ it('rolls back the topic and copied conversation when the final edit fails', async () => {+ const source = await seedConversation();+ // ROOT CAUSE:+ // Edit/resend writes two aggregates. Its transaction belongs in the+ // repository; splitting the writes would leave a topic after an edit error.+ await serverDB.execute(+ sql`ALTER TABLE messages ADD CONSTRAINT t647_reject_edit CHECK (content IS DISTINCT FROM 'reject edit')`,+ );+ try {+ await expect(+ topicRepo.branchAtMessage(source.id, 'br-u1', { content: 'reject edit' }),+ ).rejects.toThrow();+ expect(await serverDB.select().from(topics)).toHaveLength(1);+ const rows = await serverDB.select().from(messages);+ expect(rows).toHaveLength(9);+ expect(rows.find((row) => row.id === 'br-u1')?.content).toBe('typo prompt');+ } finally {+ await serverDB.execute(sql`ALTER TABLE messages DROP CONSTRAINT t647_reject_edit`);+ }+ });++ /** @example The edit boundary preserves its scoped source and copied context. */+ it('returns undefined unless the target is an accessible user message', async () => {+ const topic = await seedConversation();++ expect(await topicRepo.branchAtMessage(topic.id, 'br-a1', { content: 'x' })).toBeUndefined();+ expect(await topicRepo.branchAtMessage('nope', 'br-u1', { content: 'x' })).toBeUndefined();+ expect(+ await new TopicRepository(serverDB, otherUserId).branchAtMessage(topic.id, 'br-u1', {+ content: 'x',+ }),+ ).toBeUndefined();+ });+ });+});diff --git a/packages/database/src/repositories/topic/index.ts b/packages/database/src/repositories/topic/index.tsnew file mode 100644index 00000000000..3da1dd303be--- /dev/null+++ b/packages/database/src/repositories/topic/index.ts@@ -0,0 +1,195 @@+import type { ChatTopicMetadata } from '@lobechat/types';+import { and, eq, sql } from 'drizzle-orm';++import { messageGroups, messages, topics } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { copyMessagesInDatabase } from '../../utils/copyMessagesInDatabase';+import { idGenerator } from '../../utils/idGenerator';+import { notShareVisitorTopic } from '../../utils/shareVisitor';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../../utils/workspace';++/**+ * Run configuration a branched topic keeps from its source. Everything else in+ * the metadata describes the source's own runs (native session ids, running+ * operation, summaries) and must not leak into the branch.+ */+const BRANCH_TOPIC_METADATA_KEYS = [+ 'boundDeviceId',+ 'heteroEffort',+ 'reasoningConfig',+ 'repos',+ 'workingDirectory',+ 'workingDirectoryConfig',+] as const satisfies readonly (keyof ChatTopicMetadata)[];+/**+ * Owns atomic writes spanning a topic and its copied conversation.+ *+ * Use when:+ * - Edit/resend must create a topic and message ancestry together.+ *+ * Expects:+ * - The caller's database and workspace scope.+ *+ * Returns:+ * - Scoped conversation operations with transaction-wide rollback.+ *+ * Call stack:+ *+ * topicRouter.branchTopicAtMessage+ * -> TopicRepository.branchAtMessage+ * -> {@link copyMessagesInDatabase}+ */+export class TopicRepository {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private ownership = () =>+ and(+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ notShareVisitorTopic(),+ );++ private messageOwnership = () =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, messages);++ /**+ * Copies the conversation that leads up to one user message into a new+ * topic, ending at that message with replacement content: edit-and-resend+ * for runtimes whose native history cannot be rewound (Codex).+ *+ * The branch holds the message's ancestor chain plus every tool result of+ * the assistants on it; later turns and sibling branches stay behind, and+ * the source topic is untouched. The topic keeps its owner, project and run+ * configuration but none of the source's native session state, so the next+ * run starts a fresh session. One transaction: a failure leaves nothing.+ *+ * Use when:+ * - Editing a Codex user message starts a fresh topic and native session.+ *+ * Expects:+ * - An authorized source topic and a user-message boundary in that topic.+ *+ * Returns:+ * - The new topic and edited message, or undefined for an inaccessible boundary.+ *+ * Call stack:+ *+ * topicRouter.branchTopicAtMessage+ * -> TopicRepository.branchAtMessage+ * -> {@link copyMessagesInDatabase}+ */+ branchAtMessage = async (+ topicId: string,+ messageId: string,+ edit: { content: string; editorData?: Record<string, unknown> | null; title?: string },+ ) => {+ return this.db.transaction(async (tx) => {+ const source = await tx.query.topics.findFirst({+ where: and(eq(topics.id, topicId), this.ownership()),+ });+ if (!source) return;++ const rows = await tx+ .select({ id: messages.id, parentId: messages.parentId, role: messages.role })+ .from(messages)+ .where(and(eq(messages.topicId, topicId), this.messageOwnership()));+ const byId = new Map(rows.map((row) => [row.id, row]));+ if (byId.get(messageId)?.role !== 'user') return;++ const keep = new Set<string>();+ let id: string | null | undefined = messageId;+ while (id && !keep.has(id)) {+ // Only IDs resolved inside the authorized source topic may reach the+ // copy map: a raw parent ID can refer to a different topic or owner.+ const ancestor = byId.get(id);+ if (!ancestor) break;+ keep.add(ancestor.id);+ id = ancestor.parentId;+ }+ for (const row of rows) {+ if (row.role === 'tool' && row.parentId && keep.has(row.parentId)) keep.add(row.id);+ }++ const metadata = Object.fromEntries(+ BRANCH_TOPIC_METADATA_KEYS.filter((key) => source.metadata?.[key] !== undefined).map(+ (key) => [key, source.metadata?.[key]],+ ),+ ) as ChatTopicMetadata;+ // Marks the copy so only this topic's fresh local run replays its history.+ metadata.editedFrom = { messageId, topicId };+ const [branch] = await tx+ .insert(topics)+ .values(+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ {+ agentId: source.agentId,+ groupId: source.groupId,+ id: idGenerator('topics'),+ metadata,+ model: source.model,+ projectId: source.projectId,+ projectWorkingDirectoryId: source.projectWorkingDirectoryId,+ provider: source.provider,+ sessionId: source.sessionId,+ title: edit.title || source.title,+ },+ ),+ )+ .returning();++ const messageIdPairs = [...keep].map(+ (id) => [id, idGenerator('messages')] as [string, string],+ );+ await copyMessagesInDatabase({+ agentIdExpr: sql`${messages.agentId}`,+ childScope: (table) =>+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, table),+ executor: tx,+ groupId: source.groupId,+ messageIdPairs,+ targetIdExpr: sql`${messages.targetId}`,+ targetUserId: this.userId,+ targetWorkspaceId: this.workspaceId ?? null,+ // Thread rows on the chain join the branch's main conversation.+ threadIdPairs: [],+ topicIdPairs: [[topicId, branch.id]],+ });+ // Keep referenced groups and their ancestor closure. Deleting an empty+ // parent would cascade into its retained descendants and their messages.+ // UNION deduplicates groups so a malformed cycle cannot recurse forever.+ await tx.execute(sql`+ with recursive retained_groups(id, parent_group_id) as (+ select ${messageGroups.id}, ${messageGroups.parentGroupId}+ from ${messageGroups}+ where ${messageGroups.topicId} = ${branch.id}+ and exists (+ select 1 from ${messages} where ${messages.messageGroupId} = ${messageGroups.id}+ )+ union+ select ${messageGroups.id}, ${messageGroups.parentGroupId}+ from ${messageGroups}+ join retained_groups on ${messageGroups.id} = retained_groups.parent_group_id+ where ${messageGroups.topicId} = ${branch.id}+ )+ delete from ${messageGroups}+ where ${messageGroups.topicId} = ${branch.id}+ and ${messageGroups.id} not in (select id from retained_groups)+ `);++ const branchMessageId = messageIdPairs.find(([sourceId]) => sourceId === messageId)![1];+ await tx+ .update(messages)+ .set({+ content: edit.content,+ ...(edit.editorData !== undefined && { editorData: edit.editorData }),+ })+ .where(eq(messages.id, branchMessageId));++ return { messageId: branchMessageId, topic: branch };+ });+ };+}diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ab9230fbcb3..ec872bd614e 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -848,6 +848,16 @@ export default {'mention.category.topics': 'Topics','mention.category.workspaceAgents': 'Workspace','mention.title': 'Mention Members',+ 'messageAction.codexEdit.alreadySubmitting': 'This edit is already being submitted',+ 'messageAction.codexEdit.branchFailed':+ 'Could not create the new topic. Your edit is kept; try sending again.',+ 'messageAction.codexEdit.branchNotice':+ 'Sends in a new topic; the original stays as it is. Files Codex already changed are not reverted.',+ 'messageAction.codexEdit.cannotSubmit':+ 'This conversation cannot accept an edited message right now',+ 'messageAction.codexEdit.prepareFailed':+ 'Could not load the new topic. Your edit is kept; try sending again.',+ 'messageAction.codexEdit.sourceUnavailable': 'The source conversation or agent is unavailable','messageAction.collapse': 'Collapse Message','messageAction.continueGeneration': 'Continue Generating','messageAction.continueGenerationUnsupported':diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex 1c541f1a52e..59bb8662ad3 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -124,6 +124,14 @@ export interface ChatTopicMetadata {bot?: ChatTopicBotContext;boundDeviceId?: string;cronJobId?: string;+ /**+ * Set on a topic created by editing and resending a user message of a+ * runtime whose native history cannot be rewound (Codex). The topic holds a+ * copy of the source ancestry but no native session, so a fresh local run+ * replays the copied history as `<previous_conversation>`. Ordinary topics+ * never carry it, so their fresh sessions keep starting without replay.+ */+ editedFrom?: { messageId: string; topicId: string };/*** The agent whose Profile page this Agent Builder conversation was started* from (mirrors `ExecAgentAppContext.editingAgentId`).diff --git a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx b/src/features/Conversation/ChatItem/components/MessageContent/index.tsxindex 26f19163111..a5d803b4c30 100644--- a/src/features/Conversation/ChatItem/components/MessageContent/index.tsx+++ b/src/features/Conversation/ChatItem/components/MessageContent/index.tsx@@ -5,15 +5,12 @@ import { type ReactNode } from 'react';import { memo, useCallback, useEffect, useRef } from 'react';import { useTranslation } from 'react-i18next';-import {- dataSelectors,- messageStateSelectors,- useConversationStore,-} from '@/features/Conversation/store';+import { dataSelectors, useConversationStore } from '@/features/Conversation/store';import { openEditorModal } from '@/features/EditorModal';import { usePermission } from '@/hooks/usePermission';import { type ChatItemProps } from '../../type';+import { useEditConfirmation } from './useEditConfirmation';export const MSG_CONTENT_CLASSNAME = 'msg_content_flag';@@ -61,30 +58,12 @@ const MessageContent = memo<MessageContentProps>(className,variant,}) => {- const [toggleMessageEditing, updateMessageContent, regenerateUserMessage] =- useConversationStore((s) => [- s.toggleMessageEditing,- s.updateMessageContent,- s.regenerateUserMessage,- ]);+ const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);const editorData = useConversationStore((s) => dataSelectors.getDisplayMessageById(id)(s)?.editorData,);- // Short-circuit on non-editing rows so streaming token updates stay O(1) per row- // instead of each row running `findLast` on displayMessages (O(N²) per update).- // Use isInputLoading (covers sendMessage + AI runtime) rather than isAIGenerating,- // otherwise the initial send phase — where the persisted id has just swapped in- // under an optimistic tmp_* op — would flip to Send and kick off a duplicate- // regenerate for the same prompt.- const shouldSendOnConfirm = useConversationStore((s) => {- if (!editing) return false;- if (dataSelectors.getDisplayMessageById(id)(s)?.role !== 'user') return false;- if (s.displayMessages.findLast((m) => m.role === 'user')?.id !== id) return false;- return !messageStateSelectors.isInputLoading(s);- });-const { t } = useTranslation('common');const { allowed: canCreate } = usePermission('create_content');const { allowed: canEdit } = usePermission('edit_own_content');@@ -97,6 +76,14 @@ const MessageContent = memo<MessageContentProps>([canEdit, id, toggleMessageEditing],);+ const { notice, onConfirm, shouldSendOnConfirm } = useEditConfirmation({+ canCreate,+ canEdit,+ editing,+ id,+ onEditingChange,+ });+// Held in a ref rather than in the effect's deps: the editor snapshots the// message when it opens, so a re-render (a streaming token, a permission// refresh) must not tear down and reopen a modal the user is typing in.@@ -104,23 +91,11 @@ const MessageContent = memo<MessageContentProps>(openEditorRef.current = () =>openEditorModal({editorData,+ notice,okText: shouldSendOnConfirm ? t('send') : t('save'),value: message ? String(message) : '',onClose: () => onEditingChange(false),- onConfirm: async (value, newEditorData) => {- if (!canEdit) return;- onEditingChange(false);- // updateMessageContent does an optimistic state update synchronously before- // awaiting the DB round trip. Kick off regenerate in parallel so the old- // assistant reply is replaced by switchMessageBranch without waiting for persistence.- const save = updateMessageContent(id, value, {- editorData: newEditorData as Record<string, any> | undefined,- });- if (canCreate && shouldSendOnConfirm) {- await regenerateUserMessage(id);- }- await save;- },+ onConfirm: (value, data) => onConfirm(value, data as Record<string, unknown> | undefined),});useEffect(() => {diff --git a/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.ts b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.tsnew file mode 100644index 00000000000..791e6a71e01--- /dev/null+++ b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.test.ts@@ -0,0 +1,140 @@+import { act, renderHook } from '@testing-library/react';+import { createElement, type PropsWithChildren } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createStore, messageStateSelectors, Provider } from '@/features/Conversation/store';+import { useCanEditCodexMessage } from '@/hooks/useCanEditCodexMessage';+import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';++import { useEditConfirmation } from './useEditConfirmation';++vi.mock('@/hooks/useCanEditCodexMessage', () => ({ useCanEditCodexMessage: vi.fn(() => true) }));++/** @example The same editor routes historical Codex prompts to edit-and-resend. */+describe('message edit confirmation', () => {+ afterEach(() => vi.restoreAllMocks());++ const setup = (+ provider: 'codex' | 'claude-code' = 'codex',+ canEditCodex = true,+ globalProvider = provider,+ ) => {+ vi.mocked(useCanEditCodexMessage).mockReturnValue(canEditCodex);+ vi.spyOn(agentSelectors, 'currentAgentHeterogeneousProviderType').mockReturnValue(+ globalProvider,+ );+ vi.spyOn(agentByIdSelectors, 'getAgencyConfigById').mockImplementation(+ (id) => () => (id === 'agent' ? { heterogeneousProvider: { type: provider } } : undefined),+ );+ const store = createStore({+ context: { agentId: 'agent', topicId: 'topic', threadId: null },+ initialMessages: ['u1', 'u2'].map((id, index) => ({+ id,+ content: id,+ role: 'user',+ createdAt: index,+ updatedAt: index,+ })),+ });+ const save = vi.spyOn(store.getState(), 'updateMessageContent').mockResolvedValue();+ const resend = vi.spyOn(store.getState(), 'regenerateUserMessage').mockResolvedValue();+ const close = vi.fn();+ const wrapper = ({ children }: PropsWithChildren) =>+ createElement(Provider, { children, createStore: () => store });+ const hook = renderHook(+ () =>+ useEditConfirmation({+ id: 'u1',+ editing: true,+ canEdit: true,+ canCreate: true,+ onEditingChange: close,+ }),+ { wrapper },+ );+ return { ...hook, close, resend, save };+ };++ /** @example Editing an older Codex user turn sends its replacement with editor attachments. */+ it('submits a historical Codex edit through the context-aware rerun path', async () => {+ const { result, resend, save } = setup();+ const editorData = { attachment: 'image-1' };+ /** @example Historical Codex messages show Send rather than save-only behavior. */+ expect(result.current.shouldSendOnConfirm).toBe(true);+ await act(() => result.current.onConfirm('edited', editorData));+ /** @example Persistence and rerun are owned by one operation, with the replacement data. */+ expect(resend).toHaveBeenCalledWith('u1', {+ content: 'edited',+ editorData,+ onAccepted: expect.any(Function),+ });+ /** @example The editor cannot race a separate save against Codex execution. */+ expect(save).not.toHaveBeenCalled();+ });++ /** @example An isolated editor follows its own agent when global selection differs. */+ it('routes the conversation Codex agent to resend when the global agent is ordinary', async () => {+ // ROOT CAUSE:+ // The confirmation used global agent selection although the provider owns a+ // captured agent id. Selecting another agent could classify this row as a save.+ const { result, resend, save } = setup('codex', true, 'claude-code');+ await act(() => result.current.onConfirm('isolated edit'));+ /** @example The source row is preserved and replacement creation owns persistence. */+ expect(save).not.toHaveBeenCalled();+ /** @example Dispatch uses the editor's conversation ownership. */+ expect(resend).toHaveBeenCalledWith(+ 'u1',+ expect.objectContaining({ content: 'isolated edit' }),+ );+ });++ /** @example An ordinary conversation stays save-only regardless of global Codex selection. */+ it('keeps an ordinary conversation editable when the global agent is Codex', async () => {+ const { result, resend, save } = setup('claude-code', false, 'codex');+ await act(() => result.current.onConfirm('ordinary edit'));+ /** @example The ordinary historical row keeps its existing save behavior. */+ expect(save).toHaveBeenCalledWith('u1', 'ordinary edit', { editorData: undefined });+ /** @example A different global provider cannot redirect the row into Codex. */+ expect(resend).not.toHaveBeenCalled();+ });++ /** @example A failed save leaves the same edit draft open for correction and retry. */+ it('preserves the editor when submitting a Codex edit fails', async () => {+ // ROOT CAUSE:+ //+ // Closing editing state before the save resolved destroyed the modal and draft.+ // Dismissal belongs after persistence accepts the replacement, not before it.+ const { result, resend, close } = setup();+ resend.mockRejectedValueOnce(new Error('save unavailable'));+ /** @example The caller sees the real failure. */+ await expect(result.current.onConfirm('UNSAVED-DRAFT')).rejects.toThrow('save unavailable');+ /** @example No close callback discards the unsaved draft. */+ expect(close).not.toHaveBeenCalled();+ });++ /** @example Other heterogeneous agents keep their existing save-only historical edit behavior. */+ it('preserves ordinary historical message editing', async () => {+ const { result, resend, save } = setup('claude-code');+ /** @example A non-Codex historical message continues to offer Save. */+ expect(result.current.shouldSendOnConfirm).toBe(false);+ await act(() => result.current.onConfirm('edited'));+ /** @example The existing editor save contract remains intact. */+ expect(save).toHaveBeenCalledWith('u1', 'edited', { editorData: undefined });+ /** @example Historical saves do not acquire new regenerate behavior on other runtimes. */+ expect(resend).not.toHaveBeenCalled();+ });++ /** @example A running Codex conversation cannot be changed underneath its native session. */+ it('does not save or resend a Codex edit while input is loading', async () => {+ vi.spyOn(messageStateSelectors, 'isInputLoading').mockReturnValue(true);+ const { result, resend, save } = setup();+ /** @example Rejecting keeps the shared editor modal open. */+ await expect(result.current.onConfirm('edited')).rejects.toThrow(+ 'messageAction.codexEdit.cannotSubmit',+ );+ /** @example Busy state blocks the runtime call. */+ expect(resend).not.toHaveBeenCalled();+ /** @example Busy state also blocks a misleading save without a rerun. */+ expect(save).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.ts b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.tsnew file mode 100644index 00000000000..c44329618e7--- /dev/null+++ b/src/features/Conversation/ChatItem/components/MessageContent/useEditConfirmation.ts@@ -0,0 +1,147 @@+import { toast } from '@lobehub/ui/base-ui';+import { useCallback, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import {+ dataSelectors,+ messageStateSelectors,+ useConversationStore,+} from '@/features/Conversation/store';+import type { CodexMessageEdit } from '@/features/Conversation/store/slices/generation/action';+import { useCanEditCodexMessage } from '@/hooks/useCanEditCodexMessage';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';++/** The permissions and message identity captured by the message editor. */+interface EditConfirmationOptions {+ /** Whether the user may start a new run. */+ canCreate: boolean;+ /** Whether the user may modify the message. */+ canEdit: boolean;+ /** Whether this row owns the open editor. */+ editing?: boolean;+ /** Persisted message id. */+ id: string;+ /** Closes the editor after an accepted submission. */+ onEditingChange: (editing: boolean) => void;+}++/**+ * Selects save or edit-and-resend behavior for the message editor.+ *+ * Use when:+ * - Confirming an edit of a user or assistant message.+ *+ * Expects:+ * - The owning conversation provider and current content permissions.+ *+ * Returns:+ * - A submit callback, whether the editor should offer Send, and a notice for Codex resends.+ *+ * Call stack:+ * MessageContent+ * -> useEditConfirmation+ * -> regenerateUserMessage (Codex edit)+ * -> updateMessageContent (ordinary edit)+ */+export const useEditConfirmation = ({+ canCreate,+ canEdit,+ editing,+ id,+ onEditingChange,+}: EditConfirmationOptions) => {+ const { t } = useTranslation('chat');+ const [updateMessageContent, regenerateUserMessage] = useConversationStore((s) => [+ s.updateMessageContent,+ s.regenerateUserMessage,+ ]);+ const [agentId, topicId] = useConversationStore((s) => [s.context.agentId, s.context.topicId]);+ const canEditCodex = useCanEditCodexMessage(agentId ?? undefined, topicId);+ const isCodex = useAgentStore((s) =>+ agentId+ ? agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type === 'codex'+ : false,+ );+ const isUserMessage = useConversationStore(+ (s) => !!editing && dataSelectors.getDisplayMessageById(id)(s)?.role === 'user',+ );++ // Short-circuit on non-editing rows so streaming token updates stay O(1) per row+ // instead of each row running `findLast` on displayMessages (O(N²) per update).+ // Use isInputLoading (covers sendMessage + AI runtime) rather than isAIGenerating,+ // otherwise the initial send phase — where the persisted id has just swapped in+ // under an optimistic tmp_* op — would flip to Send and kick off a duplicate+ // regenerate for the same prompt.+ const shouldSendOnConfirm = useConversationStore((s) => {+ if (!editing || !isUserMessage || (isCodex && !canEditCodex)) return false;+ if (!isCodex && s.displayMessages.findLast((m) => m.role === 'user')?.id !== id) return false;+ return !messageStateSelectors.isInputLoading(s);+ });++ const submitting = useRef(false);+ // Keep the unsent destination with this editor so a failed preparation can+ // retry without creating another topic. Closing the editor ends that attempt.+ const pendingEdit = useRef<CodexMessageEdit | undefined>(undefined);+ if (!editing) pendingEdit.current = undefined;+ const onConfirm = useCallback(+ async (content: string, editorData?: Record<string, unknown>) => {+ if (!canEdit) return;+ if (isCodex && isUserMessage) {+ if (!canEditCodex || !canCreate || !shouldSendOnConfirm) {+ const error = new Error(t('messageAction.codexEdit.cannotSubmit'));+ toast.error(error.message);+ throw error;+ }+ if (submitting.current) {+ const error = new Error(t('messageAction.codexEdit.alreadySubmitting'));+ toast.error(error.message);+ throw error;+ }+ submitting.current = true;+ try {+ const edit = pendingEdit.current ?? { content };+ Object.assign(edit, {+ content,+ editorData,+ onAccepted: () => onEditingChange(false),+ });+ pendingEdit.current = edit;+ await regenerateUserMessage(id, edit);+ } catch (error) {+ toast.error(error instanceof Error ? error.message : String(error));+ throw error;+ } finally {+ submitting.current = false;+ }+ return;+ }+ onEditingChange(false);+ // updateMessageContent does an optimistic state update synchronously before+ // awaiting the DB round trip. Kick off regenerate in parallel so the old+ // assistant reply is replaced by switchMessageBranch without waiting for persistence.+ const save = updateMessageContent(id, content, { editorData });+ if (canCreate && shouldSendOnConfirm) await regenerateUserMessage(id);+ await save;+ },+ [+ canCreate,+ canEdit,+ canEditCodex,+ id,+ isCodex,+ isUserMessage,+ onEditingChange,+ regenerateUserMessage,+ shouldSendOnConfirm,+ updateMessageContent,+ t,+ ],+ );++ // Codex resends into a new topic and cannot rewind the files it already changed.+ const notice =+ isCodex && shouldSendOnConfirm ? t('messageAction.codexEdit.branchNotice') : undefined;++ return { notice, onConfirm, shouldSendOnConfirm };+};diff --git a/src/features/Conversation/hooks/useDoubleClickEdit.test.ts b/src/features/Conversation/hooks/useDoubleClickEdit.test.tsnew file mode 100644index 00000000000..5fa5b12763d--- /dev/null+++ b/src/features/Conversation/hooks/useDoubleClickEdit.test.ts@@ -0,0 +1,69 @@+import { fireEvent, render } from '@testing-library/react';+import { createElement } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createStore, Provider } from '@/features/Conversation/store';+import { useCanEditCodexMessage } from '@/hooks/useCanEditCodexMessage';+import { usePermission } from '@/hooks/usePermission';+import { agentByIdSelectors } from '@/store/agent/selectors';++import { useDoubleClickEdit } from './useDoubleClickEdit';++vi.mock('@/hooks/useCanEditCodexMessage', () => ({ useCanEditCodexMessage: vi.fn() }));+vi.mock('@/hooks/usePermission', () => ({ usePermission: vi.fn(() => ({ allowed: true })) }));++/** @example Alt-double-click follows the same Codex user-edit eligibility as the toolbar. */+describe('Codex user edit shortcut', () => {+ beforeEach(() => vi.mocked(usePermission).mockReturnValue({ allowed: true }));+ afterEach(() => vi.restoreAllMocks());++ const setup = (provider: 'codex' | 'claude-code', supported: boolean, role = 'user') => {+ vi.mocked(useCanEditCodexMessage).mockReturnValue(supported);+ vi.spyOn(agentByIdSelectors, 'getAgencyConfigById').mockImplementation(+ (id) => () => (id === 'owner' ? { heterogeneousProvider: { type: provider } } : undefined),+ );+ const store = createStore({+ context: { agentId: 'owner', topicId: 'source', threadId: null },+ });+ const toggle = vi.spyOn(store.getState(), 'toggleMessageEditing');+ const Bubble = () =>+ createElement('div', {+ 'data-testid': 'message',+ 'onDoubleClick': useDoubleClickEdit({ id: 'message', role, error: undefined }),+ });+ const view = render(+ createElement(Provider, { children: createElement(Bubble), createStore: () => store }),+ );+ return { bubble: view.getByTestId('message'), toggle };+ };++ /** @example A Codex runtime that cannot resend must not open a Save-only dead end. */+ it('blocks unsupported Codex user editing before opening the editor', () => {+ // ROOT CAUSE:+ // The toolbar checked effective runtime, but Alt-double-click only checked+ // role and content permission. It opened an editor whose new Codex submit+ // path always rejected. The shortcut must apply the same runtime gate.+ const { bubble, toggle } = setup('codex', false);+ fireEvent.doubleClick(bubble, { altKey: true });+ /** @example Unsupported Codex user rows keep the editor closed. */+ expect(toggle).not.toHaveBeenCalled();+ /** @example Eligibility belongs to the captured conversation, not global selection. */+ expect(useCanEditCodexMessage).toHaveBeenCalledWith('owner', 'source');+ });++ /** @example A local Codex user prompt still opens Edit with Alt-double-click. */+ it('opens supported Codex user editing', () => {+ const { bubble, toggle } = setup('codex', true);+ fireEvent.doubleClick(bubble, { altKey: true });+ /** @example The existing editor owns the selected historical message. */+ expect(toggle).toHaveBeenCalledWith('message', true);+ });++ /** @example Ordinary messages keep their existing shortcut behavior. */+ it('keeps non-Codex editing available', () => {+ const { bubble, toggle } = setup('claude-code', false);+ fireEvent.doubleClick(bubble, { altKey: true });+ /** @example The Codex runtime gate does not disable ordinary editing. */+ expect(toggle).toHaveBeenCalledWith('message', true);+ });+});diff --git a/src/features/Conversation/hooks/useDoubleClickEdit.ts b/src/features/Conversation/hooks/useDoubleClickEdit.tsindex 9120cdd40cd..47591403aad 100644--- a/src/features/Conversation/hooks/useDoubleClickEdit.ts+++ b/src/features/Conversation/hooks/useDoubleClickEdit.ts@@ -1,7 +1,10 @@import { type MouseEventHandler } from 'react';import { useCallback } from 'react';+import { useCanEditCodexMessage } from '@/hooks/useCanEditCodexMessage';import { usePermission } from '@/hooks/usePermission';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useConversationStore } from '../store';@@ -12,6 +15,18 @@ interface UseDoubleClickEditProps {role: string;}+/**+ * Opens the message editor through the Alt-double-click shortcut.+ *+ * Use when:+ * - Attaching the existing edit shortcut to a conversation message.+ *+ * Expects:+ * - The owning conversation provider and current content permissions.+ *+ * Returns:+ * - A handler that opens supported edits and ignores unavailable user edits.+ */export const useDoubleClickEdit = ({disableEditing,role,@@ -20,11 +35,19 @@ export const useDoubleClickEdit = ({}: UseDoubleClickEditProps) => {const { allowed: canEdit } = usePermission('edit_own_content');const toggleMessageEditing = useConversationStore((s) => s.toggleMessageEditing);+ const [agentId, topicId] = useConversationStore((s) => [s.context.agentId, s.context.topicId]);+ const canEditCodex = useCanEditCodexMessage(agentId ?? undefined, topicId);+ const isCodex = useAgentStore((s) =>+ agentId+ ? agentByIdSelectors.getAgencyConfigById(agentId)(s)?.heterogeneousProvider?.type === 'codex'+ : false,+ );return useCallback<MouseEventHandler<HTMLDivElement>>((e) => {if (!canEdit ||+ (role === 'user' && isCodex && !canEditCodex) ||disableEditing ||error ||id === 'default' ||@@ -35,6 +58,6 @@ export const useDoubleClickEdit = ({toggleMessageEditing(id, true);},- [role, canEdit, disableEditing, error, toggleMessageEditing, id],+ [role, canEdit, canEditCodex, isCodex, disableEditing, error, toggleMessageEditing, id],);};diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 6c2c16bf69b..80f5c47f63a 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -12,9 +12,12 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type ConversationContext, type ConversationHooks } from '../../../types';import { createStore } from '../../index';+import type { CodexMessageEdit } from './action';import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';-vi.mock('@/services/topic', () => ({ topicService: { cancelRateLimitContinuation: vi.fn() } }));+vi.mock('@/services/topic', () => ({+ topicService: { branchTopicAtMessage: vi.fn(), cancelRateLimitContinuation: vi.fn() },+}));// Mock useChatStoreconst mockCancelOperations = vi.fn();@@ -1911,6 +1914,160 @@ describe('Generation Actions', () => {);});+ it.runIf(providerType === 'codex')(+ 'resends an edit through the branched topic, leaving the source session alone',+ async () => {+ const branchContext = { agentId: 'session-1', threadId: null, topicId: 'branch-topic' };+ const branchRows = [{ content: 'fixed prompt', id: 'branch-user', role: 'user' }];+ const mockSwitchTopic = vi.fn();+ await setupHeteroChatStore({+ dbMessagesMap: { [messageMapKey(branchContext)]: branchRows },+ messagesMap: { [messageMapKey(branchContext)]: branchRows },+ prefetchMessages: vi.fn(),+ refreshTopic: vi.fn(),+ switchTopic: mockSwitchTopic,+ topicDataMap: {+ test: { items: [{ id: 'topic-1', metadata: { heteroSessionId: 'source-thread' } }] },+ },+ });+ vi.mocked(topicService.branchTopicAtMessage).mockResolvedValue({+ messageId: 'branch-user',+ topicId: 'branch-topic',+ });+ const store = createStore({+ context: { agentId: 'session-1', threadId: null, topicId: 'topic-1' },+ });+ store.setState({+ displayMessages: [{ content: 'typo prompt', id: 'msg-1', role: 'user' }],+ } as any);+ const onAccepted = vi.fn();++ await store+ .getState()+ .regenerateUserMessage('msg-1', { content: 'fixed prompt', onAccepted });+ await vi.waitFor(() => expect(executeHeterogeneousAgentSpy).toHaveBeenCalled());++ expect(topicService.branchTopicAtMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: 'fixed prompt',+ messageId: 'msg-1',+ topicId: 'topic-1',+ }),+ );+ expect(onAccepted).toHaveBeenCalled();+ expect(mockSwitchTopic).toHaveBeenCalledWith(+ 'branch-topic',+ expect.objectContaining({ onlyIfActiveTopicIn: ['topic-1'] }),+ );+ expect(createMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({ parentId: 'branch-user', topicId: 'branch-topic' }),+ );+ expect(executeHeterogeneousAgentSpy).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({+ context: expect.objectContaining({ topicId: 'branch-topic' }),+ message: 'fixed prompt',+ resumeSessionId: undefined,+ }),+ );+ },+ );++ /** @example A failed destination fetch keeps an isolated editor open and retryable. */+ it.runIf(providerType === 'codex')(+ 'keeps the edit until the copied message is available for resend',+ async () => {+ const target = { agentId: 'session-1', threadId: null, topicId: 'branch-topic' };+ const onTopicCreated = vi.fn();+ const onAccepted = vi.fn();+ const edit: CodexMessageEdit = { content: 'fixed prompt', onAccepted };+ const switchTopic = vi.fn();+ await setupHeteroChatStore({+ dbMessagesMap: {},+ messagesMap: {},+ prefetchMessages: vi.fn().mockResolvedValue(undefined),+ refreshTopic: vi.fn(),+ switchTopic,+ });+ vi.mocked(topicService.branchTopicAtMessage).mockResolvedValue({+ messageId: 'branch-user',+ topicId: 'branch-topic',+ });+ const store = createStore({+ context: {+ agentId: 'session-1',+ isolatedTopic: true,+ threadId: null,+ topicId: 'topic-1',+ },+ hooks: { onTopicCreated },+ });+ // ROOT CAUSE:+ // Background prefetch swallows network errors; an empty destination made resend silently+ // return after onAccepted closed the editor. Acceptance must wait for the copied message.+ await expect(store.getState().regenerateUserMessage('msg-1', edit)).rejects.toThrow(+ 'Could not load the new topic. Your edit is kept; try sending again.',+ );+ /** @example Neither host navigation nor draft acceptance happens on incomplete context. */+ expect(onAccepted).not.toHaveBeenCalled();+ expect(onTopicCreated).not.toHaveBeenCalled();+ expect(switchTopic).not.toHaveBeenCalled();+ expect(executeHeterogeneousAgentSpy).not.toHaveBeenCalled();++ const { useChatStore } = await import('@/store/chat');+ // The same editor may amend its draft before retrying the failed preparation.+ vi.spyOn(messageService, 'updateMessage').mockResolvedValue({ success: true });+ edit.content = 'amended prompt';+ const rows = [{ content: 'amended prompt', id: 'branch-user', role: 'user' as const }];+ const state = useChatStore.getState();+ vi.mocked(state.prefetchMessages).mockImplementation(async () => {+ state.messagesMap[messageMapKey(target)] = rows;+ state.dbMessagesMap[messageMapKey(target)] = rows;+ });+ await store.getState().regenerateUserMessage('msg-1', edit);+ /** @example A retry dispatches the edited prompt once the destination fetch succeeds. */+ await vi.waitFor(() => expect(executeHeterogeneousAgentSpy).toHaveBeenCalledTimes(1));+ /** @example Retrying preparation reuses the already-created destination. */+ expect(topicService.branchTopicAtMessage).toHaveBeenCalledTimes(1);+ /** @example Only the already-created destination receives the amended draft. */+ expect(messageService.updateMessage).toHaveBeenCalledWith('branch-user', {+ content: 'amended prompt',+ editorData: undefined,+ });+ expect(executeHeterogeneousAgentSpy).toHaveBeenCalledWith(+ expect.any(Function),+ expect.objectContaining({ message: 'amended prompt' }),+ );+ expect(onAccepted).toHaveBeenCalledTimes(1);+ expect(onTopicCreated).toHaveBeenCalledWith('branch-topic');+ },+ );++ it.runIf(providerType === 'codex')(+ 'reports a friendly error and keeps the draft when the branch cannot be created',+ async () => {+ await setupHeteroChatStore();+ vi.mocked(topicService.branchTopicAtMessage).mockRejectedValue(new Error('offline'));+ const store = createStore({+ context: { agentId: 'session-1', threadId: null, topicId: 'topic-1' },+ });+ const onAccepted = vi.fn();++ const result = store+ .getState()+ .regenerateUserMessage('msg-1', { content: 'fixed prompt', onAccepted });++ // The editor toasts this message, so it must not be the raw transport error.+ await expect(result).rejects.toThrow(+ 'Could not create the new topic. Your edit is kept; try sending again.',+ );+ await expect(result).rejects.toMatchObject({ cause: new Error('offline') });++ expect(onAccepted).not.toHaveBeenCalled();+ expect(executeHeterogeneousAgentSpy).not.toHaveBeenCalled();+ },+ );+it('preserves a legacy subscription resume', async () => {await setupHeteroChatStore({topicDataMap: {diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex 17b391321f7..39bcd8d5680 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -573,6 +573,128 @@ const regenerateUserMessageFromSource = async (}};+/** A replacement prompt for an edited Codex user message. */+export interface CodexMessageEdit {+ content: string;+ /** Updated rich editor state; omitted keeps the original message's state. */+ editorData?: Record<string, unknown>;+ /** Called once the copied message is ready, before the replacement run starts. */+ onAccepted?: () => void;+ /** Unsent destination retained by the open editor after a preparation failure. */+ preparedTopic?: {+ /** Last prompt persisted in the copied message. */+ content: string;+ /** Serialized editor state last persisted in the copied message. */+ editorData?: string;+ /** Destination user message, never the source message. */+ messageId: string;+ /** Source boundary used to prevent reuse by another editor. */+ sourceMessageId: string;+ /** Source conversation used to prevent cross-topic reuse. */+ sourceTopicId: string;+ /** Destination created for this editor but not yet dispatched. */+ topicId: string;+ };+}++/**+ * Edit-and-resend for a Codex user message. Codex cannot rewind its native+ * thread, so the server branches the conversation up to the message into a new+ * topic carrying the edited prompt, and that topic's ordinary regenerate path+ * runs it in a fresh session (the executor replays the copied history). The+ * source topic and its native session are left untouched.+ *+ * Rejects until the copied message is ready so the editor keeps the draft;+ * after acceptance, the run reports its own failures.+ */+const editCodexUserMessage = async (+ messageId: string,+ source: RegenerateUserMessageSource,+ edit: CodexMessageEdit,+) => {+ const { context, hooks } = source;+ const chatStore = useChatStore.getState();+ if (!context.agentId || !context.topicId)+ throw new Error(t('messageAction.codexEdit.sourceUnavailable', { ns: 'chat' }));++ let branch = edit.preparedTopic;+ if (branch?.sourceMessageId !== messageId || branch.sourceTopicId !== context.topicId) {+ const created = await topicService+ .branchTopicAtMessage({+ content: edit.content,+ editorData: edit.editorData,+ messageId,+ title: edit.content.slice(0, 80),+ topicId: context.topicId,+ })+ .catch((error: unknown) => {+ // Transport/parse errors are not user-facing; the editor toasts this and keeps the draft.+ console.error('[Codex edit] Could not create the branch topic:', error);+ throw new Error(t('messageAction.codexEdit.branchFailed', { ns: 'chat' }), {+ cause: error,+ });+ });+ branch = {+ ...created,+ content: edit.content,+ editorData: JSON.stringify(edit.editorData),+ sourceMessageId: messageId,+ sourceTopicId: context.topicId,+ };+ edit.preparedTopic = branch;+ }+ const target: ConversationContext = { ...context, threadId: null, topicId: branch.topicId };+ const key = messageMapKey(target);+ if (branch.content !== edit.content || branch.editorData !== JSON.stringify(edit.editorData)) {+ // The draft can change after a failed read. Update only its unsent copy,+ // then refresh that bucket before accepting; the source row stays untouched.+ await messageService.updateMessage(branch.messageId, {+ content: edit.content,+ editorData: edit.editorData,+ });+ await chatStore.refreshMessages(target);+ branch.content = edit.content;+ branch.editorData = JSON.stringify(edit.editorData);+ }+ await chatStore.prefetchMessages(target);+ const displayMessages = useChatStore.getState().messagesMap[key] ?? [];+ // Background warming may swallow a failed fetch or skip an in-flight request.+ // Keep the source editor until the copied user message can actually start a run.+ if (+ !displayMessages.some(+ (message) =>+ message.id === branch.messageId &&+ message.role === 'user' &&+ message.content === edit.content,+ )+ ) {+ throw new Error(t('messageAction.codexEdit.prepareFailed', { ns: 'chat' }));+ }+ edit.preparedTopic = undefined;+ edit.onAccepted?.();++ await chatStore.refreshTopic();+ if (context.isolatedTopic) {+ // Embedded hosts own their visible topic independently of global navigation.+ hooks.onTopicCreated?.(branch.topicId);+ } else {+ await chatStore.switchTopic(branch.topicId, {+ onlyIfActiveAgentId: context.agentId,+ onlyIfActiveTopicIn: [context.topicId],+ });+ }++ // The run outlives the editor; it surfaces its own errors.+ void regenerateUserMessageFromSource(branch.messageId, {+ context: target,+ displayMessages,+ hooks,+ readDbMessages: () => useChatStore.getState().dbMessagesMap[key] ?? [],+ }).catch((error: unknown) => {+ toast.error(error instanceof Error ? error.message : String(error));+ });+};+/*** Generation Actions*@@ -685,9 +807,10 @@ export interface GenerationAction {regenerateAssistantMessage: (messageId: string) => Promise<void>;/**- * Regenerate a user message+ * Regenerate a user message. With `edit`, resend an edited Codex prompt in a+ * branched topic instead (see {@link editCodexUserMessage}).*/- regenerateUserMessage: (messageId: string) => Promise<void>;+ regenerateUserMessage: (messageId: string, edit?: CodexMessageEdit) => Promise<void>;/*** Resend a thread message@@ -1301,8 +1424,11 @@ export const generationSlice: StateCreator<await get().regenerateUserMessage(userId);},- regenerateUserMessage: async (messageId: string) =>- regenerateUserMessageFromSource(messageId, captureRegenerateUserMessageSource(get)),+ regenerateUserMessage: async (messageId: string, edit?: CodexMessageEdit) => {+ const source = captureRegenerateUserMessageSource(get);+ if (edit) return editCodexUserMessage(messageId, source, edit);+ return regenerateUserMessageFromSource(messageId, source);+ },resendThreadMessage: async (messageId: string) => {// Resend is essentially regenerating the user message in thread contextdiff --git a/src/features/EditorModal/index.tsx b/src/features/EditorModal/index.tsxindex 3385ca66cd5..68bb061a51d 100644--- a/src/features/EditorModal/index.tsx+++ b/src/features/EditorModal/index.tsx@@ -1,4 +1,4 @@-import { Button, createModal, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';+import { Button, createModal, ModalFooter, Text, useModalContext } from '@lobehub/ui/base-ui';import { lazy, memo, type ReactNode, Suspense, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -11,11 +11,13 @@ const EditorModalContent = lazy(() => import('./EditorModalContent'));interface EditorModalFooterProps {editorBridge: EditorBridge;+ notice?: ReactNode;okText?: ReactNode;onConfirm?: (value: string, editorData?: unknown) => Promise<void>;}-const EditorModalFooter = memo<EditorModalFooterProps>(({ editorBridge, okText, onConfirm }) => {+const EditorModalFooter = memo<EditorModalFooterProps>((props) => {+ const { editorBridge, notice, okText, onConfirm } = props;const { t } = useTranslation('common');const { close } = useModalContext();const [confirmLoading, setConfirmLoading] = useState(false);@@ -40,6 +42,11 @@ const EditorModalFooter = memo<EditorModalFooterProps>(({ editorBridge, okText,return (<ModalFooter>+ {notice && (+ <Text fontSize={12} style={{ marginInlineEnd: 'auto' }} type={'secondary'}>+ {notice}+ </Text>+ )}<Button onClick={close}>{t('cancel')}</Button><Button disabled={!ready} loading={confirmLoading} type={'primary'} onClick={handleConfirm}>{okText ?? t('ok', { defaultValue: 'OK' })}@@ -52,6 +59,8 @@ EditorModalFooter.displayName = 'EditorModalFooter';export interface OpenEditorModalOptions {editorData?: unknown;+ /** Short consequence shown beside the actions (e.g. what a resend will not undo). */+ notice?: ReactNode;okText?: ReactNode;/** Runs whenever the modal closes, including confirm — clear caller-side editing flags here. */onClose?: () => void;@@ -61,6 +70,7 @@ export interface OpenEditorModalOptions {export const openEditorModal = ({editorData,+ notice,okText,onClose,onConfirm,@@ -74,7 +84,14 @@ export const openEditorModal = ({<EditorModalContent editorBridge={editorBridge} editorData={editorData} value={value} /></Suspense>),- footer: <EditorModalFooter editorBridge={editorBridge} okText={okText} onConfirm={onConfirm} />,+ footer: (+ <EditorModalFooter+ editorBridge={editorBridge}+ notice={notice}+ okText={okText}+ onConfirm={onConfirm}+ />+ ),// NOT `onOpenChange`: that only fires for user dismissal, while the footer's// Cancel goes through `instance.close()`. Cancelling would then leave the// caller's editing flag set and the editor could never be reopened.diff --git a/src/hooks/useCanEditCodexMessage.test.ts b/src/hooks/useCanEditCodexMessage.test.tsnew file mode 100644index 00000000000..b76ea03af7f--- /dev/null+++ b/src/hooks/useCanEditCodexMessage.test.ts@@ -0,0 +1,86 @@+import type * as LobechatConst from '@lobechat/const';+import type { LobeAgentAgencyConfig } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useCanEditCodexMessage } from './useCanEditCodexMessage';++const state = vi.hoisted(() => ({+ agencyConfig: undefined as LobeAgentAgencyConfig | undefined,+ isPreferenceLoading: false,+ workspaceScoped: false,+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof LobechatConst>()),+ isDesktop: true,+}));+vi.mock('@/helpers/gatewayMode', () => ({ useIsGatewayModeEnabled: () => true }));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({ useEffectiveAgencyConfig: () => state }));+vi.mock('@/store/agent', () => ({+ useAgentStore: (+ selector: (store: { agentMap: Record<string, { workspaceId?: string }> }) => unknown,+ ) => selector({ agentMap: {} }),+}));++/** @example A Codex topic uses the same valid runtime selection for Send and Edit. */+describe('useCanEditCodexMessage', () => {+ beforeEach(() => {+ state.agencyConfig = { heterogeneousProvider: { type: 'codex' } };+ state.isPreferenceLoading = false;+ state.workspaceScoped = false;+ });++ /** @example A connected device topic can edit through server dispatch. */+ it('offers Edit for Codex running on a bound device', () => {+ state.agencyConfig = {+ boundDeviceId: 't647-device',+ executionTarget: 'device',+ heterogeneousProvider: { type: 'codex' },+ };+ // ROOT CAUSE:+ //+ // The previous hook only accepted the local `hetero` runtime. Device sends+ // resolve to `gateway`, so their valid edit path was never reachable.+ // The fix retains runtime authorization and admits the bound device target.+ /** @example Device dispatch exposes the edit action. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(true);+ });++ /** @example Existing desktop-local Codex editing remains available. */+ it('retains local Codex editing', () => {+ /** @example An ordinary desktop Codex configuration stays editable. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(true);+ });++ /** @example An unresolved device choice cannot create an executable edit. */+ it('does not offer a device edit without a device binding', () => {+ state.agencyConfig = { executionTarget: 'device', heterogeneousProvider: { type: 'codex' } };+ /** @example An unbound device target stays unavailable. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(false);+ });++ /** @example Device support does not bypass an API binding restricted to local execution. */+ it('preserves the existing API-binding runtime guard', () => {+ state.agencyConfig = {+ boundDeviceId: 't647-device',+ executionTarget: 'device',+ heterogeneousProvider: { authMode: 'api', type: 'codex' },+ };+ /** @example A rejected runtime configuration never exposes Edit. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(false);+ });++ /** @example Shared preference loading must settle before an action becomes available. */+ it('waits for effective preferences', () => {+ state.isPreferenceLoading = true;+ /** @example Loading cannot accidentally enable the action. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(false);+ });++ /** @example Other CLI providers keep their existing action slots. */+ it('does not enable Claude Code editing', () => {+ state.agencyConfig = { heterogeneousProvider: { type: 'claude-code' } };+ /** @example This task changes only Codex user messages. */+ expect(useCanEditCodexMessage('agent', 'topic')).toBe(false);+ });+});diff --git a/src/hooks/useCanEditCodexMessage.ts b/src/hooks/useCanEditCodexMessage.tsnew file mode 100644index 00000000000..9eac707df92--- /dev/null+++ b/src/hooks/useCanEditCodexMessage.ts@@ -0,0 +1,54 @@+import { isDesktop } from '@lobechat/const';++import { resolveExecutionTarget } from '@/helpers/executionTarget';+import { useIsGatewayModeEnabled } from '@/helpers/gatewayMode';+import { useEffectiveAgencyConfig } from '@/hooks/useEffectiveAgencyConfig';+import { useAgentStore } from '@/store/agent';+import { selectRuntimeType } from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';++/**+ * Resolves whether a Codex conversation supports edit-and-resend on its selected runtime.+ *+ * Use when:+ * - Showing the user-message Edit action or confirming an open editor.+ *+ * Expects:+ * - The owning agent and, for a captured editor, its topic identity.+ *+ * Returns:+ * - True for executable local Codex or a bound device using the gateway runtime.+ */+export const useCanEditCodexMessage = (agentId?: string, topicId?: string | null): boolean => {+ const { agencyConfig, isPreferenceLoading, workspaceScoped } = useEffectiveAgencyConfig(agentId, {+ topicId,+ });+ const isGatewayMode = useIsGatewayModeEnabled(agentId);+ const isWorkspaceAgent = useAgentStore((s) => !!(agentId && s.agentMap[agentId]?.workspaceId));+ if (!agentId || isPreferenceLoading || agencyConfig?.heterogeneousProvider?.type !== 'codex')+ return false;+ try {+ const runtime = selectRuntimeType({+ boundDeviceId: agencyConfig.boundDeviceId,+ executionTarget: agencyConfig.executionTarget,+ heterogeneousProvider: agencyConfig.heterogeneousProvider,+ isGatewayMode,+ isWorkspaceAgent,+ workspaceScoped,+ });+ if (runtime === 'hetero') return true;++ // Resolve through the same target rules as Send, after its authorization guards.+ return (+ runtime === 'gateway' &&+ !!agencyConfig.boundDeviceId &&+ resolveExecutionTarget(agencyConfig, {+ clientExecutionAvailable: isDesktop,+ isHetero: true,+ workspaceScoped,+ }) === 'device'+ );+ } catch {+ // Invalid effective runtime configurations cannot offer an executable edit action.+ return false;+ }+};diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsxindex 24aefa66c07..b632f6f9141 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/index.test.tsx@@ -163,6 +163,26 @@ describe('ChatHydration', () => {});});+ /** @example Edit changes topic and clears an already-absent thread without reverting the URL. */+ it('does not rewrite the old URL when an edited topic clears an absent thread', async () => {+ // ROOT CAUSE:+ // switchTopic changes activeThreadId from null to undefined alongside the topic.+ // An unconditional setThread(null) navigated against the old pathname after the topic navigation.+ useParamsMock.mockReturnValue({ aid: 'agt_test', topicId: 'source' });+ useLocationMock.mockReturnValue({ hash: '', pathname: '/agent/agt_test/source', search: '' });+ useSearchParamsMock.mockReturnValue([new URLSearchParams(), setSearchParamsMock]);+ render(<ChatHydration />);+ navigateMock.mockClear();+ setSearchParamsMock.mockClear();+ await act(async () => {+ await useChatStore.getState().switchTopic('edited', { skipRefreshMessage: true });+ });+ /** @example The new Topic URL is the only navigation; refresh will reopen the edited topic. */+ expect(navigateMock).toHaveBeenCalledWith('/agent/agt_test/edited', { replace: true });+ /** @example No redundant query-string navigation can put the source pathname back. */+ expect(setSearchParamsMock).not.toHaveBeenCalled();+ });+it('keeps topic navigation inside a project conversation route', async () => {useParamsMock.mockReturnValue({ projectId: 'prj_1' });useLocationMock.mockReturnValue({diff --git a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.tsindex f67ba4ba1d3..7c9c621d571 100644--- a/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts+++ b/src/routes/(main)/agent/features/Conversation/ChatHydration/useChatRouteSync.ts@@ -80,6 +80,9 @@ export const useChatRouteSync = (options: ChatRouteSyncOptions = {}) => {const unsubscribeThread = useChatStore.subscribe((state) => state.activeThreadId,(state) => {+ // A topic switch clears null to undefined. Avoid a redundant query update+ // against the old pathname, which would undo navigation to the edited topic.+ if ((state || null) === searchParamsRef.current.get('thread')) return;setThread(state || null);},);diff --git a/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.test.ts b/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.test.tsindex 8293afca3c6..0a094dbad83 100644--- a/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.test.ts+++ b/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.test.ts@@ -1,16 +1,35 @@+import type * as LobechatConst from '@lobechat/const';import { cleanup, renderHook } from '@testing-library/react';import { act } from 'react';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useAgentStore } from '@/store/agent';import { useActionsBarConfig } from './useActionsBarConfig';+const runtime = vi.hoisted(() => ({ isDesktop: true }));+vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof LobechatConst>()),+ get isDesktop() {+ return runtime.isDesktop;+ },+}));+vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({+ useEffectiveAgencyConfig: () => ({+ agencyConfig: useAgentStore((s) =>+ s.activeAgentId ? s.agentMap[s.activeAgentId]?.agencyConfig : undefined,+ ),+ isPreferenceLoading: false,+ workspaceScoped: false,+ }),+}));+const initialState = useAgentStore.getState();/** @example A completed Codex reply exposes the existing regenerate action. */describe('useActionsBarConfig', () => {beforeEach(() => {+ runtime.isDesktop = true;useAgentStore.setState({activeAgentId: 'codex-agent',agentMap: {@@ -48,8 +67,44 @@ describe('useActionsBarConfig', () => {/** @example The user menu still supports restoring the original prompt. */expect(result.current.user?.menu).toContain('restoreToInput');- /** @example The user quick action remains copy. */- expect(result.current.user?.bar).toEqual(['copy']);+ /** @example User edits and the existing copy action are both available. */+ expect(result.current.user?.bar).toEqual(['edit', 'copy']);+ /** @example Historical user prompts also expose Edit in the overflow menu. */+ expect(result.current.user?.menu).toContain('edit');+ });++ /** @example Only executable local or bound-device targets advertise Edit. */+ it('offers device Edit while keeping unbound Web and sandbox unavailable', () => {+ // ROOT CAUSE:+ // Provider-only slots originally advertised Edit even when gateway editing+ // was unsupported. The device dispatch now hydrates durable edit context;+ // unbound Web and sandbox still have no supported edit execution target.+ const { result, rerender } = renderHook(() => useActionsBarConfig());+ runtime.isDesktop = false;+ rerender();+ /** @example Web never advertises an in-process edit operation. */+ expect(result.current.user?.menu).not.toContain('edit');+ runtime.isDesktop = true;+ for (const executionTarget of ['sandbox', 'device'] as const) {+ act(() =>+ useAgentStore.setState({+ agentMap: {+ 'codex-agent': {+ agencyConfig: {+ executionTarget,+ boundDeviceId: 'remote',+ heterogeneousProvider: { type: 'codex' },+ },+ },+ },+ }),+ );+ rerender();+ /** @example A bound device can edit; sandbox keeps its existing copy action. */+ expect(result.current.user?.bar).toEqual(+ executionTarget === 'device' ? ['edit', 'copy'] : ['copy'],+ );+ }});/** @example Switching from Codex to Claude Code removes the Codex-only action. */@@ -67,9 +122,7 @@ describe('useActionsBarConfig', () => {/** @example Claude Code keeps its current quick actions. */expect(result.current.assistant?.bar).toEqual(['copy']);/** @example Claude Code keeps its current overflow menu. */- expect(result.current.assistant?.menu).toEqual([- 'copy', 'divider', 'select', 'divider', 'del',- ]);+ expect(result.current.assistant?.menu).toEqual(['copy', 'divider', 'select', 'divider', 'del']);});/** @example A native agent keeps the default actions provided by the message components. */diff --git a/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.ts b/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.tsindex 012c2b1a7a3..db28cdfab4a 100644--- a/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.ts+++ b/src/routes/(main)/agent/features/Conversation/useActionsBarConfig.ts@@ -3,13 +3,14 @@import { useMemo } from 'react';import { type ActionsBarConfig, type MessageActionSlot } from '@/features/Conversation/types';+import { useCanEditCodexMessage } from '@/hooks/useCanEditCodexMessage';import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';/*** Hetero-agent (Claude Code / Codex) sessions keep the menu minimal — copy +* delete — because the external runtime owns the assistant message lifecycle- * (edit / branching / translate / share don't apply).+ * (assistant edit / branching / translate / share don't apply).* Regenerate was previously excluded too; Codex now uses the existing* heterogeneous rerun path, which preserves the user prompt and attachments.* `select` remains available because forwarding / batch deletion is handled by@@ -25,6 +26,12 @@ const HETERO_USER: { bar: MessageActionSlot[]; menu: MessageActionSlot[] } = {menu: ['restoreToInput', 'copy', 'divider', 'select', 'divider', 'del'],};+/** Codex user edits run a replacement prompt while preserving the original history. */+const CODEX_USER: typeof HETERO_USER = {+ bar: ['edit', ...HETERO_USER.bar],+ menu: ['edit', ...HETERO_USER.menu],+};+const HETERO_ASSISTANT: { bar: MessageActionSlot[]; menu: MessageActionSlot[] } = {bar: ['copy'],menu: ['copy', 'divider', 'select', 'divider', 'del'],@@ -49,6 +56,8 @@ const CODEX_ASSISTANT: typeof HETERO_ASSISTANT = {* - Runtime-specific overrides, or native message defaults via an empty object.*/export const useActionsBarConfig = (): ActionsBarConfig => {+ const agentId = useAgentStore((s) => s.activeAgentId);+ const canEditCodex = useCanEditCodexMessage(agentId);const isHeteroAgent = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const providerType = useAgentStore(agentSelectors.currentAgentHeterogeneousProviderType);@@ -58,10 +67,10 @@ export const useActionsBarConfig = (): ActionsBarConfig => {return {assistant: providerType === 'codex' ? CODEX_ASSISTANT : HETERO_ASSISTANT,assistantGroup: providerType === 'codex' ? CODEX_ASSISTANT : HETERO_ASSISTANT,- user: HETERO_USER,+ user: canEditCodex ? CODEX_USER : HETERO_USER,};}return {};- }, [isHeteroAgent, providerType]);+ }, [canEditCodex, isHeteroAgent, providerType]);};diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex c2a8210ab5d..89e372fd566 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -68,6 +68,17 @@ export class TopicService {return lambdaClient.topic.forkTopic.mutate(params);};+ /** Copies the conversation up to a user message into a new topic with edited content. */+ branchTopicAtMessage = (params: {+ content: string;+ editorData?: Record<string, any> | null;+ messageId: string;+ title?: string;+ topicId: string;+ }): Promise<{ messageId: string; topicId: string }> => {+ return lambdaClient.topic.branchTopicAtMessage.mutate(params);+ };+batchMoveTopics = (topicIds: string[], targetAgentId: string) => {return lambdaClient.topic.batchMoveTopics.mutate({ targetAgentId, topicIds });};diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 632d5a58d33..c6b4a392183 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -2278,6 +2278,80 @@ describe('heterogeneousAgentExecutor DB persistence', () => {expect(resumedSystemContext).not.toContain('/Users/me/repo');});+ describe('edited topic replay', () => {+ // Copied ancestry of an edited Codex topic: a tool round, then the edited prompt+ // and this run's placeholder. The projected tool row cannot be restored here.+ const editedRows = [+ { content: 'Original question', id: 'u0', role: 'user' },+ { content: '', id: 'a0', parentId: 'u0', role: 'assistant', tools: [{ id: 'call-1' }] },+ { content: '', id: 't0', parentId: 'a0', payloadOmitted: true, role: 'tool' },+ { content: 'Original answer', id: 'a1', parentId: 't0', role: 'assistant' },+ { content: 'test prompt', id: 'u1', parentId: 'a1', role: 'user' },+ { content: '...', id: 'ast-initial', parentId: 'u1', role: 'assistant' },+ ];+ const storeWith = (metadata: Record<string, unknown>) =>+ createMockStore({+ dbMessagesMap: { 'main_agent-1_topic-1': editedRows },+ topicDataMap: { 'agent-1__main': { items: [{ id: 'topic-1', metadata }] } },+ });+ const codexParams = {+ ...defaultParams,+ heterogeneousProvider: { command: 'codex', type: 'codex' as const },+ };++ it('replays the copied ancestry when an edited topic starts without a native session', async () => {+ // ROOT CAUSE:+ // The edited topic copies history into the database but has no native+ // session, so the local CLI started blank and lost the conversation.+ const store = storeWith({ editedFrom: { messageId: 'u-source', topicId: 'source' } });++ await executeHeterogeneousAgent(+ vi.fn(() => store),+ codexParams,+ );++ expect(mockSendPrompt.mock.calls[0][0].systemContext).toBe(+ [+ '<previous_conversation>',+ '<user>\nOriginal question\n</user>',+ '<assistant>\nOriginal answer\n</assistant>',+ '</previous_conversation>',+ ].join('\n'),+ );+ });++ it('does not replay once the edited topic has its own native session', async () => {+ const store = storeWith({ editedFrom: { messageId: 'u-source', topicId: 'source' } });++ await executeHeterogeneousAgent(+ vi.fn(() => store),+ { ...codexParams, resumeSessionId: 'codex-thread-1' },+ );++ expect(mockSendPrompt.mock.calls[0][0].systemContext).toBeUndefined();+ });++ it.each([+ ['codex', codexParams],+ ['claude-code', defaultParams],+ ])(+ 'leaves an ordinary fresh %s session without replay, even with an unrestorable tool row',+ async (_type, params) => {+ // A fresh session in an ordinary topic (new topic, cwd-change reset) keeps+ // canary behavior: no history replay, no tool-payload restore, no throw.+ const store = storeWith({});++ await executeHeterogeneousAgent(+ vi.fn(() => store),+ params,+ );++ expect(mockSendPrompt).toHaveBeenCalledTimes(1);+ expect(mockSendPrompt.mock.calls[0][0].systemContext).toBeUndefined();+ },+ );+ });+it('should forward context selections as heterogeneous system context', async () => {const store = createMockStore();const get = vi.fn(() => store);diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex ee484a91a3f..349e32e022c 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -92,7 +92,11 @@ import { getNativeHeteroSessionBindingKey } from './heteroResume';import { createMessageWriteBatcher, type ToolMessageUpdateOperation } from './messageWriteBatcher';import { createPendingCreateLedger } from './pendingCreateLedger';import { resolveQuotaAccountSpawnPlan } from './resolveQuotaAccountEnv';-import { buildResumeReplayMessages, shouldHydrateResumeReplay } from './resumeReplay';+import {+ buildEditedTopicPreviousConversation,+ buildResumeReplayMessages,+ shouldHydrateResumeReplay,+} from './resumeReplay';import { buildLobeHubSessionEnv } from './sessionEnv';/** Mirrors `idGenerator('threads', 16)` on the server so sync-allocated ids have the same shape. */@@ -268,14 +272,17 @@ const buildLocalHeterogeneousSystemContext = ({agentSystemContext,contextSelections,pageSelections,+ previousConversation,}: {agentSystemContext?: string;contextSelections?: ContextSelection[];pageSelections?: PageSelection[];+ previousConversation?: string;}): string | undefined => {const parts: string[] = [];if (agentSystemContext?.trim()) parts.push(agentSystemContext.trim());+ if (previousConversation) parts.push(previousConversation);const selectionContext =contextSelections && contextSelections.length > 0@@ -2586,21 +2593,31 @@ export const executeHeterogeneousAgent = async (},});+ // Raw rows first: the display map collapses history into virtual+ // `assistantGroup` rows, which carry no replayable turn.+ const replaySource = (get().dbMessagesMap?.[messageMapKey(context)] ??+ get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined;+const systemContext = buildLocalHeterogeneousSystemContext({// `/goal` reaches a hetero agent as instructions, not a tool: it creates// and plans the goal through `lh` in this same run.agentSystemContext: withConversationGoalPrompt(heterogeneousProvider.systemContext, message),contextSelections,pageSelections,+ // Only a topic created by Codex edit-and-resend starts with copied+ // history but no native session. Every other fresh session (a new+ // topic, a cwd-change reset) keeps starting without replay.+ previousConversation:+ !resumeSessionId &&+ !replayTranscript &&+ getTopicMetadataById(get(), context.topicId ?? undefined)?.editedFrom+ ? buildEditedTopicPreviousConversation(replaySource, assistantMessageId)+ : undefined,});// When resuming, hand main the prior turns so it can rebuild a Claude Code// transcript the CLI already garbage-collected (default 30 days) — without// it, `--resume <staleId>` dies with "No conversation found with session ID".- // Raw rows first: the display map collapses history into virtual- // `assistantGroup` rows, which carry no replayable turn.- const replaySource = (get().dbMessagesMap?.[messageMapKey(context)] ??- get().messagesMap?.[messageMapKey(context)]) as UIChatMessage[] | undefined;// Tool bodies the read path projected away are restored first: this// transcript is written to disk and resumed from, so an emptied tool resultdiff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.edited.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.edited.test.tsnew file mode 100644index 00000000000..33c970f258d--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.edited.test.ts@@ -0,0 +1,69 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildEditedTopicPreviousConversation } from './resumeReplay';++const msg = (over: Partial<UIChatMessage>): UIChatMessage =>+ ({ content: '', createdAt: 0, id: 'm', role: 'user', ...over }) as UIChatMessage;++describe('buildEditedTopicPreviousConversation', () => {+ it('serializes only the ancestors before the edited prompt', () => {+ const result = buildEditedTopicPreviousConversation(+ [+ msg({ content: 'first question', id: 'u0' }),+ msg({ content: 'sibling attempt', id: 'a0-old', parentId: 'u0', role: 'assistant' }),+ msg({ id: 'a0', parentId: 'u0', role: 'assistant', tools: [{ id: 'c' }] as any }),+ msg({ content: 'TOOL OUTPUT', id: 't0', parentId: 'a0', role: 'tool' }),+ msg({ content: 'first answer', id: 'a1', parentId: 't0', role: 'assistant' }),+ msg({ content: 'EDITED PROMPT', id: 'u1', parentId: 'a1' }),+ msg({ content: '...', id: 'run', parentId: 'u1', role: 'assistant' }),+ ],+ 'run',+ );++ expect(result).toBe(+ [+ '<previous_conversation>',+ '<user>\nfirst question\n</user>',+ '<assistant>\nfirst answer\n</assistant>',+ '</previous_conversation>',+ ].join('\n'),+ );+ });++ it('keeps the newest 30 turns and truncates long turns like the gateway fallback', () => {+ const rows: UIChatMessage[] = [];+ let parentId: string | undefined;+ for (let i = 0; i < 40; i++) {+ const id = `m${i}`;+ rows.push(+ msg({+ content: i === 39 ? 'a'.repeat(3000) : `turn ${i}`,+ id,+ parentId,+ role: i % 2 ? 'assistant' : 'user',+ }),+ );+ parentId = id;+ }+ rows.push(msg({ content: 'edited', id: 'edit', parentId }));+ rows.push(msg({ id: 'run', parentId: 'edit', role: 'assistant' }));++ const result = buildEditedTopicPreviousConversation(rows, 'run')!;++ expect(result.match(/<(user|assistant)>/g)).toHaveLength(30);+ expect(result).not.toContain('turn 9\n');+ expect(result).toContain('turn 10\n');+ expect(result).toContain(`${'a'.repeat(2048)}… [truncated]`);+ });++ it('returns undefined without a user prompt or history', () => {+ expect(buildEditedTopicPreviousConversation(undefined, 'run')).toBeUndefined();+ expect(+ buildEditedTopicPreviousConversation(+ [msg({ id: 'u' }), msg({ id: 'run', parentId: 'u', role: 'assistant' })],+ 'run',+ ),+ ).toBeUndefined();+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.tsindex 3fbb2e28396..5bb4d73781c 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/resumeReplay.ts@@ -1,3 +1,4 @@+import { LOADING_FLAT } from '@lobechat/const';import type { HeteroSessionImportMessage, UIChatMessage } from '@lobechat/types';/**@@ -78,3 +79,54 @@ export const buildResumeReplayMessages = (return mapped;};++/** Same limits as the gateway's `<previous_conversation>` fallback. */+const EDITED_TOPIC_MAX_TURNS = 30;+const EDITED_TOPIC_USER_MAX = 1024;+const EDITED_TOPIC_ASSISTANT_MAX = 2048;++/**+ * Serialize the copied ancestry of an edited topic for a fresh local run.+ *+ * Use when:+ * - A topic created by Codex edit-and-resend (`metadata.editedFrom`) starts+ * without a native session, so the CLI would otherwise see no history.+ *+ * Expects:+ * - The topic's persisted rows and the assistant placeholder of this run,+ * whose parent is the edited user message.+ *+ * Returns:+ * - A `<previous_conversation>` block of the completed user/assistant turns+ * before the edited message (the prompt itself is sent separately), or+ * `undefined` when there is nothing to replay. Tool rows are walked through+ * but not serialized, matching the gateway fallback.+ */+export const buildEditedTopicPreviousConversation = (+ messages: UIChatMessage[] | undefined,+ assistantMessageId: string,+): string | undefined => {+ if (!messages?.length) return;+ const byId = new Map(messages.map((message) => [message.id, message]));+ const prompt = byId.get(byId.get(assistantMessageId)?.parentId ?? '');+ if (prompt?.role !== 'user') return;++ const turns: string[] = [];+ const visited = new Set<string>([prompt.id]);+ let id = prompt.parentId;+ while (id && !visited.has(id) && turns.length < EDITED_TOPIC_MAX_TURNS) {+ visited.add(id);+ const message = byId.get(id);+ if (!message) break;+ id = message.parentId;+ if (message.role !== 'user' && message.role !== 'assistant') continue;+ const content = message.content?.trim();+ if (!content || content === LOADING_FLAT) continue;+ const limit = message.role === 'user' ? EDITED_TOPIC_USER_MAX : EDITED_TOPIC_ASSISTANT_MAX;+ const body = content.length > limit ? `${content.slice(0, limit)}… [truncated]` : content;+ turns.push(`<${message.role}>\n${body}\n</${message.role}>`);+ }+ if (turns.length === 0) return;++ return `<previous_conversation>\n${turns.reverse().join('\n')}\n</previous_conversation>`;+};