Files
agent/app/server/routes/sessions.js
T
kicer 9db3511710 优化:不传 tool 消息,tool card 展开时按需加载内容
彻底不传 role=tool 消息,API 体积大幅缩小。

sessions.js:
- GET /:id:过滤掉 tool 消息;但为 assistant 消息附加 tool_call_msg_ids 映射
  (tool_call.id → message.id),供前端懒加载用
- GET /:id/messages/:mid:返回单条消息完整内容(供懒加载调用)

tasks.js:
- renderDetail:构建并存储 toolCallMsgIds 映射
- 新增 loadToolCardContent():按 tool_call_id 懒加载对应 tool 消息 content
- tool card 的 <details> 展开时自动触发懒加载
- SSE tool_result 路径完全不受影响(仍直接内联 liveImageUrl)

效果:初始加载仅传文本,tool 内容(及图片)仅在展开 tool 卡时才按需获取。
2026-09-07 12:30:14 +08:00

203 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 会话管理 API(README 10.1)
const express = require('express');
const fs = require('fs');
const path = require('path');
const engine = require('../engine');
const log = require('../log');
const router = express.Router();
function wrap(fn) {
return function (req, res) {
try {
const r = fn(req, res);
if (r && typeof r.catch === 'function') {
r.catch(err => sendErr(res, err));
}
} catch (err) {
sendErr(res, err);
}
};
}
function sendErr(res, err) {
const code = err && err.status_code || 500;
res.status(code).json({ error: String(err && err.message || err) });
}
// 按需加载单条消息的完整内容(用于 tool 消息的懒加载)。
// 返回消息行原始 content(含 base64 图片),前端负责渲染。
function getMessage(req, res) {
const session = engine.getSession(req.params.id);
if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 }));
const db = engine.getDb();
const row = db.prepare(
'SELECT id, role, content, reasoning, tool_calls, tool_call_id, name, type, is_error, created_at FROM messages WHERE id = ? AND session_id = ?'
).get(req.params.mid, req.params.id);
if (!row) return sendErr(res, Object.assign(new Error('消息不存在'), { status_code: 404 }));
res.json(row);
}
// 递归列出任务目录文件
function listTaskFiles(dir) {
const out = [];
(function rec(d, rel) {
let entries;
try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch (_) { return; }
for (const e of entries) {
const abs = path.join(d, e.name);
const relPath = rel ? rel + '/' + e.name : e.name;
if (e.isDirectory()) rec(abs, relPath);
else if (e.isFile()) {
let size = null, mtime = null, ctime = null;
// birthtime 在部分文件系统不可用(返回 0),回退 mtime;新生成/上传的文件两者基本一致
try {
const st = fs.statSync(abs);
size = st.size; mtime = st.mtimeMs;
ctime = (st.birthtimeMs && st.birthtimeMs > 0 ? st.birthtimeMs : st.mtimeMs) || null;
} catch (_) {}
out.push({ filename: relPath, size, mtime, ctime });
}
}
})(dir, '');
// 按创建时间倒序(最新在前)方便查找;同一时刻按文件名升序保证稳定
out.sort(function (a, b) {
const ca = a.ctime || a.mtime || 0, cb = b.ctime || b.mtime || 0;
if (cb !== ca) return cb - ca;
return a.filename < b.filename ? -1 : a.filename > b.filename ? 1 : 0;
});
return out;
}
router.post('/', wrap((req, res) => {
const title = (req.body && req.body.title || '').trim();
const modelId = (req.body && req.body.model_id || '').trim();
// 助手类型建档时锁定,后续不可变更;缺省按文秘助理
const assistantType = String((req.body && req.body.assistant_type) || 'secretary').trim().slice(0, 32) || 'secretary';
// 创建者取认证中间件的 req.user(不信客户端传参);未启用认证时为空串
const user = String(req.user || '').trim().slice(0, 64);
const session = engine.createSession(title, modelId, assistantType, user);
log.info('task', (req.user || '-') + ' 新建任务 ' + session.id + '「' + (session.title || '未命名') + '」model=' + (modelId || '自动') + ' type=' + (session.assistant_type || 'secretary'));
res.json(session);
}));
// 列表查询参数(2.0):
// status=active|done|all 归档分组:active=排队/活跃/保持,done=已完成/已终止
// q=关键词 标题或消息内容 LIKE 搜索
// before + before_id 游标分页(上一页末行的 updated_at,id),避免 offset 翻页在
// updated_at 变动时重复/漏行
// with_total=1 返回 {rows,total}(归档折叠区需要总数);默认仍返回纯数组
router.get('/', wrap((req, res) => {
const db = engine.getDb();
const status = String(req.query.status || 'all');
const q = String(req.query.q || '').trim();
let limit = parseInt(req.query.limit, 10);
if (!Number.isFinite(limit) || limit < 1) limit = 50;
if (limit > 200) limit = 200;
const where = [];
const args = [];
// 按创建者隔离:已登录只列自己的会话;未启用认证(req.user 空)不过滤,保持自用场景全可见
const me = String(req.user || '').trim();
if (me) { where.push('user = ?'); args.push(me); }
if (status === 'active') where.push("status IN ('queued','active','held')");
else if (status === 'done') where.push("status IN ('completed','cancelled')");
if (q) {
where.push('(title LIKE ? OR EXISTS(SELECT 1 FROM messages m WHERE m.session_id = sessions.id AND m.content LIKE ?))');
args.push('%' + q + '%', '%' + q + '%');
}
const before = req.query.before;
const beforeId = req.query.before_id;
if (before != null && before !== '' && beforeId) {
where.push('(updated_at < ? OR (updated_at = ? AND id < ?))');
args.push(String(before), String(before), String(beforeId));
}
const whereSql = where.length ? ' WHERE ' + where.join(' AND ') : '';
const stmt = db.prepare(
'SELECT * FROM sessions' + whereSql + ' ORDER BY updated_at DESC, id DESC LIMIT ?'
);
const rows = stmt.all.apply(stmt, args.concat([limit]));
const qpos = db.prepare(
'SELECT session_id, ROW_NUMBER() OVER (ORDER BY queued_at, id) AS pos FROM wait_queue'
).all();
const posMap = {};
for (const r of qpos) posMap[r.session_id] = r.pos;
for (const row of rows) {
row.queue_pos = row.status === 'queued' ? (posMap[row.id] || null) : null;
}
if (req.query.with_total === '1') {
const cnt = db.prepare('SELECT COUNT(*) AS n FROM sessions' + whereSql);
const total = cnt.all.apply(cnt, args)[0].n;
return res.json({ rows: rows, total: total });
}
res.json(rows);
}));
router.get('/:id', wrap((req, res) => {
const session = engine.getSession(req.params.id);
if (!session) return sendErr(res, Object.assign(new Error('会话不存在'), { status_code: 404 }));
const db = engine.getDb();
// 查询所有消息,tool 消息用于建立 tool_call_id → message_id 映射,但不随消息返回
const allRows = db.prepare(
'SELECT id, role, content, reasoning, tool_calls, tool_call_id, name, type, is_error, created_at FROM messages WHERE session_id = ? ORDER BY id'
).all(session.id);
// 建立 tool_call_id → message_id 映射(供 assistant 消息的 tool_calls 展开时懒加载用)
const toolCallMsgMap = {}; // tool_call_id → message id
for (const row of allRows) {
if (row.role === 'tool' && row.tool_call_id) {
toolCallMsgMap[row.tool_call_id] = row.id;
}
}
// 过滤掉 tool 消息,但为 assistant 消息附带 tool_call 懒加载映射
const messages = [];
for (const row of allRows) {
if (row.role === 'tool') continue;
// assistant 消息附加 tool_call_msg_ids(让前端知道展开时去拉哪条消息)
if (row.role === 'assistant' && row.tool_calls) {
let toolCalls;
try { toolCalls = JSON.parse(row.tool_calls); } catch (_) { toolCalls = []; }
const tool_call_msg_ids = {};
for (const tc of toolCalls) {
if (tc && tc.id && toolCallMsgMap[tc.id]) {
tool_call_msg_ids[tc.id] = toolCallMsgMap[tc.id];
}
}
row.tool_call_msg_ids = Object.keys(tool_call_msg_ids).length ? tool_call_msg_ids : undefined;
}
messages.push(row);
}
const taskDir = engine.taskDirOf(session.id);
res.json({
session,
messages,
files: listTaskFiles(taskDir),
queue_pos: session.status === 'queued' ? engine.queuePosition(session.id) : null,
running: !!(engine.getRun(session.id) || {}).looping,
});
}));
// 按需加载单条消息的完整内容(用于 tool 消息的懒加载)
router.get('/:id/messages/:mid', wrap(getMessage));
router.post('/:id/bind', wrap((req, res) => {
res.json(engine.bindToSession(req.params.id, req.body && req.body.model_id));
}));
router.patch('/:id', wrap((req, res) => {
res.json(engine.renameSession(req.params.id, req.body && req.body.title));
}));
router.delete('/:id', wrap((req, res) => {
const delDir = req.query.delete_dir === 'true' || req.query.delete_dir === '';
log.info('task', (req.user || '-') + ' 删除任务 ' + req.params.id + (delDir ? '(含任务目录)' : ''));
res.json(engine.deleteSession(req.params.id, delDir));
}));
module.exports = router;
module.exports.listTaskFiles = listTaskFiles;