支持编辑已发送的用户消息(覆盖式重发)

This commit is contained in:
2026-10-22 20:55:38 +08:00
parent bc34f91417
commit 61245b1c65
8 changed files with 154 additions and 14 deletions
+20
View File
@@ -1465,6 +1465,25 @@ function deleteMessage(sessionId, messageId) {
return { ok: true, id: messageId, removed: removed + 1 };
}
// 覆盖式编辑用户消息:删掉该条及其后的全部历史(含 tool 回执/摘要),再以新内容重开一轮。
// 编辑点是 user 行,前缀必然停在 assistant,不会留下无配对的 tool_call。
// 运行中不支持:runLoop 每轮重载历史,中途截断会让当前回合的 tool 回执缺失。
function editUserMessage(sessionId, messageId, content, opts) {
const session = getSession(sessionId);
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
const row = db.prepare('SELECT id, role FROM messages WHERE id = ? AND session_id = ?').get(messageId, sessionId);
if (!row) throw Object.assign(new Error('消息不存在'), { status_code: 404 });
if (row.role !== 'user') throw Object.assign(new Error('只能编辑用户消息'), { status_code: 400 });
const run = runs.get(sessionId);
if (run && run.looping) throw Object.assign(new Error('任务正在执行,请先终止再编辑'), { status_code: 409 });
// 先确保能开跑:无可用模型时抛 503,避免删完历史却发不出去
ensureBinding(session);
const removed = db.prepare('DELETE FROM messages WHERE session_id = ? AND id >= ?').run(sessionId, messageId).changes;
const r = postUserMessage(sessionId, content, opts);
log.info('msg', sessionId + ' 编辑消息 ' + messageId + ',丢弃其后 ' + Math.max(0, removed - 1) + ' 条历史');
return Object.assign({ removed: removed }, r);
}
// 删工具回执(任务执行卡片):同步把对应 tool_call 从父 assistant 的 tool_calls 里摘掉,
// 避免留下「有调用无结果」被严格上游拒收。父回合若是纯工具调用轮(无文本)且已无
// 其余调用,则整行一起删(空气泡没有意义);有文本则保留为普通文本回复。
@@ -1511,6 +1530,7 @@ module.exports = {
clearSessionMessages,
summarizeContext,
deleteMessage,
editUserMessage,
getSession,
getRun,
taskDirOf,
+16 -2
View File
@@ -280,7 +280,7 @@ main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
.tool-card .tool-time .act-del:hover { color: #c0392b; }
/* ================= 底部输入区 ================= */
footer { flex: none; padding: 8px 12px calc(10px + env(safe-area-inset-bottom, 0px)); background: var(--page); }
footer { position: relative; flex: none; padding: 8px 12px calc(10px + env(safe-area-inset-bottom, 0px)); background: var(--page); }
.attach-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
.attach-chip {
display: inline-flex; align-items: center; gap: 6px;
@@ -792,8 +792,10 @@ footer { flex: none; padding: 8px 12px calc(10px + env(safe-area-inset-bottom, 0
}
/* ================= 回到底部浮动按钮(同步 index 右下角导航浮动图标) ================= */
/* 停靠在输入区上方:包含块是 footer,bottom:100% = footer 顶边,
输入框长高/编辑条出现时随 footer 一起上移,不再用固定值 140px 遮挡输入区。 */
.scroll-bottom-btn {
position: absolute; right: 14px; bottom: 140px;
position: absolute; right: 14px; bottom: calc(100% + 6px); margin: 0;
width: 38px; height: 38px; border-radius: 50%;
border: none; cursor: pointer; padding: 0;
display: flex; align-items: center; justify-content: center;
@@ -1458,3 +1460,15 @@ body.pv-resizing #pv-pane iframe { pointer-events: none; }
background: var(--active-soft); color: var(--active);
}
@keyframes drop-overlay-in { from { opacity: 0; } to { opacity: 1; } }
/* ================= 编辑已发送消息提示条 ================= */
/* 覆盖式重发:输入框内部的浅蓝提示条(嵌在 .input-shell 顶端,间距由 shell 的 gap 提供)。 */
.edit-bar {
display: flex; align-items: center; gap: 8px;
padding: 6px 6px 6px 12px;
border-radius: 12px; background: var(--active-soft);
color: var(--active); font-size: 12.5px;
}
.edit-bar span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.edit-bar button { flex: none; padding: 2px 10px; border-radius: 8px; font-size: 12.5px; font-weight: 600; color: var(--active); }
.edit-bar button:active { background: rgba(57, 100, 254, 0.12); }
+11 -6
View File
@@ -158,6 +158,11 @@
<footer>
<div class="attach-chips hidden" id="attach-chips"></div>
<div class="input-shell">
<!-- 编辑已发送消息:覆盖式重发提示条(发送后丢弃该条及其后的历史) -->
<div class="edit-bar hidden" id="edit-bar">
<span>正在编辑已发送的消息,发送后将丢弃其后的历史</span>
<button id="edit-cancel" type="button">取消</button>
</div>
<div class="up-cards hidden" id="up-cards" aria-label="已上传文件"></div>
<textarea id="msg-input" placeholder="传送信息" rows="2" enterkeyhint="enter"></textarea>
<div class="input-actions">
@@ -182,14 +187,14 @@
</div>
</div>
</div>
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈)。
放在 footer 内、相对 footer 顶边停靠:输入框长高/编辑条出现时不会被盖住 -->
<button class="scroll-bottom-btn hidden" id="scroll-bottom-btn" onclick="clickScrollBottom()" title="回到底部" aria-label="回到底部">
<svg class="sb-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg>
<svg class="sb-spinner hidden" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><path d="M22 12a10 10 0 0 1-10 10"></path></svg>
</button>
</footer>
<!-- 回到底部浮动按钮(搬自 index;上翻历史时出现、AI 输出中常驻转圈) -->
<button class="scroll-bottom-btn hidden" id="scroll-bottom-btn" onclick="clickScrollBottom()" title="回到底部" aria-label="回到底部">
<svg class="sb-arrow" viewBox="0 0 24 24"><polyline points="6 9 12 15 18 9"></polyline></svg>
<svg class="sb-spinner hidden" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"></circle><path d="M22 12a10 10 0 0 1-10 10"></path></svg>
</button>
<!-- ================= 历史记录抽屉 ================= -->
<div id="scrim"></div>
<aside id="drawer" aria-label="对话历史">
+12 -3
View File
@@ -27,7 +27,7 @@
(u.cached == null ? '未上报' : u.cached + ' tok') + ',输出 ' + (u.ct || 0) + ' tok';
}
function actionsHtml(ts, content, msgId, usage) {
function actionsHtml(ts, content, msgId, usage, canEdit) {
const b64 = btoa(unescape(encodeURIComponent(content)));
// 删除本条:仅已落库消息可删(传 m.id);流式未落库时无 id,不渲染
const del = msgId
@@ -35,6 +35,12 @@
'<svg class="ic sm" viewBox="0 0 24 24"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>' +
'</button>'
: '';
// 编辑并重发:只给未压缩的用户消息(调用方传 canEdit);带 b64 回填输入框,避免从 DOM 反推
const edit = canEdit && msgId
? '<button class="act act-edit" title="编辑并重发" data-msg-id="' + msgId + '" data-b64="' + b64 + '">' +
'<svg class="ic sm" viewBox="0 0 24 24"><path d="M12 20h9"></path><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"></path></svg>' +
'</button>'
: '';
const u = normUsage(usage);
const usageHtml = u
? '<span class="act-usage" title="' + usageTip(u) + '">' + usageBrief(u) + '</span>'
@@ -45,6 +51,7 @@
'<button class="act act-copy" title="复制" data-b64="' + b64 + '">' +
'<svg class="ic sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>' +
'</button>' +
edit +
del +
'</div>';
}
@@ -55,9 +62,10 @@
? '<div class="attach-line">📎 ' + esc(p.files.join('、')) + '</div>' : '';
const r = mdHtml(p.text);
// 复制内容取纯文本(不含【系统通知】附件行),与气泡里显示一致
// 编辑按钮只给「用户手打/粘贴」的消息:archived(已压缩存档)与 scheduler_note 等系统行不给
return '<div class="msg me">' +
'<div class="bubble-user' + (r.fmt ? ' md' : '') + '">' + attach + r.html + '</div>' +
actionsHtml(m.created_at, p.text, m.id) +
actionsHtml(m.created_at, p.text, m.id, null, !m.type) +
'</div>';
}
@@ -513,7 +521,8 @@
const wrap = document.createElement('div');
wrap.className = 'msg me';
wrap.innerHTML = '<div class="bubble-user' + (r.fmt ? ' md' : '') + '">' + attach + r.html + '</div>' +
actionsHtml(Date.now(), content, msgId);
// 刚发送的用户消息同样可编辑(canEdit=true);actionsHtml 只在有 msgId 时才渲染按钮
actionsHtml(Date.now(), content, msgId, null, true);
decorateCodePre(wrap); // 用户消息里也可能有围栏代码块
$('chat-view').appendChild(wrap);
// 已落库的行记入增量跟踪:避免回前台补拉时把这条再追加一遍
+2
View File
@@ -9,6 +9,7 @@
* POST /api/sessions {title:'', model_id:''} 首条消息自动建档
* GET /api/sessions/:id 打开会话(消息+文件)
* POST /api/sessions/:id/messages {content, attachments} 发送消息
* POST /api/sessions/:id/messages/:mid/edit 编辑用户消息(覆盖式重发)
* POST /api/sessions/:id/files 附件上传(multipart)
* GET /api/sessions/:id/stream SSE 流式输出
* POST /api/sessions/:id/stop | /release 状态栏「终止/断开」
@@ -169,6 +170,7 @@
schedule: null, // 当前会话定时任务(详情 schedule 字段,null=无)
sessions: [], // 抽屉列表缓存
attachments: [], // 待发送附件 {file, name, size}
editingMsgId: 0, // 正在编辑的历史消息 id(0=普通发送,覆盖式重发)
lastImgBlobUrl: null, // 任务文件图片预览的 blob URL,下次预览或开新图时回收
lastPdfBlobUrl: null, // 同上:PDF 页内预览的 blob URL(浏览器内建查看器用)
es: null, // EventSource
+3
View File
@@ -86,6 +86,7 @@
state.lastRenderedMsgId = 0;
state.renderedSigs = {};
state.streaming = false;
if (typeof clearEditState === 'function') clearEditState();
setView('welcome'); // 复用 newChat 同样的视图切换路径
}
toast('已删除会话');
@@ -200,6 +201,7 @@
state.toolCallStreaming = {}; // 流式参数早卡映射随会话/回合重置
state.streaming = false;
state.attachments = [];
if (typeof clearEditState === 'function') clearEditState();
userPaused = false;
state.chatHasMore = false; // 分页状态先复位:防详情返回前用旧会话的游标/标志拉到错会话的消息
state.chatOldestId = null;
@@ -249,6 +251,7 @@
state.schedule = null;
state.pendingModel = '';
state.attachments = [];
if (typeof clearEditState === 'function') clearEditState();
state.streamEl = null;
state.streamText = '';
state.toolCards = {};
+79 -3
View File
@@ -17,6 +17,7 @@
async function send() {
const ta = $('msg-input');
const content = ta.value.trim();
const editingId = state.editingMsgId || 0;
// 没有文字就不发(避免产生空消息);但只有附件时允许发送——粘贴长文本转成的 .txt 需要能单独发出。
// 运行中也是这条规则:有字就发(后端 live 追投),没字又没附件时按钮本身是「停止」。
if (!content && !state.attachments.length) return;
@@ -28,6 +29,7 @@
autosize();
updateSendBtn(); // 清空后若仍在生成中,按钮应回到「停止」
let domDropped = false;
try {
const id = await ensureSession();
let atts = [];
@@ -42,7 +44,16 @@
? '用户上传了文件:' + names.join('、') + (content ? '\n\n' + content : '')
: content;
const body = { content: text, deepThink: !!state.deepThink };
const sent = await req('POST', '/api/sessions/' + id + '/messages', body);
let sent;
if (editingId) {
// 覆盖式编辑:先撤掉本地该条及其后的渲染,再让服务端删除同范围历史并以新内容重开一轮
dropDomFromMessage(editingId);
domDropped = true;
sent = await req('POST', '/api/sessions/' + id + '/messages/' + editingId + '/edit', body);
clearEditState();
} else {
sent = await req('POST', '/api/sessions/' + id + '/messages', body);
}
clearUploadCards(); // 消息已发出(告知行已拼入正文),卡片使命完成清掉
appendUserMsg(text, atts.map(a => a.name), sent && sent.message_id);
@@ -66,6 +77,8 @@
autosize();
}
updateSendBtn(); // 文字/附件都可能被还原:按当前状态刷新发送键(附件在时不能停在停止态)
// 编辑请求失败(如运行中 409):服务端历史未动,把被乐观撤掉的节点重拉回来
if (domDropped) restoreChatView();
toast('发送失败:' + e.message);
}
}
@@ -435,6 +448,69 @@
}
});
// ---------- 编辑已发送的用户消息(覆盖式) ----------
// 发送时服务端会删除该条及其后的全部历史(含工具回执/摘要),前端同步丢弃同范围的 DOM。
// 已压缩存档的消息(type='archived')不给编辑入口:删掉摘要后它前面的行仍不发模型,上下文会断。
function clearEditState() {
state.editingMsgId = 0;
const bar = $('edit-bar');
if (bar) bar.classList.add('hidden');
}
function setEditState(msgId) {
state.editingMsgId = msgId;
const bar = $('edit-bar');
if (bar) bar.classList.remove('hidden');
}
// 乐观撤场:删掉该条及之后的所有节点(旧工具卡/打字点/流式气泡都在后面),
// 并把增量渲染游标回退到编辑点之前,免得后续软补拉把已丢的行当成还在。
function dropDomFromMessage(msgId) {
const box = $('chat-view');
const btn = box && box.querySelector('[data-msg-id="' + msgId + '"]');
const node = btn && btn.closest('.msg');
if (!node) return false;
let n = node;
while (n) { const next = n.nextElementSibling; n.remove(); n = next; }
let max = 0;
for (const k of Object.keys(state.renderedSigs)) {
const id = Number(k);
if (id >= msgId) delete state.renderedSigs[k];
else if (id > max) max = id;
}
state.lastRenderedMsgId = max;
return true;
}
// 编辑失败(如运行中 409):服务端没动历史,重拉已加载量恢复被乐观撤掉的节点。
async function restoreChatView() {
try {
const detail = await req('GET', '/api/sessions/' + state.sessionId + '?limit=' + Math.max(CHAT_PAGE_SIZE, state.chatLoadedCount));
if (state.view === 'chat') renderDetail(detail);
} catch (_) { /* 恢复失败不阻断主流程 */ }
}
$('chat-view').addEventListener('click', e => {
const btn = e.target.closest('.act-edit');
if (!btn) return;
const msgId = Number(btn.dataset.msgId);
if (!msgId || !state.sessionId) return;
if (state.status === 'active') { toast('任务执行中,暂不支持编辑'); return; }
let text = '';
try { text = decodeURIComponent(escape(atob(btn.dataset.b64 || ''))); } catch (_) { return; }
const ta = $('msg-input');
ta.value = text;
autosize();
updateSendBtn();
setEditState(msgId);
ta.focus();
try { ta.setSelectionRange(text.length, text.length); } catch (_) {}
});
$('edit-cancel').addEventListener('click', () => {
clearEditState();
const ta = $('msg-input');
ta.value = '';
autosize();
updateSendBtn();
ta.focus();
});
// ---------- 全屏查看器(双击气泡/工具卡放大;图片单击放大;均同步 index) ----------
// 源码查看:当前内容有源文本时(消息/文件预览)右上角 eye 钮可点,源码面板与渲染视图互切。
// 源文本两条来路:预览调用方直接传(文件原文);双击消息时从尾部操作行复制钮取
@@ -476,8 +552,8 @@
clone.querySelectorAll('[id]').forEach(function (n) { n.removeAttribute('id'); });
// 全屏查看直接展开参数/结果,方便观看
clone.querySelectorAll('details').forEach(function (d) { d.open = true; });
// 克隆里摘掉删除钮:删除的委托绑在 chat-view,查看器里点了无响应,不留死按钮
clone.querySelectorAll('.act-del').forEach(function (n) { n.remove(); });
// 克隆里摘掉删除/编辑钮:二者的委托绑在 chat-view,查看器里点了无响应,不留死按钮
clone.querySelectorAll('.act-del, .act-edit').forEach(function (n) { n.remove(); });
// 源文本:调用方传入优先(文件预览),否则从消息自带 b64 现取(双击场景)
let s = src;
if (s == null) {
+11
View File
@@ -28,6 +28,17 @@ router.post('/:id/messages', wrap((req, res) => {
}));
// 覆盖式编辑:删除该条及其后的历史,再以新内容重开一轮(运行中 409)。
router.post('/:id/messages/:mid/edit', wrap((req, res) => {
const content = String((req.body && req.body.content) || '').trim();
if (!content) return res.status(400).json({ error: 'content 不能为空' });
const deepThink = !!(req.body && req.body.deepThink);
const r = engine.editUserMessage(req.params.id, Number(req.params.mid), content, { deepThink });
log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 编辑消息 ' + req.params.mid +
'(丢弃其后 ' + Math.max(0, (r.removed || 1) - 1) + ' 条)');
res.json(r);
}));
router.post('/:id/stop', wrap((req, res) => {
const r = engine.stop(req.params.id);
log.info('msg', (req.user || '-') + ' ' + req.params.id + ' 用户终止');