feat: AI 控制台历史会话(DeepSeek 式)——①agent_conversation 表:会话持久化(单表 JSON 消息),一轮 run 完成后 user/assistant 自动落库、新会话以首条消息作标题;②会话 API:列表/新建/详情/删除/重命名;③run 绑定 conversation_id:history 从会话加载(多轮上下文延续)、完成写回;④前端三栏布局:左侧会话栏(新建/列表/高亮/悬停删除/轮数时间)+ 聊天 + 实时画面,切换会话即切换上下文,刷新后自动恢复当前会话与消息

This commit is contained in:
2026-09-06 15:12:56 +08:00
parent 9b8ecd63f7
commit a77635c925
3 changed files with 345 additions and 70 deletions
+129 -47
View File
@@ -19,7 +19,9 @@ function initAgentChat(){
loadLiveDevices();
loadAgentTargetDevices();
startRunPoll();
restoreAgentView();
renderConvList(); // 会话列表(决定当前会话)
loadCurrentConvMessages(); // 渲染当前会话历史
restoreRunningFlow(); // 若任务运行中:重订阅事件流
// 输入框快捷键
const inp = document.getElementById('agent-input');
inp.addEventListener('keydown', ev=>{
@@ -30,39 +32,22 @@ function initAgentChat(){
});
}
// ================== 页面刷新/重进恢复 ==================
// 刷新后聊天区是空的,但后端任务可能还在跑、历史还在——从这里恢复:
// 1) 渲染会话历史(user/assistant 文本轮)
// 2) 任务运行中 → 重新订阅事件流(服务端队列保留积压,重连后补发)
function restoreAgentView(){
const chat = document.getElementById('agent-chat');
if(!chat) return;
const hasContent = chat.children.length > 0 && !chat.querySelector('.agent-empty');
if(hasContent) return; // 页面未刷新(切 Tab 回来 DOM 还在),无需恢复
// ================== 页面刷新/重进恢复(运行中任务续流) ==================
// 历史轮次由 loadCurrentConvMessages 从会话渲染;这里只处理「任务仍在后台跑」:
// 重新订阅事件流(服务端队列保留积压,重连后补发 delta/step/done)。
function restoreRunningFlow(){
apiGet('/api/agent/run').then(r=>{
if(!r||!r.ok) return;
const hist = r.history || [];
hist.forEach(h=>{
const txt = (h.content || '').trim();
if(!txt) return;
if(h.role === 'user'){ addUserMsg(txt); }
else{
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = txt;
}
});
if(r.state === 'running' && r.run_id){
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '↻ 已恢复连接,任务仍在后台运行(此前的内容可在上方查看)…';
setRunning(true);
listenStream(r.run_id);
}else if(r.state === 'error' && r.error){
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + r.error;
}else if(!hist.length && r.state === 'idle'){
clearEmpty();
document.getElementById('agent-chat').innerHTML =
'<div class="agent-empty">👋 给 AI 下达指令…(先选 🎯 目标设备)</div>';
}else if(r.state === 'error' && r.error && _currentConvId){
// 错误提示仅当本会话相关时展示
const chat = document.getElementById('agent-chat');
if(chat && !chat.children.length){
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + r.error;
}
}
});
}
@@ -200,18 +185,95 @@ function bindChatScroll(){
});
}
function clearAgentChat(){
document.getElementById('agent-chat').innerHTML =
'<div class="agent-empty">对话已清空。给 AI 下达新指令…</div>';
document.getElementById('agent-chat').innerHTML = '';
}
// 新建会话:清后端历史 + 清前端对话区(像 DeepSeek 的新建会话)
function newAgentSession(){
// ================== 历史会话(DeepSeek 式:左侧列表,多会话持久化) ==================
let _currentConvId = localStorage.getItem('agent_conv_id') || '';
function saveConvId(id){
_currentConvId = id || '';
if(id) localStorage.setItem('agent_conv_id', id);
else localStorage.removeItem('agent_conv_id');
}
function createAgentSession(){
if(_agentBusy){showToast('运行中不能新建会话','error');return;}
if(!confirm('新建会话将清空当前对话历史,确定?'))return;
apiPost('/api/agent/clear',{}).then(r=>{
apiPost('/api/agent/conversations',{}).then(r=>{
if(r&&r.ok){
saveConvId(r.id);
clearAgentChat();
showToast('已新建会话','success');
}else showToast('操作失败','error');
renderConvList();
}else showToast('新建失败: '+((r&&r.error)||''),'error');
});
}
function selectAgentSession(id){
if(_agentBusy){showToast('运行中不能切换会话','error');return;}
if(id === _currentConvId) return;
saveConvId(id);
clearAgentChat();
loadCurrentConvMessages();
renderConvList();
}
function deleteAgentSession(id){
if(!confirm('删除该会话?历史消息将不可恢复。')) return;
apiDelete('/api/agent/conversations/'+id).then(r=>{
if(r&&r.ok){
if(_currentConvId === id) saveConvId('');
showToast('会话已删除','success');
renderConvList();
loadCurrentConvMessages();
}else showToast('删除失败: '+((r&&r.error)||''),'error');
});
}
function renderConvList(){
apiGet('/api/agent/conversations').then(r=>{
if(!r||!r.ok)return;
const list = document.getElementById('agent-sess-list');
if(!list)return;
const convs = r.conversations || [];
let cur = _currentConvId;
if(!convs.some(c=>c.id===cur)) cur = convs.length ? convs[0].id : '';
if(cur !== _currentConvId){ saveConvId(cur); clearAgentChat(); loadCurrentConvMessages(); }
if(!convs.length){
list.innerHTML = '<div class="agent-empty" style="padding:20px 10px;font-size:12px">'
+ '暂无历史会话<br><br>点「+ 新建会话」开始</div>';
return;
}
list.innerHTML = convs.map(c=>{
const t = c.title || '新会话';
return '<div class="agent-sess-item'+(c.id===cur?' active':'')
+'" onclick="selectAgentSession(\''+c.id+'\')">'
+'<button class="agent-sess-del" title="删除会话" '
+'onclick="event.stopPropagation();deleteAgentSession(\''+c.id+'\')">✕</button>'
+'<div class="t">'+esc(t)+'</div>'
+'<div class="m">'+esc(c.updated_at||'')+(c.count ? ' · '+c.count+' 轮' : '')+'</div></div>';
}).join('');
});
}
function loadCurrentConvMessages(){
const chat = document.getElementById('agent-chat');
if(!chat) return;
if(!_currentConvId){
chat.innerHTML = '<div class="agent-empty">👋 点左侧「+ 新建会话」开始,'
+ '给 AI 下达指令(先选 🎯 目标设备)。</div>';
return;
}
apiGet('/api/agent/conversations/'+_currentConvId).then(r=>{
if(!r||!r.ok)return;
chat.innerHTML = '';
(r.messages||[]).forEach(m=>{
const txt = (m.content||'').trim();
if(!txt) return;
if(m.role==='user'){ addUserMsg(txt); }
else{
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = txt;
}
});
if(!chat.children.length){
chat.innerHTML = '<div class="agent-empty">新会话。给 AI 下达指令'
+ '(先选 🎯 目标设备)…</div>';
}
});
}
@@ -244,17 +306,36 @@ function sendAgentMsg(){
inp.value = '';
addUserMsg(text);
apiPost('/api/agent/run', {prompt: text, serial: serial}).then(r=>{
if(!r||!r.ok){
const msg = r ? (r.error||'启动失败') : '请求失败';
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + msg;
showToast(msg,'error');
return;
}
setRunning(true);
listenStream(r.run_id);
});
// 会话:无当前会话时自动新建(DeepSeek 式:消息总归属于一个会话)
const doRun = (convId)=>{
apiPost('/api/agent/run', {prompt: text, serial: serial,
conversation_id: convId}).then(r=>{
if(!r||!r.ok){
const msg = r ? (r.error||'启动失败') : '请求失败';
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ ' + msg;
showToast(msg,'error');
return;
}
setRunning(true);
listenStream(r.run_id);
});
};
if(_currentConvId){
doRun(_currentConvId);
}else{
apiPost('/api/agent/conversations',{}).then(r=>{
if(r&&r.ok){
saveConvId(r.id);
renderConvList();
doRun(r.id);
}else{
const div = newAssistantMsg();
div.querySelector('.agent-text').textContent = '⚠ 新建会话失败';
showToast('新建会话失败','error');
}
});
}
}
function listenStream(runId){
@@ -309,6 +390,7 @@ function listenStream(runId){
msgEl.querySelector('.agent-text').textContent = d.answer;
}
endRun();
renderConvList(); // 落库已完成:刷新标题/时间/轮数
});
es.addEventListener('error', ev=>{