Files
agent/app/server/public/v2.html
T
kicer 5b72a0bcf7 v2 抽出独立 CSS 并接入真实后端接口
- 将 v2.html 内联样式抽取为 public/css/v2.css
- v2 前端接入 /api/sessions 列表/搜索/详情、消息发送、SSE 流式、文件上传、会话删除
- 尚未接入或后端无支撑的能力以注释列出(重命名/终止/绑定/清空/下载/模式/深度思考等)
2026-09-03 11:42:05 +08:00

676 lines
28 KiB
HTML
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.
<!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 任务台 · v2</title>
<meta name="theme-color" content="#3964FE">
<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/v2.css">
</head>
<body>
<div id="app">
<!-- ================= 顶部导航栏 ================= -->
<header class="header">
<button class="icon-btn" id="menu-btn" title="历史记录" aria-label="打开历史记录">
<svg class="ic" viewBox="0 0 24 24"><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
</button>
<div class="header-center" id="header-center"><!-- 未对话状态为空白,JS 注入对话信息 --></div>
<button class="icon-btn hidden" id="new-chat-btn" title="新建对话" aria-label="新建对话">
<svg class="ic" 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>
</header>
<main>
<!-- ================= 未对话状态:模式切换区 ================= -->
<section id="welcome-view">
<div class="welcome-head">
<div class="logo-badge">
<svg class="ic" viewBox="0 0 24 24"><rect x="4" y="8" width="16" height="12" rx="3"></rect><line x1="12" y1="4" x2="12" y2="8"></line><circle cx="12" cy="3" r="1.4"></circle><circle cx="9" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><circle cx="15" cy="13.5" r="1" fill="currentColor" stroke="none"></circle><line x1="9.5" y1="17" x2="14.5" y2="17"></line></svg>
</div>
<div class="welcome-slog</title>an">选择模式开始对话</div>
</div>
<div class="mode-switch" role="tablist" id="mode-switch">
<button class="mode-chip on" data-mode="secretary" role="tab" aria-selected="true">
<svg class="ic sm" viewBox="0 0 24 24"><path d="M6 3h12l4 6-10 13L2 9z"></path><polyline points="2 9 22 9"></polyline><polyline points="10 3 8 9 12 22"></polyline><polyline points="14 3 16 9 12 22"></polyline></svg>
文秘助理
</button>
<button class="mode-chip" data-mode="vision" role="tab" aria-selected="false">
<svg class="ic sm" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>
识图专家
</button>
</div>
<div class="mode-hint" id="mode-hint"></div>
</section>
<!-- ================= 对话状态:对话内容区 ================= -->
<section id="chat-view" class="hidden"></section>
</main>
<!-- ================= 底部输入区 ================= -->
<footer>
<div class="attach-chips hidden" id="attach-chips"></div>
<div class="input-shell">
<textarea id="msg-input" placeholder="传送信息" rows="2" enterkeyhint="send"></textarea>
<div class="input-actions">
<button class="think-toggle" id="deep-think-btn" title="深度思考">
<svg viewBox="0 0 24 24" class="ic sm"><path d="M12 10.2a1.8 1.8 0 1 0 0.001 3.6A1.8 1.8 0 0 0 12 10.2z"></path><path stroke-width="1.5" d="M15.76 15.76 C10.955 20.565 5.373 22.779 3.297 20.703 C1.22 18.627 3.434 13.045 8.24 8.24 C13.045 3.435 18.627 1.22 20.703 3.297 C22.779 5.374 20.565 10.955 15.76 15.76z"></path><path stroke-width="1.5" d="M16.096 7.904 C20.905 12.713 22.965 18.298 20.703 20.703 C18.44 23.108 13.003 20.755 8.24 15.76 C3.477 10.76 1.22 5.373 3.297 3.297 C5.374 1.22 10.955 3.434 16.096 7.904z"></path></svg>
深度思考
</button>
<button class="plus-btn" id="attach-btn" title="添加附件或图片" aria-label="添加附件">
<svg class="ic" 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>
<input type="file" id="file-input" multiple hidden>
</div>
</div>
</footer>
<!-- ================= 历史记录抽屉 ================= -->
<div id="scrim"></div>
<aside id="drawer" aria-label="对话历史">
<div class="drawer-search">
<div class="search-box">
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
<input type="search" id="search-input" placeholder="搜寻对话内容..." enterkeyhint="search">
</div>
</div>
<div class="drawer-list" id="drawer-list"></div>
<div class="drawer-user">
<div class="avatar">A</div>
<div class="user-name">Agent 用户</div>
<button class="user-more" id="user-more-btn" title="更多设置" aria-label="更多设置">
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="19" cy="12" r="1.4" fill="currentColor" stroke="none"></circle></svg>
</button>
</div>
</aside>
<div id="toast" class="hidden"></div>
</div>
<script>
/*
* ============================================================================
* Agent 任务台 v2 —— 接入真实后端(全部沿用 /api 现有接口,未新增任何接口)
* ----------------------------------------------------------------------------
* 已接入:
* GET /api/sessions?status=active&limit=100 抽屉「今天/昨天」活跃列表
* GET /api/sessions?status=done&limit=50&with_total=1 抽屉归档列表
* GET /api/sessions?q=..&limit=50 抽屉搜索
* POST /api/sessions {title:'', model_id:''} 首条消息自动建档
* GET /api/sessions/:id 打开会话(消息+文件)
* DELETE /api/sessions/:id?delete_dir=true 删除会话(操作栏删除按钮)
* POST /api/sessions/:id/messages {content, attachments} 发送消息
* POST /api/sessions/:id/files 附件上传(multipart)
* GET /api/sessions/:id/stream SSE 流式输出
*
* 后端已有但 v2 尚未接入 UI 的接口(先列出,不实现):
* PATCH /api/sessions/:id 重命名(后端已支持)
* POST /api/sessions/:id/stop | /release | /bind 终止/断开/绑定模型
* DELETE /api/sessions/:id/messages 清空会话内容
* GET /api/sessions/:id/files/download-token?path= 文件下载
* GET /api/models | /api/system/status 模型池 / 系统状态
*
* 无后端支撑、仅前端占位的概念(先不实现):
* · 「文秘助理 / 识图专家」模式 —— 后端无 mode 字段,当前仅影响提示文案
* · 「深度思考」开关 —— 后端无 reasoning/deep-think 参数,当前仅本地视觉状态
* · 「思考过程」折叠块(已思考 N 秒) —— 后端不产出 reasoning,已移除 mock
* · 按消息粒度删除 —— 现有接口为会话级删除,故操作栏删除按钮指向删除会话
* 鉴权:任意请求 401 时跳转 /login(与 core.js 的 req 一致)。
* ============================================================================
*/
'use strict';
// ---------- 工具 ----------
function $(id) { return document.getElementById(id); }
function esc(s) { const d = document.createElement('div'); d.textContent = s == null ? '' : String(s); return d.innerHTML; }
function fmtTime(ts) {
if (!ts) return '';
const d = new Date(ts);
const p = n => String(n).padStart(2, '0');
const now = new Date();
const hm = p(d.getHours()) + ':' + p(d.getMinutes());
if (now.toDateString() === d.toDateString()) return hm;
const md = (d.getMonth() + 1) + '/' + d.getDate();
return (d.getFullYear() === now.getFullYear() ? md : d.getFullYear() + '/' + md) + ' ' + hm;
}
function toast(msg) {
const el = $('toast');
el.textContent = msg;
el.classList.remove('hidden');
clearTimeout(toast._t);
toast._t = setTimeout(() => el.classList.add('hidden'), 2000);
}
async function copyText(text) {
try {
if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; }
} catch (_) { /* 落入降级 */ }
try {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed'; ta.style.top = '0'; ta.style.left = '-9999px'; ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
ta.setSelectionRange(0, ta.value.length);
const ok = document.execCommand('copy');
document.body.removeChild(ta);
return ok;
} catch (_) { return false; }
}
// ---------- API(与 core.js 的 req 保持一致) ----------
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 (_) {}
const err = new Error(msg);
err.status = res.status;
throw err;
}
return res.json();
}
// ---------- 模式配置 ----------
const MODES = {
secretary: { label: '文秘助理', hint: '支持文字输入,可起草、润色、整理文书' },
vision: { label: '识图专家', hint: '支持图片识别输入' },
};
// ---------- 全局状态 ----------
const state = {
view: 'welcome', // welcome | chat
mode: 'secretary', // 模式选择区当前选中
deepThink: false, // 深度思考开关(仅本地视觉状态,无后端参数)
sessionId: null, // 当前会话
sessionTitle: '', // 当前会话标题
status: '', // 当前会话状态(SSE 更新)
sessions: [], // 抽屉列表缓存
attachments: [], // 待发送附件 {file, name, size}
es: null, // EventSource
streamText: '', // 当前流式累积文本
streamEl: null, // 当前流式 AI 气泡
toolLines: {}, // tool_call_id -> 工具行元素
typingEl: null, // 「思考中」占位
streaming: false,
};
// ---------- 视图切换 ----------
function setView(view) {
state.view = view;
$('welcome-view').classList.toggle('hidden', view !== 'welcome');
$('chat-view').classList.toggle('hidden', view !== 'chat');
$('new-chat-btn').classList.toggle('hidden', view !== 'chat'); // 新建按钮仅对话状态显示
renderHeader();
}
function renderHeader() {
const c = $('header-center');
if (state.view !== 'chat' || !state.sessionId) { c.innerHTML = ''; return; }
const stMap = { queued: '排队中', active: '活跃中', held: '保持中', completed: '已完成', cancelled: '已终止' };
const st = stMap[state.status] || '';
c.innerHTML =
'<div class="header-title">' + esc(state.sessionTitle || state.sessionId) + '</div>' +
'<div class="header-sub"><span class="mode">' + esc(MODES[state.mode].label) + '</span>' +
(st ? ' · ' + esc(st) : '') + ' · 回答由 AI 产生,仅供参考</div>';
}
// ---------- 模式切换区 ----------
function selectMode(mode) {
state.mode = mode;
for (const chip of document.querySelectorAll('.mode-chip')) {
const on = chip.dataset.mode === mode;
chip.classList.toggle('on', on);
chip.setAttribute('aria-selected', on ? 'true' : 'false');
}
$('mode-hint').textContent = MODES[mode].hint;
}
$('mode-switch').addEventListener('click', e => {
const chip = e.target.closest('.mode-chip');
if (chip) selectMode(chip.dataset.mode);
});
// ---------- 消息渲染 ----------
// 服务端把附件说明拼在正文前(【系统通知】用户上传了文件:...),此处拆开单独展示 📎 行
function parseUploadNotice(content) {
const m = /^【系统通知】用户上传了文件:([^\n]*)(?:\n([\s\S]*))?$/.exec(content || '');
if (!m) return { text: content || '', files: null };
const files = m[1].split('、').map(s => s.replace(/(大小[^)]*)$/, '').trim()).filter(Boolean);
return { text: m[2] || '', files: files };
}
function actionsHtml(ts, content) {
const b64 = btoa(unescape(encodeURIComponent(content)));
return '<div class="msg-actions">' +
'<span>' + fmtTime(ts) + '</span>' +
'<button class="act act-copy" title="复制" data-b64="' + b64 + '">' +
'<svg class="ic sm" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>' +
'</button>' +
'<button class="act act-del" title="删除会话">' +
'<svg class="ic sm" viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>' +
'</button>' +
'</div>';
}
function userMsgHtml(m) {
const p = parseUploadNotice(m.content);
const attach = p.files && p.files.length
? '<div class="attach-line">📎 ' + esc(p.files.join('、')) + '</div>' : '';
return '<div class="msg me">' +
'<div class="bubble-user">' + attach + esc(p.text) + '</div>' +
'<div class="msg-actions"><span>' + fmtTime(m.created_at) + '</span></div>' +
'</div>';
}
function aiMsgHtml(m) {
const hasText = !!(m.content && m.content.trim());
let toolLines = '';
if (m.tool_calls) {
let calls = m.tool_calls;
try { if (typeof calls === 'string') calls = JSON.parse(calls); } catch (_) { calls = null; }
if (Array.isArray(calls)) {
toolLines = calls.map(c => '<div class="tool-line">🔧 ' + esc(c.function && c.function.name || '工具') + '</div>').join('');
}
}
return '<div class="msg other">' +
toolLines +
(hasText ? '<div class="bubble-ai">' + esc(m.content) + '</div>' : '') +
(hasText ? actionsHtml(m.created_at, m.content) : '') +
'</div>';
}
function msgNode(m) {
if (m.role === 'user') return userMsgHtml(m);
if (m.role === 'assistant') return aiMsgHtml(m);
return null; // tool 结果不单独展示
}
function renderDetail(detail) {
const s = detail.session;
state.sessionTitle = (s && s.title) || '';
state.status = (s && s.status) || '';
renderHeader();
const box = $('chat-view');
box.innerHTML = '';
for (const m of detail.messages || []) {
const node = msgNode(m);
if (node) box.insertAdjacentHTML('beforeend', node);
}
if (!(detail.messages || []).length) {
box.innerHTML = '<div class="drawer-empty">描述你的需求,AI 会和你讨论并直接干活。</div>';
}
scrollBottom();
}
function appendUserMsg(content, fileNames) {
const attach = fileNames && fileNames.length
? '<div class="attach-line">📎 ' + esc(fileNames.join('、')) + '</div>' : '';
const wrap = document.createElement('div');
wrap.className = 'msg me';
wrap.innerHTML = '<div class="bubble-user">' + attach + esc(content) + '</div>' +
'<div class="msg-actions"><span>' + fmtTime(Date.now()) + '</span></div>';
$('chat-view').appendChild(wrap);
scrollBottom();
}
function scrollBottom() {
const box = $('chat-view');
box.scrollTop = box.scrollHeight;
}
function addTyping() {
removeTyping();
const ph = document.createElement('div');
ph.className = 'msg other';
ph.innerHTML = '<div class="typing"><i></i><i></i><i></i></div>';
$('chat-view').appendChild(ph);
state.typingEl = ph;
scrollBottom();
}
function removeTyping() {
if (state.typingEl) { state.typingEl.remove(); state.typingEl = null; }
}
// ---------- 会话列表(抽屉) ----------
function groupLabel(ts) {
const d = new Date(ts), n = new Date();
const sod = t => new Date(t.getFullYear(), t.getMonth(), t.getDate()).getTime();
const diff = (sod(n) - sod(d)) / 86400000;
if (diff <= 0) return '今天';
if (diff === 1) return '昨天';
return d.getFullYear() + '年' + (d.getMonth() + 1) + '月';
}
function renderDrawerList() {
const list = state.sessions.slice().sort((a, b) => (b.updated_at || 0) - (a.updated_at || 0));
const box = $('drawer-list');
if (!list.length) { box.innerHTML = '<div class="drawer-empty">没有找到相关对话</div>'; return; }
let html = '', lastGroup = null;
for (const s of list) {
const g = groupLabel(s.updated_at);
if (g !== lastGroup) { html += '<div class="group-label">' + esc(g) + '</div>'; lastGroup = g; }
html += '<button class="conv-item' + (s.id === state.sessionId ? ' active' : '') + '" data-id="' + esc(s.id) + '">' +
esc(s.title || s.id) + '</button>';
}
box.innerHTML = html;
}
async function loadSessionList() {
const q = $('search-input').value.trim();
try {
let list;
if (q) {
const r = await req('GET', '/api/sessions?q=' + encodeURIComponent(q) + '&limit=50&with_total=1');
list = r.rows || [];
} else {
const [active, done] = await Promise.all([
req('GET', '/api/sessions?status=active&limit=100'),
req('GET', '/api/sessions?status=done&limit=50&with_total=1'),
]);
list = (active || []).concat((done && done.rows) || []);
}
state.sessions = list;
renderDrawerList();
} catch (e) { toast('加载会话失败:' + e.message); }
}
// ---------- 会话打开 / 新建 / 删除 ----------
function closeStream() {
if (state.es) { state.es.close(); state.es = null; }
}
async function openSession(id) {
closeStream();
removeTyping();
state.sessionId = id;
state.streamEl = null;
state.streamText = '';
state.toolLines = {};
state.streaming = false;
state.attachments = [];
renderAttachChips();
setView('chat');
$('chat-view').innerHTML = '<div class="drawer-empty">加载中…</div>';
try {
const detail = await req('GET', '/api/sessions/' + id);
if (state.sessionId !== id) return; // 期间已切到别的会话
renderDetail(detail);
connectStream();
} catch (e) {
if (state.sessionId === id) toast('打开会话失败:' + e.message);
}
}
// 确保存在当前会话:首条消息自动建档(POST /api/sessions)
async function ensureSession() {
if (state.sessionId) return state.sessionId;
const s = await req('POST', '/api/sessions', { title: '', model_id: '' });
state.sessionId = s.id;
state.sessionTitle = (s && s.title) || '';
setView('chat');
renderHeader();
connectStream();
return s.id;
}
function newChat() {
closeStream();
removeTyping();
state.sessionId = null;
state.sessionTitle = '';
state.status = '';
state.attachments = [];
state.streamEl = null;
state.streamText = '';
state.toolLines = {};
state.streaming = false;
renderAttachChips();
selectMode('secretary'); // 置顶逻辑:新建时自动选中【文秘助理】
setView('welcome');
$('chat-view').innerHTML = '';
$('msg-input').value = '';
autosize();
}
async function deleteSession() {
if (!state.sessionId) return;
const id = state.sessionId;
if (!confirm('删除整个会话?其任务文件也将一并删除,且不可恢复。')) return;
try {
await req('DELETE', '/api/sessions/' + id + '?delete_dir=true');
newChat();
loadSessionList();
} catch (e) { toast('删除失败:' + e.message); }
}
// ---------- 发送 ----------
async function uploadFiles(sessionId, files) {
const fd = new FormData();
for (const f of files) fd.append('files', f.file, f.name);
const r = await req('POST', '/api/sessions/' + sessionId + '/files', fd, true);
return (r.uploaded || []).map(u => ({ name: u.filename, size: u.size }));
}
async function send() {
const ta = $('msg-input');
const content = ta.value.trim();
if (!content && !state.attachments.length) return;
const pending = state.attachments.slice();
state.attachments = [];
renderAttachChips();
ta.value = '';
autosize();
try {
const id = await ensureSession();
let atts = [];
if (pending.length) atts = await uploadFiles(id, pending);
const body = { content };
if (atts.length) body.attachments = atts;
await req('POST', '/api/sessions/' + id + '/messages', body);
appendUserMsg(content, atts.map(a => a.name));
if (!state.sessionTitle && content) {
state.sessionTitle = content.length > 24 ? content.slice(0, 24) : content;
}
renderHeader();
addTyping();
loadSessionList();
} catch (e) {
// 发送失败:附件还原,交由用户决定重试或移除
state.attachments = pending.concat(state.attachments);
renderAttachChips();
toast('发送失败:' + e.message);
}
}
// ---------- SSE 流式 ----------
function connectStream() {
closeStream();
if (!state.sessionId) return;
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;
renderHeader();
});
es.addEventListener('assistant_delta', ev => {
const d = JSON.parse(ev.data);
removeTyping();
state.streamText += d.text;
if (!state.streamEl) {
if (!state.streamText.trim()) return; // 忽略前导空白(纯工具调用回合无文本)
const wrap = document.createElement('div');
wrap.className = 'msg other';
const bubble = document.createElement('div');
bubble.className = 'bubble-ai';
wrap.appendChild(bubble);
$('chat-view').appendChild(wrap);
state.streamEl = bubble;
state.streamText = d.text;
}
state.streamEl.textContent = state.streamText;
state.streaming = true;
scrollBottom();
});
es.addEventListener('assistant_message', ev => {
const d = JSON.parse(ev.data);
removeTyping();
const hasText = !!(d.content && d.content.trim());
if (state.streamEl) {
if (hasText) state.streamEl.textContent = d.content;
else state.streamEl.remove();
state.streamEl = null;
state.streamText = '';
} else if (hasText) {
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="bubble-ai">' + esc(d.content) + '</div>';
$('chat-view').appendChild(wrap);
}
state.streaming = false;
scrollBottom();
});
es.addEventListener('tool_call', ev => {
const d = JSON.parse(ev.data);
removeTyping();
const wrap = document.createElement('div');
wrap.className = 'msg other';
wrap.innerHTML = '<div class="tool-line">🔧 ' + esc(d.name || '工具') + '</div>';
$('chat-view').appendChild(wrap);
state.toolLines[d.id] = wrap;
scrollBottom();
});
es.addEventListener('tool_result', ev => {
const d = JSON.parse(ev.data);
const wrap = state.toolLines[d.tool_call_id];
if (wrap && d.is_error) {
const line = wrap.querySelector('.tool-line');
if (line) line.textContent += ' ⚠️ 失败';
}
scrollBottom();
});
es.addEventListener('done', ev => {
removeTyping();
state.streaming = false;
state.streamEl = null;
state.streamText = '';
state.toolLines = {};
loadSessionList();
});
es.addEventListener('error', ev => {
removeTyping();
try {
const d = JSON.parse(ev.data);
if (d && d.message) toast('错误:' + d.message);
} catch (_) { /* EventSource 连接错误,自动重连 */ }
});
}
// ---------- 消息区点击代理(复制 / 删除) ----------
$('chat-view').addEventListener('click', async e => {
const copyBtn = e.target.closest('.act-copy');
if (copyBtn) {
let text = '';
try { text = decodeURIComponent(escape(atob(copyBtn.dataset.b64 || ''))); } catch (_) {}
const ok = await copyText(text);
toast(ok ? '已复制' : '复制失败');
if (ok) {
copyBtn.classList.add('copied');
setTimeout(() => copyBtn.classList.remove('copied'), 1200);
}
return;
}
const delBtn = e.target.closest('.act-del');
if (delBtn) { deleteSession(); }
});
// ---------- 输入区 ----------
const ta = $('msg-input');
function autosize() { ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 120) + 'px'; }
ta.addEventListener('input', autosize);
ta.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
});
// 深度思考开关(仅本地视觉状态,后端无 reasoning 参数)
$('deep-think-btn').addEventListener('click', () => {
state.deepThink = !state.deepThink;
$('deep-think-btn').classList.toggle('on', state.deepThink);
toast(state.deepThink ? '深度思考已开启(暂不影响后端)' : '深度思考已关闭');
});
// 加号:选择附件(仅入队本地展示,发送时才真正上传)
$('attach-btn').addEventListener('click', () => $('file-input').click());
$('file-input').addEventListener('change', e => {
for (const f of Array.prototype.slice.call(e.target.files || [])) {
state.attachments.push({ file: f, name: f.name, size: f.size });
}
e.target.value = '';
renderAttachChips();
});
function renderAttachChips() {
const row = $('attach-chips');
row.classList.toggle('hidden', !state.attachments.length);
row.innerHTML = state.attachments.map((f, i) =>
'<span class="attach-chip"><span class="name">' + esc(f.name) + '</span>' +
'<button class="rm" data-i="' + i + '" aria-label="移除附件">' +
'<svg class="ic sm" 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></span>').join('');
}
$('attach-chips').addEventListener('click', e => {
const rm = e.target.closest('.rm');
if (rm) { state.attachments.splice(+rm.dataset.i, 1); renderAttachChips(); }
});
// ---------- 抽屉 ----------
function openDrawer(open) {
$('drawer').classList.toggle('open', open);
$('scrim').classList.toggle('show', open);
}
$('menu-btn').addEventListener('click', () => {
const open = !$('drawer').classList.contains('open');
openDrawer(open);
if (open) loadSessionList();
});
$('scrim').addEventListener('click', () => openDrawer(false));
let searchTimer = null;
$('search-input').addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(loadSessionList, 250);
});
$('drawer-list').addEventListener('click', e => {
const item = e.target.closest('.conv-item');
if (!item) return;
openSession(item.dataset.id);
openDrawer(false);
});
$('user-more-btn').addEventListener('click', () => toast('更多设置:待接入'));
// ---------- 顶栏 ----------
$('new-chat-btn').addEventListener('click', newChat);
// ---------- 初始化 ----------
selectMode('secretary'); // 默认选中【文秘助理】
setView('welcome');
loadSessionList();
</script>
</body>
</html>