/* Copyright (C) 2025 QuantumNous This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . For commercial licensing, please contact support@quantumnous.com */ import { useCallback, useState, useRef } from 'react'; import { Toast, Modal } from '@douyinfe/semi-ui'; import { useTranslation } from 'react-i18next'; import { getTextContent, buildApiPayload, createLoadingAssistantMessage, applySummaryAndWindow, } from '../../helpers'; import { MESSAGE_ROLES } from '../../constants/playground.constants'; import { deleteMessagesFrom } from '../../services/playgroundConversation'; export const useMessageEdit = ( setMessage, inputs, parameterEnabled, sendRequest, saveMessages, options = {}, ) => { const { // 当前消息列表快照(由调用方每次渲染传入)。handleEditSave 的查找/确认弹窗/后端删除 // 必须在 setMessage updater 外完成 —— StrictMode 下 updater 会执行两次, // 放里面会双弹 Modal、双发请求。 messages = [], activeSessionId, sessionEnabled = false, maxHistoryRounds = 0, conversationSummary = '', summarizedUpToMessageId = 0, summaryEnabled = false, // 当编辑触发的消息在摘要覆盖范围内(其 backendId ≤ summarizedUpToMessageId)时调用, // 用于使过时的摘要失效,避免模型同时看到「摘要里的旧版本」+「正文里的新版本」 onSummaryInvalidate, // 归档会话只读:handleEditSave 进入即拦截,否则"重新生成"路径会发起 // deleteMessagesFrom + sendRequest 两个被后端拒的请求,本地状态与服务端永久分叉 activeSessionArchived = false, } = options; const { t } = useTranslation(); const [editingMessageId, setEditingMessageId] = useState(null); const [editValue, setEditValue] = useState(''); const editingMessageRef = useRef(null); const handleMessageEdit = useCallback((targetMessage) => { const editableContent = getTextContent(targetMessage); setEditingMessageId(targetMessage.id); editingMessageRef.current = targetMessage; setEditValue(editableContent); }, []); const handleEditSave = useCallback(() => { if (!editingMessageId || !editValue.trim()) return; // 归档会话只读拦截:任何路径(仅保存 / 重新生成)都会导致本地与服务端分叉,直接拒绝 if (activeSessionArchived) { Toast.warning({ content: t('当前会话已归档,无法编辑消息'), duration: 2, }); setEditingMessageId(null); editingMessageRef.current = null; setEditValue(''); return; } // 查找目标消息:全部基于当前渲染传入的 messages 快照,在 updater 外完成。 let messageIndex = messages.findIndex( (msg) => msg === editingMessageRef.current, ); if (messageIndex === -1) { messageIndex = messages.findIndex((msg) => msg.id === editingMessageId); } const targetMessage = messages[messageIndex]; // 目标消息已不存在(被删除 / 切换会话):静默退出编辑态,不能继续往下走 // (原实现会直接读 undefined.content 抛 TypeError) if (!targetMessage) { setEditingMessageId(null); editingMessageRef.current = null; setEditValue(''); return; } let newContent; if (Array.isArray(targetMessage.content)) { newContent = targetMessage.content.map((item) => item.type === 'text' ? { ...item, text: editValue.trim() } : item, ); } else { newContent = editValue.trim(); } const updatedMessages = messages.map((msg) => msg.id === editingMessageId ? { ...msg, content: newContent } : msg, ); // 编辑命中已被摘要覆盖的历史消息时,让摘要失效(next send 退化为不带摘要,再下一次到阈值时重摘) const summaryInvalidated = targetMessage.backendId && summarizedUpToMessageId > 0 && targetMessage.backendId <= summarizedUpToMessageId && typeof onSummaryInvalidate === 'function'; if (summaryInvalidated) { onSummaryInvalidate(); } const finishEditing = () => { setEditingMessageId(null); editingMessageRef.current = null; setEditValue(''); }; // 处理用户消息编辑后的重新生成 const hasSubsequentAssistantReply = targetMessage.role === MESSAGE_ROLES.USER && messageIndex < messages.length - 1 && messages[messageIndex + 1].role === MESSAGE_ROLES.ASSISTANT; if (hasSubsequentAssistantReply) { Modal.confirm({ title: t('消息已编辑'), content: t('检测到该消息后有AI回复,是否删除后续回复并重新生成?'), okText: t('重新生成'), cancelText: t('仅保存'), onOk: () => { const messagesUntilUser = updatedMessages.slice(0, messageIndex + 1); setMessage(messagesUntilUser); // 编辑后保存(重新生成的情况),传入更新后的消息列表 setTimeout(() => saveMessages(messagesUntilUser), 0); // 用 IIFE 而不是把 onOk 写成 async —— Semi Modal 会 await onOk 的返回值, // 那样弹窗会挂着 loading 等删除接口返回,这里希望弹窗立即关闭 (async () => { // 后端同步:删除被编辑的 user 消息及之后所有消息(重发时后端会基于 // 新内容重新落库)。必须等删除落地后再重发 —— 删除接口语义是 // 「删 id ≥ fromId」,若重发的新消息先落库、删除后执行, // 新消息(id 更大)会被一并删掉,DB 丢当前轮。 if (sessionEnabled && activeSessionId && targetMessage.backendId) { try { await deleteMessagesFrom( activeSessionId, targetMessage.backendId, ); } catch (e) { console.warn('编辑后重发,后端删除消息序列失败:', e); } } setTimeout(() => { // 编辑后重发同样应用「摘要 + 窗口」处理(Feature A + B)。 // 不在编辑路径触发新摘要,沿用会话已有摘要(接受轻微陈旧)。 // 注意:本次编辑若已使摘要失效,这里必须用失效后的空值 —— // 闭包里的 conversationSummary 是失效前的旧状态,直接用会把 // 「陈旧摘要 + 全量历史」双份上下文发给模型。 const payload = buildApiPayload( applySummaryAndWindow(messagesUntilUser, { maxRounds: maxHistoryRounds, summary: summaryInvalidated ? '' : conversationSummary, summarizedUpToMessageId: summaryInvalidated ? 0 : summarizedUpToMessageId, summaryEnabled, }), null, inputs, parameterEnabled, ); // 与 onMessageSend 对齐:若被编辑的 user 消息含 file 附件, // loading 显示"正在处理 N 个附件…",避免重发时用户体感卡顿无反馈 const lastUserMsg = messagesUntilUser[messagesUntilUser.length - 1]; const fileCount = Array.isArray(lastUserMsg?.content) ? lastUserMsg.content.filter((p) => p && p.type === 'file') .length : 0; setMessage((prevMsg) => [ ...prevMsg, createLoadingAssistantMessage( fileCount > 0 ? { processingAttachments: fileCount } : {}, ), ]); sendRequest(payload, inputs.stream); }, 100); })(); }, onCancel: () => { setMessage(updatedMessages); // 编辑后保存(仅保存的情况),传入更新后的消息列表 setTimeout(() => saveMessages(updatedMessages), 0); Toast.success({ content: t('消息已更新'), duration: 2 }); }, }); finishEditing(); return; } // 编辑后保存(普通情况),传入更新后的消息列表 setMessage(updatedMessages); setTimeout(() => saveMessages(updatedMessages), 0); finishEditing(); Toast.success({ content: t('消息已更新'), duration: 2 }); }, [ editingMessageId, editValue, messages, t, inputs, parameterEnabled, sendRequest, setMessage, saveMessages, sessionEnabled, activeSessionId, maxHistoryRounds, conversationSummary, summarizedUpToMessageId, summaryEnabled, onSummaryInvalidate, activeSessionArchived, ]); const handleEditCancel = useCallback(() => { setEditingMessageId(null); editingMessageRef.current = null; setEditValue(''); }, []); return { editingMessageId, editValue, setEditValue, handleMessageEdit, handleEditSave, handleEditCancel, }; };