feat: terminal 执行中增量输出走 SSE(tool_output),工具卡实时滚动

This commit is contained in:
2026-11-20 11:03:18 +08:00
parent 02c154ae24
commit ba20a4f39d
5 changed files with 42 additions and 5 deletions
+12
View File
@@ -1048,9 +1048,20 @@ async function runLoopInner(sessionId, run) {
output = chk.error; output = chk.error;
isError = true; isError = true;
} else { } else {
// 工具执行中的增量输出(terminal 长命令):50ms 或 16KB 合并成一帧 SSE,避免逐行刷包
let liveBuf = '';
let liveTimer = null;
const flushLive = () => {
if (liveTimer) { clearTimeout(liveTimer); liveTimer = null; }
if (!liveBuf) return;
const chunk = liveBuf;
liveBuf = '';
bus.emit(sessionId, 'tool_output', { id, chunk });
};
try { try {
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), workDir: sessionWorkDir(sessionId), run, cfg, db, vision, output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), workDir: sessionWorkDir(sessionId), run, cfg, db, vision,
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card), onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card),
onOutput: (s) => { liveBuf += s; if (liveBuf.length >= 16384) flushLive(); else if (!liveTimer) liveTimer = setTimeout(flushLive, 50); },
onDeepThink: (info) => { onDeepThink: (info) => {
const m = (cfg.models || []).find(x => x.id === session.model_id); const m = (cfg.models || []).find(x => x.id === session.model_id);
const supported = !!(m && m.thinking_params && Object.keys(m.thinking_params).length); const supported = !!(m && m.thinking_params && Object.keys(m.thinking_params).length);
@@ -1063,6 +1074,7 @@ async function runLoopInner(sessionId, run) {
output = 'Error: ' + (err && err.message || String(err)); output = 'Error: ' + (err && err.message || String(err));
isError = true; isError = true;
} }
flushLive();
} }
// 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/, // 工具可返回 {text, image_rel}(read_file 读图且模型支持 vision,压缩产物在 .imgcache/,
// text 是 imageReceipt 生成的结构化 JSON 回执):落库时以 image_ref 内容块拼进 tool 消息 // text 是 imageReceipt 生成的结构化 JSON 回执):落库时以 image_ref 内容块拼进 tool 消息
+13
View File
@@ -274,6 +274,19 @@
pre.insertAdjacentElement('afterend', el); pre.insertAdjacentElement('afterend', el);
} }
} }
// 工具执行中的增量输出(terminal 长命令):边跑边填;只留尾部 2000 行,避免长跑命令撑爆 DOM
function appendToolOutput(id, chunk) {
const card = document.getElementById('tool-' + id);
if (!card) return;
const pre = card.querySelector('.tool-result');
if (!pre) return;
if (!pre.dataset.streaming) { pre.textContent = ''; pre.dataset.streaming = '1'; } // 首块到达:清掉“执行中…”占位
const follow = pre.scrollHeight - pre.scrollTop - pre.clientHeight < 40; // 用户往上翻时不抢滚动
pre.appendChild(document.createTextNode(chunk));
const lines = pre.textContent.split('\n');
if (lines.length > 2000) pre.textContent = '…(更早输出已折叠)\n' + lines.slice(-2000).join('\n');
if (follow) pre.scrollTop = pre.scrollHeight;
}
// 把 assistant 消息里的 tool_calls 建成工具卡片(历史渲染与 assistant_message 事件共用) // 把 assistant 消息里的 tool_calls 建成工具卡片(历史渲染与 assistant_message 事件共用)
function appendToolCardsFromAssistant(m, container) { function appendToolCardsFromAssistant(m, container) {
if (!m.tool_calls) return; if (!m.tool_calls) return;
+5 -1
View File
@@ -243,7 +243,7 @@
state.lastSseAt = Date.now(); // 建连即重置静默计时 state.lastSseAt = Date.now(); // 建连即重置静默计时
// 任何具名事件都算连接存活:静默看门狗与回前台宽限共用(error 不列,原生连接错误也走 error) // 任何具名事件都算连接存活:静默看门狗与回前台宽限共用(error 不列,原生连接错误也走 error)
['ping', 'status', 'assistant_delta', 'reasoning_delta', 'assistant_message', 'tool_call_start', ['ping', 'status', 'assistant_delta', 'reasoning_delta', 'assistant_message', 'tool_call_start',
'tool_call_args', 'tool_call', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title', 'think_auto', 'tool_call_args', 'tool_call', 'tool_output', 'tool_result', 'ui_card', 'auto_compress', 'done', 'title', 'think_auto',
'pending_added', 'pending_removed', 'user_message'] 'pending_added', 'pending_removed', 'user_message']
.forEach(function (n) { es.addEventListener(n, function () { markSseAlive(n); }); }); .forEach(function (n) { es.addEventListener(n, function () { markSseAlive(n); }); });
es.addEventListener('status', ev => { es.addEventListener('status', ev => {
@@ -424,6 +424,10 @@
state.toolCards[d.id] = card; state.toolCards[d.id] = card;
maybeAutoScroll(); maybeAutoScroll();
}); });
es.addEventListener('tool_output', ev => {
const d = JSON.parse(ev.data);
appendToolOutput(d.id, d.chunk);
});
es.addEventListener('tool_result', ev => { es.addEventListener('tool_result', ev => {
const d = JSON.parse(ev.data); const d = JSON.parse(ev.data);
fillToolResult(d.tool_call_id, d.content, d.is_error, d.image_url, d.msg_id); fillToolResult(d.tool_call_id, d.content, d.is_error, d.image_url, d.msg_id);
+6 -2
View File
@@ -19,7 +19,7 @@ function reqHeaders(cfg) {
} }
// 执行一条命令。返回 { code, killed_by, out };传输层失败抛 Error(由调用方决定如何呈现)。 // 执行一条命令。返回 { code, killed_by, out };传输层失败抛 Error(由调用方决定如何呈现)。
// opts: { command, cwd?, timeout_ms?, env?, run? }(run = engine 的 {cancelled, procs},可省略) // opts: { command, cwd?, timeout_ms?, env?, run?, onChunk? }(run = engine 的 {cancelled, procs},可省略)
async function run(cfg, opts) { async function run(cfg, opts) {
const base = cfg.executor.url; const base = cfg.executor.url;
const timeoutMs = opts.timeout_ms && opts.timeout_ms > 0 ? opts.timeout_ms : 300000; const timeoutMs = opts.timeout_ms && opts.timeout_ms > 0 ? opts.timeout_ms : 300000;
@@ -73,7 +73,11 @@ async function run(cfg, opts) {
let ev; let ev;
try { ev = JSON.parse(line.slice(6)); } catch (_) { continue; } try { ev = JSON.parse(line.slice(6)); } catch (_) { continue; }
if (ev.type === 'start') id = ev.id; if (ev.type === 'start') id = ev.id;
else if (ev.type === 'out' || ev.type === 'err') out += ev.chunk; else if (ev.type === 'out' || ev.type === 'err') {
out += ev.chunk;
// 增量回调(UI 实时显示用):失败不影响主流程
if (opts.onChunk) { try { opts.onChunk(ev.chunk); } catch (_) {} }
}
else if (ev.type === 'exit') { exit = ev; break outer; } else if (ev.type === 'exit') { exit = ev; break outer; }
} }
} }
+6 -2
View File
@@ -905,7 +905,7 @@ async function toolTerminal(ctx, args) {
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。 // 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
if (rexec.isRemote(cfg)) { if (rexec.isRemote(cfg)) {
const r = await rexec.run(cfg, { command: args.command, cwd, timeout_ms: timeout, run: ctx.run }); const r = await rexec.run(cfg, { command: args.command, cwd, timeout_ms: timeout, run: ctx.run, onChunk: ctx.onOutput });
r.out = drainUiCards(r.out, ctx); r.out = drainUiCards(r.out, ctx);
let text = selectOutput(r.out.replace(/\n+$/, ''), args.head_lines, args.tail_lines); let text = selectOutput(r.out.replace(/\n+$/, ''), args.head_lines, args.tail_lines);
if (r.killed_by === 'timeout') { if (r.killed_by === 'timeout') {
@@ -931,7 +931,11 @@ async function toolTerminal(ctx, args) {
killGroup(child); killGroup(child);
}, timeout); }, timeout);
const onData = (d) => { out += d.toString(); }; const onData = (d) => {
const s = d.toString();
out += s;
if (ctx.onOutput) { try { ctx.onOutput(s); } catch (_) {} }
};
child.stdout.on('data', onData); child.stdout.on('data', onData);
child.stderr.on('data', onData); child.stderr.on('data', onData);