按 README 设计方案实现 Agent 系统 app/:多模型 FIFO 调度、Agent 主循环、13 个沙箱工具(web_search 走内网 MCP)、H5 前端(SSE 流式)、Docker 部署与端到端冒烟测试(25/25 通过)

This commit is contained in:
2026-08-31 06:57:38 +08:00
parent 4e6c1b0121
commit 677b70cffe
28 changed files with 4876 additions and 0 deletions
+237
View File
@@ -0,0 +1,237 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; overscroll-behavior: none; }
body {
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", Helvetica, Arial, sans-serif;
background: #f2f3f7;
font-size: 15px;
color: #222;
}
.app { height: 100vh; height: 100dvh; overflow: hidden; position: relative; }
.hidden { display: none !important; }
/* ---- 页面滑动 ---- */
.page {
position: absolute; inset: 0;
display: flex; flex-direction: column;
background: #f2f3f7;
transition: transform 0.28s ease;
will-change: transform;
}
.page.off-right { transform: translateX(100%); }
.page.off-left { transform: translateX(-100%); }
/* ---- 顶部栏 ---- */
.header {
display: flex; align-items: center;
background: linear-gradient(135deg, #1e3c72, #2a5299);
color: #fff; padding: 12px 12px;
padding-top: calc(12px + env(safe-area-inset-top));
gap: 8px;
}
.header-left { display: flex; align-items: center; gap: 8px; flex: 1; }
.header h2 { font-size: 17px; font-weight: 600; white-space: nowrap; }
.chat-title {
flex: 1; text-align: center; font-size: 16px; font-weight: 600;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.header-right { display: flex; gap: 2px; }
.icon-btn {
background: none; border: none; cursor: pointer;
width: 36px; height: 36px; border-radius: 8px;
display: inline-flex; align-items: center; justify-content: center;
color: #fff;
}
.icon-btn:active { background: rgba(255,255,255,0.15); }
.icon-btn svg { width: 22px; height: 22px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
#files-panel .icon-btn, .files-panel-header .icon-btn { color: #555; }
#files-panel .icon-btn:active { background: #eee; }
/* ---- 模型池条 ---- */
.model-strip {
display: flex; gap: 6px; padding: 8px 12px 0;
flex-wrap: wrap;
}
.model-chip {
font-size: 11px; padding: 3px 8px; border-radius: 10px;
background: #e3f2e6; color: #217a34;
}
.model-chip.busy { background: #fdecea; color: #b3382c; }
/* ---- 会话列表 ---- */
.session-list { flex: 1; overflow-y: auto; padding: 10px 12px calc(16px + env(safe-area-inset-bottom)); }
.session-card {
background: #fff; border-radius: 12px; padding: 12px 14px; margin-bottom: 10px;
box-shadow: 0 1px 4px rgba(30,40,90,0.06);
display: flex; align-items: center; gap: 10px; cursor: pointer;
}
.session-card:active { background: #f7f8fb; }
.session-main { flex: 1; overflow: hidden; }
.session-name { font-weight: 600; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.session-meta { font-size: 12px; color: #888; margin-top: 3px; display: flex; gap: 8px; flex-wrap: wrap; }
.badge { font-size: 11px; padding: 1px 7px; border-radius: 8px; white-space: nowrap; }
.badge.active { background: #e3f2e6; color: #217a34; }
.badge.queued { background: #fff4dc; color: #a06a00; }
.badge.completed { background: #eceff5; color: #5c6674; }
.badge.cancelled { background: #fdecea; color: #b3382c; }
.badge.execution { background: #e8ecfd; color: #3550b8; }
.session-del { color: #c33; background: none; border: none; font-size: 12px; padding: 6px; }
/* ---- 阶段开关条 ---- */
.phase-bar {
display: flex; align-items: center; justify-content: space-between;
padding: 8px 12px; background: #fff; border-bottom: 1px solid #e8e8ee;
}
.status-pill { font-size: 12px; color: #666; }
.phase-switch {
border: none; border-radius: 18px; padding: 8px 18px;
font-size: 14px; font-weight: 600; color: #fff; cursor: pointer;
box-shadow: inset 0 -2px 0 rgba(0,0,0,0.18);
transition: background 0.2s;
}
.phase-switch.planning { background: #2e9d54; }
.phase-switch.planning:active { background: #268547; }
.phase-switch.execution { background: #d2483c; }
.phase-switch.execution:active { background: #b13a2f; }
/* ---- 消息 ---- */
.messages {
flex: 1; overflow-y: auto; padding: 12px 12px 8px;
display: flex; flex-direction: column; gap: 10px;
scroll-behavior: smooth;
}
.msg { display: flex; flex-direction: column; max-width: 86%; }
.msg.me { align-self: flex-end; align-items: flex-end; }
.msg.other { align-self: flex-start; align-items: flex-start; }
.msg-user { font-size: 11px; color: #98a; margin-bottom: 3px; display: flex; gap: 6px; align-items: center; }
.ai-avatar {
width: 18px; height: 18px; border-radius: 50%;
background: linear-gradient(135deg, #2a5299, #4d7fd6);
display: inline-block;
}
.ai-avatar.gray { background: #b9bec9; filter: grayscale(); }
.msg-bubble {
padding: 9px 12px; border-radius: 12px; line-height: 1.55;
word-break: break-word; overflow-wrap: break-word; font-size: 14.5px;
background: #fff; box-shadow: 0 1px 3px rgba(30,40,90,0.07);
}
.msg.me .msg-bubble { background: #d7e7ff; border-bottom-right-radius: 4px; }
.msg.other .msg-bubble { border-bottom-left-radius: 4px; }
.msg-bubble pre {
background: #f0f2f6; padding: 8px 10px; border-radius: 8px;
overflow-x: auto; font-size: 12.5px; margin: 6px 0;
}
.msg-bubble code { background: #f0f2f6; padding: 1px 4px; border-radius: 4px; font-size: 12.5px; }
.msg-bubble pre code { background: none; padding: 0; }
.msg-bubble img { max-width: 100%; border-radius: 8px; }
.msg-bubble table { border-collapse: collapse; margin: 6px 0; display: block; overflow-x: auto; }
.msg-bubble th, .msg-bubble td { border: 1px solid #dde; padding: 4px 8px; font-size: 13px; }
.msg-bubble blockquote { border-left: 3px solid #ccd; padding-left: 8px; color: #667; margin: 4px 0; }
.msg-time { font-size: 10px; color: #aab; margin-top: 3px; }
/* 工具卡片 */
.tool-card {
align-self: stretch; max-width: 100%;
background: #fbf7ee; border: 1px solid #eadfc4; border-radius: 10px;
padding: 8px 12px; font-size: 13px; color: #6b5b2a;
}
.tool-card .tool-name { font-weight: 600; }
.tool-card summary { cursor: pointer; list-style: none; display: flex; gap: 8px; align-items: center; }
.tool-card summary::-webkit-details-marker { display: none; }
.tool-card .tool-args { color: #8a763b; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; font-size: 12px; }
.tool-card pre {
background: #f6f1e3; padding: 8px; border-radius: 8px; margin-top: 6px;
white-space: pre-wrap; overflow-x: auto; max-height: 300px; overflow-y: auto;
font-size: 12px; color: #55492a;
}
.tool-card.error { background: #fdecea; border-color: #f2c4bd; color: #a3352a; }
.tool-card .spin { display: inline-block; animation: rot 1s linear infinite; }
@keyframes rot { to { transform: rotate(360deg); } }
/* ---- 文件面板 ---- */
.files-panel {
position: absolute; left: 0; right: 0; bottom: 0;
max-height: 55%; background: #fff; border-radius: 16px 16px 0;
box-shadow: 0 -4px 20px rgba(20,30,70,0.15); z-index: 9;
display: flex; flex-direction: column;
padding-bottom: env(safe-area-inset-bottom);
}
.files-panel-header {
display: flex; justify-content: space-between; align-items: center;
padding: 12px 16px; font-weight: 600; border-bottom: 1px solid #eee;
}
.files-list { overflow-y: auto; padding: 6px 8px; }
.file-row {
display: flex; align-items: center; gap: 8px; padding: 8px 8px;
border-radius: 8px; font-size: 13.5px;
}
.file-row:active { background: #f4f5f9; }
.file-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-size { color: #99a; font-size: 12px; }
.file-act { color: #2a5299; text-decoration: none; font-size: 13px; padding: 2px 6px; background: none; border: none; cursor: pointer; }
.file-act.del { color: #c33; }
.empty-tip { color: #99a; text-align: center; padding: 18px; font-size: 13px; }
/* ---- 输入区 ---- */
.input-area {
display: flex; align-items: flex-end; gap: 8px;
padding: 8px 10px calc(8px + env(safe-area-inset-bottom));
background: #fff; border-top: 1px solid #e8e8ee;
}
.input-area textarea {
flex: 1; resize: none; border: none; outline: none;
background: #f2f3f7; border-radius: 18px; padding: 9px 14px;
font-size: 15px; line-height: 1.4; max-height: 120px;
font-family: inherit;
}
.file-upload-btn {
width: 38px; height: 38px; border-radius: 50%;
display: inline-flex; align-items: center; justify-content: center;
color: #667; cursor: pointer; flex-shrink: 0;
}
.file-upload-btn:active { background: #eee; }
.file-upload-btn svg { width: 22px; height: 22px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.send-btn {
width: 38px; height: 38px; border-radius: 50%; border: none; cursor: pointer;
background: linear-gradient(135deg, #2a5299, #4d7fd6);
display: inline-flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.send-btn:active { opacity: 0.8; }
.send-btn svg { width: 18px; height: 18px; stroke: #fff; fill: none; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
/* ---- 弹窗 ---- */
.modal-overlay {
position: fixed; inset: 0; background: rgba(20,25,50,0.45);
display: flex; align-items: center; justify-content: center; z-index: 100;
}
.modal {
background: #fff; border-radius: 14px; padding: 20px; width: 84%; max-width: 360px;
position: relative;
}
.modal h3 { margin-bottom: 12px; font-size: 16px; }
.modal input {
width: 1; border: 1px solid #dde; border-radius: 8px;
padding: 10px 12px; font-size: 15px; margin-bottom: 10px; outline: none;
}
.modal input:focus { border-color: #2a5299; }
.modal-close-btn {
position: absolute; right: 10px; top: 10px;
background: none; border: none; cursor: pointer; color: #99a;
width: 28px; height: 28px;
}
.modal-close-btn svg { width: 18px; height: 18px; stroke: currentColor; fill: none; stroke-width: 2; stroke-linecap: round; }
.primary-btn {
width: 1; background: linear-gradient(135deg, #1e3c72, #2a5299);
color: #fff; border: none; border-radius: 10px; padding: 11px;
font-size: 15px; font-weight: 600; cursor: pointer;
}
.primary-btn:active { opacity: 0.9; }
/* ---- Toast ---- */
.toast {
position: fixed; left: 50%; bottom: 90px; transform: translateX(-50%);
background: rgba(20,25,45,0.85); color: #fff;
padding: 9px 16px; border-radius: 20px; font-size: 13.5px; z-index: 200;
max-width: 80%; text-align: center;
}
+102
View File
@@ -0,0 +1,102 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Agent 任务台</title>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<meta name="theme-color" content="#1e3c72">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="stylesheet" href="/css/style.css">
</head>
<body>
<div class="app" id="app">
<!-- 会话列表页 -->
<div id="list-page" class="page">
<div class="header">
<div class="header-left">
<svg width="24" height="24" viewBox="0 0 24 24" stroke="#fff" fill="none" stroke-width="1.5">
<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="9" y1="9" x2="15" y2="9"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>
</svg>
<h2>Agent 任务台</h2>
</div>
<div style="display:flex; gap:2px;">
<button class="icon-btn" id="create-session-btn" onclick="ui.openCreate()" title="新建任务">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</button>
</div>
</div>
<div class="model-strip" id="model-strip"></div>
<div class="session-list" id="session-list"></div>
</div>
<!-- 聊天/任务页 -->
<div id="chat-page" class="page hidden">
<div class="header">
<button class="icon-btn back-btn" onclick="ui.backToList()">
<svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"></polyline></svg>
</button>
<span class="chat-title" id="chat-title"></span>
<div class="header-right">
<button class="icon-btn" onclick="ui.toggleFiles()" title="文件">
<svg viewBox="0 0 24 24"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
</button>
</div>
</div>
<!-- 任务状态开关 -->
<div class="phase-bar" id="phase-bar">
<span class="status-pill" id="status-pill">--</span>
<button class="phase-switch planning" id="phase-switch" onclick="ui.togglePhase()">▶ 开始执行</button>
</div>
<div class="messages" id="messages"></div>
<!-- 文件面板 -->
<div class="files-panel hidden" id="files-panel">
<div class="files-panel-header">
<span>任务文件</span>
<div>
<label class="icon-btn" title="上传文件">
<input type="file" id="file-input" multiple style="display:none;" onchange="ui.uploadFiles(event)">
<svg viewBox="0 0 24 24"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
</label>
<button class="icon-btn" onclick="ui.toggleFiles()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
</div>
</div>
<div class="files-list" id="files-list"></div>
</div>
<div class="input-area">
<label class="file-upload-btn" title="上传文件">
<input type="file" id="msg-file-input" multiple style="display:none;" onchange="ui.uploadFiles(event)">
<svg viewBox="0 0 24 24"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg>
</label>
<textarea id="msg-input" placeholder="输入消息…" rows="1"></textarea>
<button class="send-btn" onclick="ui.send()">
<svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg>
</button>
</div>
</div>
<!-- 新建会话弹窗 -->
<div id="create-modal" class="modal-overlay hidden" onclick="if(event.target===this)ui.closeCreate()">
<div class="modal">
<button class="modal-close-btn" onclick="ui.closeCreate()">
<svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
</button>
<h3>新建任务会话</h3>
<input type="text" id="new-title" placeholder="任务标题(可留空,AI 自动取首条消息)">
<button class="primary-btn" onclick="ui.createSession()">创建</button>
</div>
</div>
</div>
<div class="toast hidden" id="toast"></div>
<script src="/js/app.js"></script>
</body>
</html>
+472
View File
@@ -0,0 +1,472 @@
// Agent 任务台前端:会话列表 / 聊天(SSE 流式)/ 文件管理 / 阶段开关
// 交互风格参考 ai-xiaocai(移动优先、左右滑动切页)。
'use strict';
if (typeof marked !== 'undefined') {
marked.setOptions({ breaks: true, gfm: true });
}
const state = {
sessionId: null,
phase: 'planning',
status: '',
es: null,
streamEl: null,
streamText: '',
toolCards: {},
filePanelOpen: false,
};
// ---------- API ----------
async function req(method, url, body, isForm) {
const opt = { method, headers: {} };
if (body && !isForm) {
opt.headers['Content-Type'] = 'application/json';
opt.body = JSON.stringify(body);
} else if (body && isForm) {
opt.body = body;
}
const res = await fetch(url, opt);
if (!res.ok) {
let msg = 'HTTP ' + res.status;
try { msg = (await res.json()).error || msg; } catch (_) {}
throw new Error(msg);
}
return res.json();
}
// ---------- 工具函数 ----------
function $(id) { return document.getElementById(id); }
function esc(s) { const d = document.createElement('div'); d.textContent = s == null ? '' : String(s); return d.innerHTML; }
function fmtSize(n) {
if (n == null) return '';
if (n < 1024) return n + ' B';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
return (n / 1024 / 1024).toFixed(1) + ' MB';
}
function fmtTime(ts) {
if (!ts) return '';
const d = new Date(ts);
const p = n => String(n).padStart(2, '0');
const today = new Date().toDateString() === d.toDateString();
return (today ? '' : (d.getMonth() + 1) + '/' + d.getDate() + ' ') + p(d.getHours()) + ':' + p(d.getMinutes());
}
function toast(msg) {
const el = $('toast');
el.textContent = msg;
el.classList.remove('hidden');
clearTimeout(toast._t);
toast._t = setTimeout(() => el.classList.add('hidden'), 2500);
}
function toolArgsSummary(name, argsStr) {
let s = '';
try {
const o = JSON.parse(argsStr || '{}');
const key = ['path', 'command', 'regex', 'glob', 'url', 'query', 'source_path', 'destination_path'];
for (const k of key) if (o[k]) { s = String(o[k]); break; }
if (!s) s = argsStr || '';
} catch (_) { s = argsStr || ''; }
if (s.length > 80) s = s.slice(0, 80) + '…';
return s;
}
// ---------- 页面切换 ----------
function showChat() {
$('list-page').classList.add('off-left');
$('chat-page').classList.remove('hidden');
$('chat-page').classList.add('off-right');
requestAnimationFrame(() => {
requestAnimationFrame(() => $('chat-page').classList.remove('off-right'));
});
}
function showList() {
$('chat-page').classList.add('off-right');
setTimeout(() => {
$('chat-page').classList.add('hidden');
$('list-page').classList.remove('off-left');
}, 50);
}
// 滑动切换:聊天页右滑返回列表
(function bindSwipe() {
let x0 = null, y0 = null;
$('chat-page').addEventListener('touchstart', e => {
if (e.touches.length !== 1) return;
x0 = e.touches[0].clientX; y0 = e.touches[0].clientY;
}, { passive: true });
$('chat-page').addEventListener('touchend', e => {
if (x0 == null) return;
const t = e.changedTouches[0];
const dx = t.clientX - x0, dy = t.clientY - y0;
x0 = null;
if (dx > 70 && Math.abs(dy) < 60) ui.backToList();
}, { passive: true });
})();
// ---------- 会话列表 ----------
async function loadSessions() {
try {
const rows = await req('GET', '/api/sessions');
const el = $('session-list');
if (!rows.length) {
el.innerHTML = '<div class="empty-tip">还没有任务,点右上角 + 新建</div>';
return;
}
el.innerHTML = rows.map(s => {
const st = { queued: '排队中', active: '活跃中', completed: '已完成', cancelled: '已终止' }[s.status] || s.status;
const badge = '<span class="badge ' + s.status + '">' + st + (s.status === 'queued' && s.queue_pos ? ' #' + s.queue_pos : '') + '</span>';
const phase = s.phase === 'execution' ? '<span class="badge execution">执行中阶段</span>' : '';
return '<div class="session-card" onclick="ui.openSession(\'' + s.id + '\')">' +
'<div class="session-main">' +
'<div class="session-name">' + esc(s.title || s.id) + '</div>' +
'<div class="session-meta"><span>' + esc(s.id) + '</span>' + badge + phase +
(s.model_id ? '<span>' + esc(s.model_id) + '</span>' : '') + '</div>' +
'</div>' +
'<button class="session-del" onclick="event.stopPropagation();ui.deleteSession(\'' + s.id + '\')">删除</button>' +
'</div>';
}).join('');
} catch (e) { toast('加载会话失败:' + e.message); }
}
async function loadModels() {
try {
const rows = await req('GET', '/api/models');
$('model-strip').innerHTML = rows.map(m =>
'<span class="model-chip ' + (m.is_busy ? 'busy' : '') + '">' +
esc(m.display_name || m.id) + (m.is_busy ? ' 忙' : ' 空闲') + '</span>').join('');
} catch (_) {}
}
// ---------- 消息渲染 ----------
function md(text) {
if (typeof marked === 'undefined') return esc(text);
try { return marked.parse(text || ''); } catch (_) { return esc(text); }
}
function renderToolCard(id, name, argsStr) {
const div = document.createElement('div');
div.className = 'tool-card';
div.id = 'tool-' + id;
div.innerHTML =
'<details><summary><span class="spin">◌</span>' +
'<span class="tool-name">' + esc(name) + '</span>' +
'<span class="tool-args">' + esc(toolArgsSummary(name, argsStr)) + '</span></summary>' +
'<pre>执行中…</pre></details>';
return div;
}
function fillToolResult(id, content, isError) {
const card = document.getElementById('tool-' + id);
if (!card) return;
if (isError) card.classList.add('error');
card.querySelector('.spin').textContent = isError ? '✕' : '✓';
card.querySelector('pre').textContent = content || '(空)';
}
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);
}
return null;
}
const wrap = document.createElement('div');
if (m.role === 'user') {
wrap.className = 'msg me';
wrap.innerHTML = '<div class="msg-user">我</div>' +
'<div class="msg-bubble">' + esc(m.content) + '</div>' +
'<div class="msg-time">' + fmtTime(m.created_at) + '</div>';
return wrap;
}
if (m.role === 'assistant') {
wrap.className = 'msg other';
const gray = state.status === 'queued' ? ' gray' : '';
let inner = '<div class="msg-user"><span class="ai-avatar' + gray + '"></span>AI' +
(m.model_tag ? ' · ' + esc(m.model_tag) : '') + '</div>';
if (m.content) inner += '<div class="msg-bubble">' + md(m.content) + '</div>';
inner += '<div class="msg-time">' + fmtTime(m.created_at) + '</div>';
wrap.innerHTML = inner;
return wrap;
}
return null;
}
function appendToolCardsFromAssistant(m, container) {
if (!m.tool_calls) return;
let calls;
try { calls = typeof m.tool_calls === 'string' ? JSON.parse(m.tool_calls) : m.tool_calls; } catch (_) { return; }
for (const c of calls) {
const id = c.id || ('c' + Math.random().toString(36).slice(2, 10));
const card = renderToolCard(id, c.function.name, c.function.arguments);
container.appendChild(card);
state.toolCards[id] = card;
}
}
async function renderDetail(detail) {
const box = $('messages');
box.innerHTML = '';
state.streamEl = null;
state.streamText = '';
state.toolCards = {};
const s = detail.session;
state.phase = s.phase;
state.status = s.status;
updatePhaseUI();
$('chat-title').textContent = s.title || s.id;
for (const m of detail.messages) {
const node = msgNode(m, state.toolCards);
if (node) box.appendChild(node);
if (m.role === 'assistant') appendToolCardsFromAssistant(m, box);
}
if (!detail.messages.length) {
box.innerHTML = '<div class="empty-tip">描述你的需求,AI 会先和你讨论(规划阶段)。</div>';
}
scrollBottom();
loadFiles();
}
function scrollBottom() {
const box = $('messages');
box.scrollTop = box.scrollHeight;
}
// ---------- SSE ----------
function connectStream() {
if (state.es) { state.es.close(); state.es = null; }
const es = new EventSource('/api/sessions/' + state.sessionId + '/stream');
state.es = es;
es.addEventListener('status', ev => {
const d = JSON.parse(ev.data);
state.status = d.status;
state.phase = d.phase;
updatePhaseUI(d);
});
es.addEventListener('phase', ev => {
state.phase = JSON.parse(ev.data).phase;
updatePhaseUI();
});
es.addEventListener('assistant_delta', ev => {
const d = JSON.parse(ev.data);
if (!state.streamEl) {
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="msg-user"><span class="ai-avatar"></span>AI</div>' +
'<div class="msg-bubble"></div>';
state.streamEl = wrap.querySelector('.msg-bubble');
state.streamText = '';
$('messages').appendChild(wrap);
}
state.streamText += d.text;
state.streamEl.textContent = state.streamText;
scrollBottom();
});
es.addEventListener('assistant_message', ev => {
const d = JSON.parse(ev.data);
if (state.streamEl) {
const bubble = state.streamEl;
bubble.innerHTML = md(d.content || '');
state.streamEl = null;
state.streamText = '';
} else if (d.content) {
const box = $('messages');
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="msg-user"><span class="ai-avatar"></span>AI</div>' +
'<div class="msg-bubble">' + md(d.content) + '</div>';
box.appendChild(wrap);
}
if (d.tool_calls) {
appendToolCardsFromAssistant({ tool_calls: d.tool_calls }, $('messages'));
scrollBottom();
}
});
es.addEventListener('tool_call', ev => {
const d = JSON.parse(ev.data);
const card = renderToolCard(d.id, d.name, d.arguments);
$('messages').appendChild(card);
state.toolCards[d.id] = card;
scrollBottom();
});
es.addEventListener('tool_result', ev => {
const d = JSON.parse(ev.data);
fillToolResult(d.tool_call_id, d.content, d.is_error);
scrollBottom();
});
es.addEventListener('done', ev => {
loadSessions();
loadModels();
});
es.addEventListener('error', ev => {
try {
const d = JSON.parse(ev.data);
if (d && d.message) toast('错误:' + d.message);
} catch (_) { /* EventSource 连接错误,自动重连 */ }
});
}
// ---------- 阶段开关 ----------
function updatePhaseUI(d) {
const btn = $('phase-switch');
const pill = $('status-pill');
const stMap = { queued: '排队中', active: '活跃中', completed: '已完成', cancelled: '已终止' };
let text = stMap[state.status] || state.status || '--';
if (d && d.queue_pos) text += '(第 ' + d.queue_pos + ' 位)';
if (state.status === 'active') {
const run = d && d.running;
text = '活跃中 · ' + (state.phase === 'execution' ? '执行' : '规划') + (d && d.model_id ? ' · ' + d.model_id : '');
}
pill.textContent = text;
if (state.phase === 'execution') {
btn.textContent = '■ 终止';
btn.className = 'phase-switch execution';
} else {
btn.textContent = '▶ 开始执行';
btn.className = 'phase-switch planning';
}
}
// ---------- 文件 ----------
async function loadFiles() {
if (!state.sessionId) return;
try {
const files = await req('GET', '/api/sessions/' + state.sessionId + '/files');
const el = $('files-list');
if (!files.length) {
el.innerHTML = '<div class="empty-tip">还没有文件。上传文件或在执行阶段让 AI 生成。</div>';
return;
}
el.innerHTML = files.map(f => {
const url = '/api/sessions/' + state.sessionId + '/files/download?path=' + encodeURIComponent(f.filename);
return '<div class="file-row"><span class="file-name">' + esc(f.filename) + '</span>' +
'<span class="file-size">' + fmtSize(f.size) + '</span>' +
'<a class="file-act" href="' + url + '">下载</a>' +
'<button class="file-act del" onclick="ui.deleteFile(\'' + esc(f.filename).replace(/'/g, '%27') + '\')">删</button></div>';
}).join('');
} catch (e) { toast('读取文件失败:' + e.message); }
}
// ---------- 主逻辑 ----------
const ui = {
openCreate() { $('create-modal').classList.remove('hidden'); $('new-title').focus(); },
closeCreate() { $('create-modal').classList.add('hidden'); },
async createSession() {
try {
const title = $('new-title').value.trim();
const s = await req('POST', '/api/sessions', { title });
this.closeCreate();
$('new-title').value = '';
await loadSessions();
this.openSession(s.id);
} catch (e) { toast('创建失败:' + e.message); }
},
async deleteSession(id) {
if (!confirm('删除会话?')) return;
const delDir = confirm('同时删除任务目录(文件将不可恢复)?\n取消 = 仅删除会话记录');
try {
await req('DELETE', '/api/sessions/' + id + '?delete_dir=' + (delDir ? 'true' : 'false'));
if (state.sessionId === id) this.backToList();
loadSessions();
} catch (e) { toast('删除失败:' + e.message); }
},
async openSession(id) {
state.sessionId = id;
showChat();
try {
const detail = await req('GET', '/api/sessions/' + id);
await renderDetail(detail);
connectStream();
} catch (e) { toast('打开会话失败:' + e.message); }
},
backToList() {
if (state.es) { state.es.close(); state.es = null; }
state.sessionId = null;
showList();
loadSessions();
loadModels();
},
async send() {
const ta = $('msg-input');
const content = ta.value.trim();
if (!content || !state.sessionId) return;
ta.value = '';
ta.style.height = 'auto';
const box = $('messages');
const tip = box.querySelector('.empty-tip');
if (tip) tip.remove();
try {
const r = await req('POST', '/api/sessions/' + state.sessionId + '/messages', { content });
const wrap = document.createElement('div');
wrap.className = 'msg me';
wrap.innerHTML = '<div class="msg-user">我' + (r.delivered === 'queued' ? '(排队中,暂存)' : '') + '</div>' +
'<div class="msg-bubble">' + esc(content) + '</div>';
box.appendChild(wrap);
scrollBottom();
} catch (e) { toast('发送失败:' + e.message); }
},
async togglePhase() {
if (!state.sessionId) return;
try {
if (state.phase === 'planning') {
await req('POST', '/api/sessions/' + state.sessionId + '/start');
state.phase = 'execution';
updatePhaseUI();
const box = $('messages');
const wrap = document.createElement('div');
wrap.className = 'msg me';
wrap.innerHTML = '<div class="msg-user">我(开始执行)</div>' +
'<div class="msg-bubble">我说完了,你可以开始干活了。先把我上面说的需求整理成 task.md 文件写入任务目录,然后按照 task.md 开始执行。</div>';
box.appendChild(wrap);
scrollBottom();
} else {
await req('POST', '/api/sessions/' + state.sessionId + '/stop');
toast('已发送终止指令');
}
} catch (e) { toast('操作失败:' + e.message); }
},
toggleFiles() {
state.filePanelOpen = !state.filePanelOpen;
$('files-panel').classList.toggle('hidden', !state.filePanelOpen);
if (state.filePanelOpen) loadFiles();
},
async uploadFiles(ev) {
const input = ev.target;
const files = input.files;
if (!files || !files.length || !state.sessionId) return;
const fd = new FormData();
for (const f of files) fd.append('files', f);
input.value = '';
try {
const r = await req('POST', '/api/sessions/' + state.sessionId + '/files', fd, true);
toast('已上传 ' + r.uploaded.length + ' 个文件');
loadFiles();
} catch (e) { toast('上传失败:' + e.message); }
},
async deleteFile(name) {
if (!confirm('删除文件 ' + name + '?')) return;
try {
await req('DELETE', '/api/sessions/' + state.sessionId + '/files?path=' + encodeURIComponent(name));
loadFiles();
} catch (e) { toast('删除失败:' + e.message); }
},
};
// ---------- 输入框行为 ----------
document.addEventListener('input', e => {
if (e.target.id === 'msg-input') {
e.target.style.height = 'auto';
e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px';
}
});
document.addEventListener('keydown', e => {
if (e.target.id === 'msg-input' && e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
ui.send();
}
});
// ---------- 启动 ----------
showList();
loadSessions();
loadModels();
setInterval(loadSessions, 8000);