2.0阶段1: h5重构为底部导航四Tab(任务/技能/模型/设置),app.js拆分为core/tasks/skills/models/settings,聊天详情改为全屏覆盖页

This commit is contained in:
2026-09-01 16:34:16 +08:00
parent 86ec831b74
commit 4968241951
7 changed files with 355 additions and 132 deletions
+48
View File
@@ -300,3 +300,51 @@ body {
padding: 9px 16px; border-radius: 20px; font-size: 13.5px; z-index: 200;
max-width: 80%; text-align: center;
}
/* ================= 2.0:底部导航 + Tab 页 ================= */
.tabbar {
position: absolute; left: 0; right: 0; bottom: 0; z-index: 50;
display: flex; background: #fff; border-top: 1px solid #e8e8ee;
height: calc(56px + env(safe-area-inset-bottom));
padding-bottom: env(safe-area-inset-bottom);
}
.tab-item {
flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center;
gap: 2px; padding-top: 6px;
color: #8a93a6; text-decoration: none; font-size: 11px;
-webkit-tap-highlight-color: transparent; user-select: none;
}
.tab-item svg { width: 22px; height: 22px; stroke: currentColor; fill: none; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.tab-item.active { color: #2a5299; font-weight: 600; }
.tab-item:active { opacity: 0.7; }
/* Tab 内容页:占满除底部导航外的区域(导航隐藏时被聊天页盖住,无影响) */
.tab-page {
position: absolute; top: 0; left: 0; right: 0;
bottom: calc(56px + env(safe-area-inset-bottom));
display: flex; flex-direction: column; background: #f2f3f7;
}
.tab-body-area { flex: 1; overflow-y: auto; padding: 10px 12px 16px; }
/* 聊天详情为全屏覆盖页,需盖住底部导航 */
#chat-page { z-index: 60; }
/* ---- 模型占位卡片(阶段 4 会扩展为用量/费用卡) ---- */
.model-card {
background: #fff; border-radius: 12px; padding: 12px 14px; margin-bottom: 10px;
box-shadow: 0 1px 4px rgba(30,40,90,0.06);
}
.model-card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.model-card-name { font-weight: 600; font-size: 15px; }
.model-card-state { font-size: 11px; padding: 2px 8px; border-radius: 9px; }
.model-card-state.idle { background: #e3f2e6; color: #217a34; }
.model-card-state.busy { background: #fdecea; color: #b3382c; }
.model-card-meta { font-size: 12px; color: #888; margin-top: 4px; }
/* ---- 设置页行 ---- */
.settings-row {
display: flex; align-items: center; justify-content: space-between; gap: 10px;
background: #fff; border-radius: 12px; padding: 12px 14px; margin-bottom: 10px;
box-shadow: 0 1px 4px rgba(30,40,90,0.06); font-size: 14px;
}
.ghost-btn.small { flex: none; padding: 6px 12px; font-size: 13px; border-radius: 8px; }
+64 -5
View File
@@ -12,8 +12,9 @@
</head>
<body>
<div class="app" id="app">
<!-- 会话列表页 -->
<div id="list-page" class="page">
<!-- ================= Tab:任务(会话列表) ================= -->
<div id="tab-tasks" class="tab-page hidden">
<div class="header">
<div class="header-left"><div class="brand" onclick="ui.logout()">
<svg width="24" height="24" viewBox="0 0 24 24" stroke="#fff" fill="none" stroke-width="1.5">
@@ -31,7 +32,61 @@
<div class="session-list" id="session-list"></div>
</div>
<!-- 聊天/任务页 -->
<!-- ================= Tab:技能 ================= -->
<div id="tab-skills" class="tab-page hidden">
<div class="header">
<div class="header-left"><h2>技能管理</h2></div>
</div>
<div class="tab-body-area">
<div class="empty-tip">技能管理开发中(阶段 3):技能的创建 / 编辑 / 删除与技能文件管理。</div>
</div>
</div>
<!-- ================= Tab:模型 ================= -->
<div id="tab-models" class="tab-page hidden">
<div class="header">
<div class="header-left"><h2>模型池</h2></div>
</div>
<div class="tab-body-area" id="model-cards">
<div class="empty-tip">加载中…</div>
</div>
</div>
<!-- ================= Tab:设置 ================= -->
<div id="tab-settings" class="tab-page hidden">
<div class="header">
<div class="header-left"><h2>设置</h2></div>
</div>
<div class="tab-body-area">
<div class="settings-row">
<span>当前用户:<b id="whoami" class="hidden">-</b></span>
<button class="ghost-btn small hidden" id="logout-btn" onclick="ui.logout()">退出登录</button>
</div>
<div class="empty-tip">设置中心开发中(阶段 5):config.yml 配置管理与服务重启。</div>
</div>
</div>
<!-- ================= 底部导航 ================= -->
<nav class="tabbar" id="tabbar">
<a class="tab-item" href="#/tasks" data-tab="tasks">
<svg viewBox="0 0 24 24"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>
<span>任务</span>
</a>
<a class="tab-item" href="#/skills" data-tab="skills">
<svg viewBox="0 0 24 24"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>
<span>技能</span>
</a>
<a class="tab-item" href="#/models" data-tab="models">
<svg viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><line x1="9" y1="1" x2="9" y2="4"></line><line x1="15" y1="1" x2="15" y2="4"></line><line x1="9" y1="20" x2="9" y2="23"></line><line x1="15" y1="20" x2="15" y2="23"></line><line x1="20" y1="9" x2="23" y2="9"></line><line x1="20" y1="14" x2="23" y2="14"></line><line x1="1" y1="9" x2="4" y2="9"></line><line x1="1" y1="14" x2="4" y2="14"></line></svg>
<span>模型</span>
</a>
<a class="tab-item" href="#/settings" data-tab="settings">
<svg viewBox="0 0 24 24"><line x1="4" y1="21" x2="4" y2="14"></line><line x1="4" y1="10" x2="4" y2="3"></line><line x1="12" y1="21" x2="12" y2="12"></line><line x1="12" y1="8" x2="12" y2="3"></line><line x1="20" y1="21" x2="20" y2="16"></line><line x1="20" y1="12" x2="20" y2="3"></line><line x1="1" y1="14" x2="7" y2="14"></line><line x1="9" y1="8" x2="15" y2="8"></line><line x1="17" y1="16" x2="23" y2="16"></line></svg>
<span>设置</span>
</a>
</nav>
<!-- ================= 聊天/任务详情(全屏覆盖,盖住底部导航) ================= -->
<div id="chat-page" class="page hidden">
<div class="header">
<button class="icon-btn back-btn" onclick="ui.backToList()">
@@ -113,7 +168,11 @@
<div class="toast hidden" id="toast"></div>
<!-- 发版时更新 v 参数,避免移动端浏览器缓存旧 JS -->
<script src="/js/app.js?v=20260901b"></script>
<!-- 发版时更新 v 参数,避免移动端浏览器缓存旧 JS -->
<script src="/js/core.js?v=20260901c"></script>
<script src="/js/tasks.js?v=20260901c"></script>
<script src="/js/skills.js?v=20260901c"></script>
<script src="/js/models.js?v=20260901c"></script>
<script src="/js/settings.js?v=20260901c"></script>
</body>
</html>
+112
View File
@@ -0,0 +1,112 @@
// Agent 任务台前端核心(2.0):共享工具函数 + 底部导航路由。
// 页面拆分:core.js(本文件)/ tasks.js / skills.js / models.js / settings.js。
// 约定:各业务文件把自身注册进 window.tabModules[tabName] = { onShow() {...} },
// 路由在对应 Tab 每次显示时调用其 onShow()。
'use strict';
if (typeof marked !== 'undefined') {
marked.setOptions({ breaks: true, gfm: true });
}
// 全局共享状态(目前主要被 tasks.js 使用;core 仅用 sessionId 处理 Tab 切换时的聊天收尾)
const state = {
sessionId: null,
status: '',
es: null,
streamEl: null,
streamText: '',
toolCards: {},
filePanelOpen: false,
pendingDeleteId: null,
pendingEl: null,
pendingTimer: null,
pendingStart: 0,
};
window.tabModules = window.tabModules || {};
// ---------- 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.status === 401) { location.href = '/login'; throw new Error('未登录'); }
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);
}
// ---------- 底部导航路由(hash) ----------
const TABS = ['tasks', 'skills', 'models', 'settings'];
function currentTabFromHash() {
const m = /^#\/(\w+)/.exec(location.hash || '');
const t = m && m[1];
return TABS.indexOf(t) >= 0 ? t : 'tasks';
}
function showTab(name) {
for (const t of TABS) {
const el = $('tab-' + t);
if (el) el.classList.toggle('hidden', t !== name);
}
for (const a of document.querySelectorAll('.tab-item')) {
a.classList.toggle('active', a.dataset.tab === name);
}
const mod = window.tabModules[name];
if (mod && typeof mod.onShow === 'function') {
try { mod.onShow(); } catch (e) { console.error('[tab ' + name + '] onShow 失败', e); }
}
}
function initRouter() {
for (const a of document.querySelectorAll('.tab-item')) {
a.addEventListener('click', () => {
// 点当前已激活的 Tab 不会触发 hashchange:若正停在聊天详情,直接返回列表
if (a.dataset.tab === currentTabFromHash() && state.sessionId && window.ui) ui.backToList();
});
}
window.addEventListener('hashchange', () => {
// 跨 Tab 导航(含浏览器返回键)时,先收尾打开中的聊天详情
if (state.sessionId && window.ui) ui.backToList();
showTab(currentTabFromHash());
});
}
function boot() {
initRouter();
showTab(currentTabFromHash());
}
document.addEventListener('DOMContentLoaded', boot);
+35
View File
@@ -0,0 +1,35 @@
// 模型 Tab:模型池卡片。
// 阶段 1 先用现有 /api/models 渲染状态占位卡片,验证 Tab 数据链路;
// 阶段 4 补充 token 用量、费用统计与按天曲线。
'use strict';
window.tabModules = window.tabModules || {};
async function loadModelCards() {
const el = $('model-cards');
if (!el) return;
try {
const rows = await req('GET', '/api/models');
if (!rows.length) {
el.innerHTML = '<div class="empty-tip">未配置模型</div>';
return;
}
el.innerHTML = rows.map(m =>
'<div class="model-card">' +
'<div class="model-card-head">' +
'<span class="model-card-name">' + esc(m.display_name || m.id) + '</span>' +
'<span class="model-card-state ' + (m.is_busy ? 'busy' : 'idle') + '">' + (m.is_busy ? '占用中' : '空闲') + '</span>' +
'</div>' +
'<div class="model-card-meta">' + esc(m.id) +
(m.is_busy && m.current_session_id ? ' · 会话 ' + esc(m.current_session_id) : '') +
'</div>' +
'</div>').join('') +
'<div class="empty-tip">token 用量与费用统计在阶段 4 上线。</div>';
} catch (e) {
el.innerHTML = '<div class="empty-tip">加载失败:' + esc(e.message) + '</div>';
}
}
tabModules.models = {
onShow() { loadModelCards(); },
};
+25
View File
@@ -0,0 +1,25 @@
// 设置 Tab:用户信息 + config.yml 管理。
// 阶段 1 先注册模块占位并显示登录用户;阶段 5 实现配置编辑与重启。
'use strict';
window.tabModules = window.tabModules || {};
// 显示当前登录用户(沿用 1.0 逻辑;未启用认证时静默跳过)
async function refreshUser() {
try {
const me = await req('GET', '/api/me');
const who = $('whoami');
if (who && me && me.user) {
who.textContent = me.user;
who.classList.remove('hidden');
}
const out = $('logout-btn');
if (out) out.classList.toggle('hidden', !(me && me.user));
} catch (_) { /* 未启用认证 */ }
}
tabModules.settings = {
onShow() {
refreshUser();
},
};
+11
View File
@@ -0,0 +1,11 @@
// 技能 Tab:SKILL 管理(增删改 + 文件管理)。
// 阶段 1 先注册模块占位;阶段 3 实现完整功能。
'use strict';
window.tabModules = window.tabModules || {};
tabModules.skills = {
onShow() {
// TODO 阶段 3:loadSkillList()
},
};
@@ -1,67 +1,8 @@
// Agent 任务台前端:会话列表 / 聊天(SSE 流式)/ 文件管理 / 阶段开关
// 交互风格参考 ai-xiaocai(移动优先、左右滑动切页)。
// 任务 Tab:会话列表 / 聊天(SSE 流式)/ 文件管理 / 阶段开关。
// 交互沿用 1.0:移动优先,聊天详情为全屏覆盖页(盖住底部导航),右滑返回列表。
'use strict';
if (typeof marked !== 'undefined') {
marked.setOptions({ breaks: true, gfm: true });
}
const state = {
sessionId: null,
status: '',
es: null,
streamEl: null,
streamText: '',
toolCards: {},
filePanelOpen: false,
pendingDeleteId: null,
pendingEl: null,
pendingTimer: null,
pendingStart: 0,
};
// ---------- 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.status === 401) { location.href = '/login'; throw new Error('未登录'); }
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 {
@@ -78,31 +19,33 @@ function toolArgsFull(argsStr) {
catch (_) { return argsStr || ''; }
}
// ---------- 页面切换 ----------
// ---------- 聊天详情覆盖页进出(底部导航随之隐藏/恢复) ----------
function showChat() {
$('list-page').classList.add('off-left');
$('chat-page').classList.remove('hidden');
$('chat-page').classList.add('off-right');
$('tabbar').classList.add('hidden');
const cp = $('chat-page');
cp.classList.remove('hidden');
cp.classList.add('off-right');
requestAnimationFrame(() => {
requestAnimationFrame(() => $('chat-page').classList.remove('off-right'));
requestAnimationFrame(() => cp.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);
const cp = $('chat-page');
cp.classList.add('off-right');
setTimeout(() => cp.classList.add('hidden'), 50);
$('tabbar').classList.remove('hidden');
}
// 滑动切换:聊天页右滑返回列表
// 滑动切换:聊天页右滑返回列表
(function bindSwipe() {
let x0 = null, y0 = null;
$('chat-page').addEventListener('touchstart', e => {
const cp = $('chat-page');
if (!cp) return;
cp.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 => {
cp.addEventListener('touchend', e => {
if (x0 == null) return;
const t = e.changedTouches[0];
const dx = t.clientX - x0, dy = t.clientY - y0;
@@ -117,7 +60,7 @@ async function loadSessions() {
const rows = await req('GET', '/api/sessions');
const el = $('session-list');
if (!rows.length) {
el.innerHTML = '<div class="empty-tip">还没有任务,点右上角 + 新建</div>';
el.innerHTML = '<div class="empty-tip">还没有任务,点右上角 + 新建</div>';
return;
}
el.innerHTML = rows.map(s => {
@@ -132,7 +75,7 @@ async function loadSessions() {
'<button class="session-del" onclick="event.stopPropagation();ui.deleteSession(\'' + s.id + '\')">删除</button>' +
'</div>';
}).join('');
} catch (e) { toast('加载会话失败:' + e.message); }
} catch (e) { toast('加载会话失败:' + e.message); }
}
async function loadModels() {
@@ -169,7 +112,7 @@ function fillToolResult(id, content, isError) {
if (isError) card.classList.add('error');
card.querySelector('.spin').textContent = isError ? '✕' : '✓';
const pre = card.querySelector('.tool-result');
if (pre) pre.textContent = content || '(空)';
if (pre) pre.textContent = content || '(空)';
}
function msgNode(m, cardMap) {
@@ -206,7 +149,7 @@ function appendToolCardsFromAssistant(m, container) {
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));
if (state.toolCards[id]) continue; // tool_call 事件已经建过同一张卡,不重复创建
if (state.toolCards[id]) continue; // tool_call 事件已经建过同一张卡,不重复创建
const card = renderToolCard(id, c.function.name, c.function.arguments);
container.appendChild(card);
state.toolCards[id] = card;
@@ -230,7 +173,7 @@ async function renderDetail(detail) {
if (m.role === 'assistant') appendToolCardsFromAssistant(m, box);
}
if (!detail.messages.length) {
box.innerHTML = '<div class="empty-tip">描述你的需求,AI 会和你讨论并直接干活。</div>';
box.innerHTML = '<div class="empty-tip">描述你的需求,AI 会和你讨论并直接干活。</div>';
}
scrollBottom();
loadFiles();
@@ -242,7 +185,7 @@ function scrollBottom() {
}
// ---------- AI 处理中占位 ----------
// 发送后立即挂一个「思考中 + 秒计时」占位气泡,首个增量/回复/工具卡到达时移除,
// 发送后立即挂一个「思考中 + 秒计时」占位气泡,首个增量/回复/工具卡到达时移除,
// 避免上游慢时长时间无反馈像卡死。
function addPendingBubble() {
removePendingBubble();
@@ -319,7 +262,7 @@ function connectStream() {
es.addEventListener('tool_call', ev => {
const d = JSON.parse(ev.data);
removePendingBubble(); // 工具卡出现也算即时反馈
if (state.toolCards[d.id]) return; // assistant_message 已建卡(含完整参数),不重复创建
if (state.toolCards[d.id]) return; // assistant_message 已建卡(含完整参数),不重复创建
const card = renderToolCard(d.id, d.name, d.arguments);
$('messages').appendChild(card);
state.toolCards[d.id] = card;
@@ -331,7 +274,7 @@ function connectStream() {
scrollBottom();
});
es.addEventListener('done', ev => {
removePendingBubble(); // 本轮结束,占位兼终止(如模型报错无回复)
removePendingBubble(); // 本轮结束,占位兼终止(如模型报错无回复)
loadSessions();
loadModels();
});
@@ -339,8 +282,8 @@ function connectStream() {
removePendingBubble();
try {
const d = JSON.parse(ev.data);
if (d && d.message) toast('错误:' + d.message);
} catch (_) { /* EventSource 连接错误,自动重连 */ }
if (d && d.message) toast('错误:' + d.message);
} catch (_) { /* EventSource 连接错误,自动重连 */ }
});
}
@@ -349,16 +292,16 @@ function updatePhaseUI(d) {
const pill = $('status-pill');
const stMap = { queued: '排队中', active: '活跃中', held: '保持中', completed: '已完成', cancelled: '已终止' };
let text = stMap[state.status] || state.status || '--';
if (d && d.queue_pos) text += '(第 ' + d.queue_pos + ' 位)';
if (d && d.queue_pos) text += '(第 ' + d.queue_pos + ' 位)';
// active/held 时附带当前占用的模型
if ((state.status === 'active' || state.status === 'held') && d && d.model_id) {
text += ' · ' + d.model_id;
}
pill.textContent = text;
// 状态胶囊配色:活跃中绿(执行中)、保持中黄(已答完、保持模型中)等;状态栏整体同步染色
// 状态胶囊配色:活跃中绿(执行中)、保持中黄(已答完、保持模型中)等;状态栏整体同步染色
pill.className = 'status-pill ' + (state.status || '');
$('phase-bar').className = 'phase-bar ' + (state.status || '');
// 活跃中提供「终止」;保持中改为「断开」(主动放弃保持租约,会话结为已完成)
// 活跃中提供「终止」;保持中改为「断开」(主动放弃保持租约,会话结为已完成)
const btn = $('stop-btn');
const actionable = state.status === 'active' || state.status === 'held';
btn.classList.toggle('hidden', !actionable);
@@ -367,16 +310,16 @@ function updatePhaseUI(d) {
}
// ---------- 文件 ----------
// 下载:先换一枚短时效签名链接,再 window.location.href 交给浏览器原生下载。
// (fetch+blob 在移动端浏览器会被改名 uuid.bin;原生导航下载按服务端
// Content-Disposition 保留原名,同源自动携带登录 cookie。)
// 下载:先换一枚短时效签名链接,再 window.location.href 交给浏览器原生下载。
// (fetch+blob 在移动端浏览器会被改名 uuid.bin;原生导航下载按服务端
// Content-Disposition 保留原名,同源自动携带登录 cookie。)
async function downloadFile(name) {
if (!state.sessionId) return;
try {
const r = await req('GET', '/api/sessions/' + state.sessionId + '/files/download-token?path=' + encodeURIComponent(name));
window.location.href = r.url;
} catch (e) {
toast('下载失败:' + e.message);
toast('下载失败:' + e.message);
}
}
@@ -395,7 +338,7 @@ async function loadFiles() {
'<button class="file-act" onclick="ui.downloadFile(\'' + esc(f.filename) + '\')">下载</button>' +
'<button class="file-act del" onclick="ui.deleteFile(\'' + esc(f.filename).replace(/'/g, '%27') + '\')">删</button></div>';
}).join('');
} catch (e) { toast('读取文件失败:' + e.message); }
} catch (e) { toast('读取文件失败:' + e.message); }
}
// ---------- 主逻辑 ----------
@@ -425,12 +368,12 @@ const ui = {
$('new-title').value = '';
await loadSessions();
this.openSession(s.id);
} catch (e) { toast('创建失败:' + e.message); }
} catch (e) { toast('创建失败:' + e.message); }
},
deleteSession(id) {
state.pendingDeleteId = id;
$('del-dir-check').checked = true;
$('delete-modal-text').textContent = '确定删除会话 ' + id + '?';
$('delete-modal-text').textContent = '确定删除会话 ' + id + '?';
$('delete-modal').classList.remove('hidden');
},
closeDelete() {
@@ -446,7 +389,7 @@ const ui = {
await req('DELETE', '/api/sessions/' + id + '?delete_dir=' + (delDir ? 'true' : 'false'));
if (state.sessionId === id) this.backToList();
loadSessions();
} catch (e) { toast('删除失败:' + e.message); }
} catch (e) { toast('删除失败:' + e.message); }
},
async openSession(id) {
state.sessionId = id;
@@ -455,7 +398,7 @@ const ui = {
const detail = await req('GET', '/api/sessions/' + id);
await renderDetail(detail);
connectStream();
} catch (e) { toast('打开会话失败:' + e.message); }
} catch (e) { toast('打开会话失败:' + e.message); }
},
backToList() {
if (state.es) { state.es.close(); state.es = null; }
@@ -478,16 +421,16 @@ const ui = {
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>' +
wrap.innerHTML = '<div class="msg-user">我' + (r.delivered === 'queued' ? '(排队中,暂存)' : '') + '</div>' +
'<div class="msg-bubble">' + esc(content) + '</div>';
box.appendChild(wrap);
// 立即给出回馈:占位气泡 + 等待计时,首个增量/回复到达时移除并填充内容
// 立即给出回馈:占位气泡 + 等待计时,首个增量/回复到达时移除并填充内容
if (r.delivered !== 'queued') addPendingBubble();
scrollBottom();
} catch (e) { toast('发送失败:' + e.message); }
} catch (e) { toast('发送失败:' + e.message); }
},
toggleFiles(ev) {
// 阻断冒泡,避免开启面板的同一次点击被「点外部自动关闭」监听器立刻关掉
// 阻断冒泡,避免开启面板的同一次点击被「点外部自动关闭」监听器立刻关掉
if (ev) ev.stopPropagation();
state.filePanelOpen = !state.filePanelOpen;
$('files-panel').classList.toggle('hidden', !state.filePanelOpen);
@@ -499,12 +442,12 @@ const ui = {
try {
if (held) {
await req('POST', '/api/sessions/' + state.sessionId + '/release');
toast('已断开,模型已释放');
toast('已断开,模型已释放');
} else {
await req('POST', '/api/sessions/' + state.sessionId + '/stop');
toast('已发送终止指令');
}
} catch (e) { toast((held ? '断开失败:' : '终止失败:') + e.message); }
} catch (e) { toast((held ? '断开失败:' : '终止失败:') + e.message); }
},
async uploadFiles(ev) {
const input = ev.target;
@@ -517,19 +460,19 @@ const ui = {
const r = await req('POST', '/api/sessions/' + state.sessionId + '/files', fd, true);
toast('已上传 ' + r.uploaded.length + ' 个文件');
loadFiles();
} catch (e) { toast('上传失败:' + e.message); }
} catch (e) { toast('上传失败:' + e.message); }
},
async deleteFile(name) {
if (!confirm('删除文件 ' + name + '?')) return;
if (!confirm('删除文件 ' + name + '?')) return;
try {
await req('DELETE', '/api/sessions/' + state.sessionId + '/files?path=' + encodeURIComponent(name));
loadFiles();
} catch (e) { toast('删除失败:' + e.message); }
} catch (e) { toast('删除失败:' + e.message); }
},
logout() { location.href = '/logout'; },
};
// 文件面板展开时,点击面板以外的区域自动关闭
// 文件面板展开时,点击面板以外的区域自动关闭
document.addEventListener('click', e => {
if (!state.filePanelOpen) return;
if ($('files-panel').contains(e.target)) return;
@@ -537,18 +480,6 @@ document.addEventListener('click', e => {
$('files-panel').classList.add('hidden');
});
// ---------- 登录态:显示当前用户;未启用认证(/api/me 404)则隐藏退出按钮 ----------
async function initAuth() {
try {
const me = await req('GET', '/api/me');
if (me && me.user) {
$('whoami').textContent = me.user;
$('whoami').classList.remove('hidden');
$('logout-btn').classList.remove('hidden');
}
} catch (_) { /* 未启用认证 */ }
}
// ---------- 输入框行为 ----------
document.addEventListener('input', e => {
if (e.target.id === 'msg-input') {
@@ -558,17 +489,19 @@ document.addEventListener('input', e => {
});
document.addEventListener('keydown', e => {
if (e.target.id !== 'msg-input' || e.key !== 'Enter') return;
if (e.isComposing) return; // 中文输入法候选中,回车不拦截
// 桌面:Ctrl/⌘/⌥+Enter 发送;其余 Enter(含手机软键盘)保持默认换行,发送用右侧按钮
if (e.isComposing) return; // 中文输入法候选中,回车不拦截
// 桌面:Ctrl/⌘/⌥+Enter 发送;其余 Enter(含手机软键盘)保持默认换行,发送用右侧按钮
if (e.ctrlKey || e.metaKey || e.altKey) {
e.preventDefault();
ui.send();
}
});
// ---------- 启动 ----------
showList();
// ---------- Tab 注册 ----------
window.tabModules = window.tabModules || {};
tabModules.tasks = {
onShow() {
loadSessions();
loadModels();
initAuth();
setInterval(loadSessions, 8000);
},
};