修复:tool 卡懒加载落到实际视图 index.html(此前误改了已废弃的 js/tasks.js)

根因:index.html 是自闭合内联脚本(不加载 js/tasks.js),历史渲染依赖
role=tool 消息回填工具卡;上一提交把 tool 消息从接口移除后,所有卡停在执行中…。

index.html:
- renderDetail 收集 assistant 消息的 tool_call_msg_ids 映射,首次展开 tool 卡时
  经 GET /api/sessions/:id/messages/:mid 懒加载回填(toggle 捕获阶段代理,只挂钩一次)
- parseToolContent 兼容剥掉历史行里的「,图片见同条消息的 image_url 内容块」尾巴
- 实时回合卡片无映射条目自然跳过,仍由 SSE tool_result 填充,不受影响

executor.js:
- read_file 读图文案去掉「图片见同条消息的 image_url 内容块」

js/tasks.js: 回滚到改动前(死代码,不再保留半套修改)
This commit is contained in:
2026-09-07 12:52:35 +08:00
parent 9db3511710
commit 937b6fa671
3 changed files with 48 additions and 79 deletions
+45 -1
View File
@@ -479,6 +479,7 @@
streamReasoning: '', // 当前流式累积思考文本
streamThinkEl: null, // 当前流式思考面板的 body 节点(未出现思考时为 null)
toolCards: {}, // tool_call_id -> 工具卡片元素(同步 index 工具卡样式)
toolCallMsgIds: {}, // tool_call_id -> tool 消息行 id(历史懒加载映射,renderDetail 重建)
typingEl: null, // 「思考中」占位
streaming: false,
pendingSummary: false, // 是否在等待「压缩」总结 AI 回复(避免重复弹窗;同时用于按钮 disabled 防重入)
@@ -656,13 +657,14 @@
return div;
}
// tool 消息 content:纯文本,或含图片时的哨兵 JSON {"__blocks__":[...]}(read_file 读图回传)
// 顺手剥掉旧数据里的「,图片见同条消息的 image_url 内容块」尾巴(新版文案已去掉,历史行还在库里)
function parseToolContent(content) {
if (typeof content === 'string' && content.startsWith('{"__blocks__":')) {
try {
const blocks = JSON.parse(content).__blocks__ || [];
const img = blocks.find(b => b.type === 'image_url');
return {
text: blocks.filter(b => b.type === 'text').map(b => b.text).join('\n'),
text: blocks.filter(b => b.type === 'text').map(b => (b.text || '').replace(/,图片见同条消息的 image_url 内容块/g, '')).join('\n'),
imageUrl: img && img.image_url && img.image_url.url || null,
};
} catch (_) { /* 解析失败按原文显示 */ }
@@ -712,6 +714,45 @@
}
}
// ---------- tool 卡懒加载 ----------
// 历史接口不再返回 role=tool 消息(内容大、含 base64 图片);assistant 消息附带
// tool_call_msg_ids 映射(tool_call.id → tool 消息行 id)。首次展开卡片时才拉取全文回填。
function hookToolCardLazyLoad() {
const box = $('chat-view');
if (!box || box.dataset.toolLazyHooked) return;
box.dataset.toolLazyHooked = '1';
// toggle 事件不冒泡,用捕获阶段代理到列表容器
box.addEventListener('toggle', e => {
const details = e.target;
if (!details || details.tagName !== 'DETAILS') return;
const card = details.closest('.tool-card');
if (!card) return;
const pre = card.querySelector('.tool-result');
// 仍是占位文案才拉取(已回填/流式输出中/加载失败复位后的文案都偏离占位时不重复触发)
if (pre && pre.textContent !== '执行中…') return;
loadToolCardContent(card);
}, true);
}
async function loadToolCardContent(card) {
const toolCallId = card.id.replace(/^tool-/, '');
const msgId = state.toolCallMsgIds && state.toolCallMsgIds[toolCallId];
if (!msgId || card.dataset.loading) return; // 无映射(tool 结果尚未产出/实时回合):SSE 会自己填
card.dataset.loading = '1';
const pre = card.querySelector('.tool-result');
if (pre) pre.textContent = '加载中…';
try {
const m = await req('GET', '/api/sessions/' + state.sessionId + '/messages/' + msgId);
if (m && m.role === 'tool') fillToolResult(toolCallId, m.content, !!m.is_error, undefined, m.id);
else if (pre) pre.textContent = '(无结果)';
} catch (_) {
// 复位占位,再次折叠/展开可重试
if (pre) pre.textContent = '执行中…';
} finally {
delete card.dataset.loading;
}
}
function msgNode(m) {
if (m.role === 'user') return userMsgHtml(m);
// 被「压缩总结」标记的摘要消息:重渲染成摘要卡片,而不是普通 AI 气泡
@@ -725,6 +766,7 @@
state.sessionType = (s && s.assistant_type) || 'secretary'; // 顶部 icon 跟随会话类型
state.status = (s && s.status) || '';
state.toolCards = {};
state.toolCallMsgIds = {}; // tool_call.id → tool 消息行 id(展开时懒加载用)
userPaused = false;
removeTyping();
renderHeader();
@@ -750,6 +792,7 @@
}
const node = msgNode(m);
if (node) target.insertAdjacentHTML('beforeend', node);
if (m.role === 'assistant' && m.tool_call_msg_ids) Object.assign(state.toolCallMsgIds, m.tool_call_msg_ids);
if (m.role === 'assistant') appendToolCardsFromAssistant(m, target);
else if (m.role === 'tool' && m.tool_call_id) fillToolResult(m.tool_call_id, m.content, !!m.is_error, undefined, m.id);
}
@@ -757,6 +800,7 @@
if (!(detail.messages || []).length) {
box.innerHTML = '<div class="drawer-empty">描述你的需求,AI 会和你讨论并直接干活。</div>';
}
hookToolCardLazyLoad();
scrollBottom();
updateScrollBottomBtn();
}
+2 -77
View File
@@ -339,10 +339,9 @@ function parseToolContent(content) {
return { text: content, imageUrl: null };
}
function fillToolResult(id, content, isError, liveImageUrl, hasImage, msgId) {
function fillToolResult(id, content, isError, liveImageUrl) {
const card = document.getElementById('tool-' + id);
if (!card) return;
if (msgId) card.dataset.msgId = msgId;
if (isError) card.classList.add('error');
card.querySelector('.spin').textContent = isError ? '✕' : '✓';
const parsed = parseToolContent(content);
@@ -361,36 +360,6 @@ function fillToolResult(id, content, isError, liveImageUrl, hasImage, msgId) {
el.src = img;
el.title = '点击放大查看';
pre.insertAdjacentElement('afterend', el);
} else if (!img && hasImage && !card.querySelector('.tool-img-load')) {
// base64 已剥离且非实时图片时,显示「加载图片」按钮(按需从服务端获取)
const btn = document.createElement('button');
btn.className = 'tool-img-load';
btn.textContent = '加载图片';
btn.title = '点击加载图片';
btn.style.marginTop = '4px';
btn.onclick = async function () {
btn.textContent = '加载中…';
btn.disabled = true;
try {
const mid = card.dataset.msgId;
const sessionId = state.sessionId;
if (!mid || !sessionId) { btn.textContent = '加载失败'; return; }
const resp = await fetch('/api/sessions/' + sessionId + '/messages/' + mid + '/image');
if (!resp.ok) throw new Error('加载失败');
const blob = await resp.blob();
const url = URL.createObjectURL(blob);
const el = document.createElement('img');
el.className = 'tool-img';
el.src = url;
el.title = '点击放大查看';
btn.insertAdjacentElement('afterend', el);
btn.remove();
} catch (e) {
btn.textContent = '加载失败';
btn.disabled = false;
}
};
pre.insertAdjacentElement('afterend', btn);
}
}
@@ -409,7 +378,7 @@ function copyBtnHtml(text) {
function msgNode(m, cardMap) {
if (m.role === 'tool') {
if (m.tool_call_id && cardMap && cardMap[m.tool_call_id]) {
fillToolResult(m.tool_call_id, m.content, false, null, m.hasImage, m.id);
fillToolResult(m.tool_call_id, m.content, false);
}
return null;
}
@@ -458,8 +427,6 @@ async function renderDetail(detail) {
state.streamText = '';
state.turnEl = null;
state.toolCards = {};
// tool_call_id → message id 映射(从 assistant 消息的 tool_call_msg_ids 字段构建)
state.toolCallMsgIds = {};
// 切换会话后重置滚动跟随状态
userPaused = false;
state.streaming = false;
@@ -471,10 +438,6 @@ async function renderDetail(detail) {
updateScrollBottomBtn(); // 打开仍在运行中的会话时,立即恢复右下角转圈
$('chat-title').textContent = s.title || s.id;
for (const m of detail.messages) {
// 收集 tool_call_msg_ids(assistant 消息携带的 tool_call_id → message_id 映射)
if (m.role === 'assistant' && m.tool_call_msg_ids) {
Object.assign(state.toolCallMsgIds, m.tool_call_msg_ids);
}
const node = msgNode(m, state.toolCards);
if (node) box.appendChild(node);
if (m.role === 'assistant') appendToolCardsFromAssistant(m, box);
@@ -482,48 +445,10 @@ async function renderDetail(detail) {
if (!detail.messages.length) {
box.innerHTML = '<div class="empty-tip">描述你的需求,AI 会和你讨论并直接干活。</div>';
}
// 事件委托:tool card 的 <details> 展开时懒加载内容
box.addEventListener('toggle', e => {
const details = e.target.closest('details');
if (!details) return;
const card = details.closest('.tool-card');
if (!card) return;
const toolCallId = card.id.replace(/^tool-/, '');
const pre = card.querySelector('.tool-result');
// 内容为空或"执行中…"才需要加载(避免重复加载)
if (!pre || pre.textContent === '执行中…') {
loadToolCardContent(card, toolCallId);
}
}, true);
scrollBottom();
loadFiles();
}
// 懒加载 tool card 内容:按需从服务端获取 tool 消息完整 content(含 base64 图片)
async function loadToolCardContent(card, toolCallId) {
const msgId = state.toolCallMsgIds && state.toolCallMsgIds[toolCallId];
if (!msgId) {
// 映射不存在(不应该),什么也不做
return;
}
try {
const resp = await fetch('/api/sessions/' + state.sessionId + '/messages/' + msgId);
if (!resp.ok) return;
const msg = await resp.json();
if (msg.role !== 'tool') return;
// 解析 image_url(parseToolContent 依赖 content 格式)
let imageUrl = null;
if (typeof msg.content === 'string' && msg.content.startsWith('{"__blocks__":')) {
try {
const blocks = JSON.parse(msg.content).__blocks__ || [];
const img = blocks.find(b => b && b.type === 'image_url');
imageUrl = img && img.image_url && img.image_url.url || null;
} catch (_) {}
}
fillToolResult(toolCallId, msg.content, false, imageUrl, false, msg.id);
} catch (_) {}
}
// ---------- 滚动跟随 ----------
// 判断是否「贴近底部」:用户在底部附近时,新内容到来自动滚动跟随;
// 一旦手动上翻阅读历史,暂停自动滚动以免打斷阅读。