<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>CmdCode WebUI</title>
<style>
/* ==================== 设计令牌 ==================== */
:root {
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--mono: "SF Mono", "Fira Code", "Fira Mono", Menlo, Consolas, monospace;
--radius: 12px;
--radius-sm: 8px;
--radius-xs: 4px;
--shadow: 0 4px 16px rgba(0,0,0,0.08);
/* 亮色主题 */
--bg-primary: #ffffff;
--bg-secondary: #f5f5f7;
--bg-tertiary: #e8e8ed;
--text-primary: #1d1d1f;
--text-secondary: #86868b;
--border: #d2d2d7;
--border-light: #e5e5ea;
--accent: #0071e3;
--accent-hover: #0077ed;
--danger: #ff3b30;
--success: #34c759;
--warning: #ff9500;
--bubble-user: #0071e3;
--bubble-user-text: #ffffff;
--bubble-assistant: #f2f2f7;
--bubble-assistant-text: #1d1d1f;
--code-bg: #f4f4f4;
--header-bg: rgba(255,255,255,0.8);
}
/* 暗色主题 */
[data-theme="dark"] {
--bg-primary: #1c1c1e;
--bg-secondary: #2c2c2e;
--bg-tertiary: #3a3a3c;
--text-primary: #f5f5f7;
--text-secondary: #98989d;
--border: #48484a;
--border-light: #3a3a3c;
--bubble-user: #0a84ff;
--bubble-assistant: #2c2c2e;
--bubble-assistant-text: #f5f5f7;
--code-bg: #2c2c2e;
--header-bg: rgba(28,28,30,0.8);
}
/* 重置 */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { height: 100%; }
body {
font-family: var(--font);
background: var(--bg-primary);
color: var(--text-primary);
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
-webkit-font-smoothing: antialiased;
}
/* 顶部导航 */
header {
display: flex; align-items: center; justify-content: space-between;
padding: 12px 20px; background: var(--header-bg);
backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px);
border-bottom: 1px solid var(--border-light); z-index: 10;
}
.brand { font-weight: 600; font-size: 18px; }
.header-actions { display: flex; gap: 8px; align-items: center; }
/* 按钮通用 */
button {
font-family: var(--font); border: none; cursor: pointer;
transition: all 0.2s; outline: none;
}
.icon-btn {
width: 36px; height: 36px; border-radius: 50%;
background: var(--bg-tertiary); color: var(--text-primary);
display: flex; align-items: center; justify-content: center;
font-size: 16px;
}
.icon-btn:hover { background: var(--border); }
.btn-primary {
background: var(--accent); color: white; border-radius: var(--radius-sm);
padding: 8px 16px; font-weight: 500;
}
.btn-primary:hover { background: var(--accent-hover); }
.btn-danger { background: var(--danger); color: white; border-radius: var(--radius-sm); padding: 8px 16px; }
/* 连接状态 */
#connection-status {
font-size: 12px; text-align: center; padding: 4px;
background: var(--bg-secondary); color: var(--text-secondary);
}
/* 聊天容器 */
main {
flex: 1; overflow-y: auto; padding: 20px; display: flex;
flex-direction: column; gap: 16px; scroll-behavior: smooth;
}
.welcome { text-align: center; margin: auto; padding: 40px; }
.welcome h2 { font-size: 28px; margin-bottom: 16px; }
.welcome p { color: var(--text-secondary); }
/* 消息气泡 */
.message-row { display: flex; gap: 12px; }
.message-row.user { justify-content: flex-end; }
.message-bubble {
max-width: 80%; padding: 12px 16px; border-radius: var(--radius);
line-height: 1.5; word-break: break-word; position: relative;
}
.user .message-bubble { background: var(--bubble-user); color: var(--bubble-user-text); border-bottom-right-radius: 4px; }
.assistant .message-bubble { background: var(--bubble-assistant); color: var(--bubble-assistant-text); border-bottom-left-radius: 4px; }
.msg-time { font-size: 11px; color: var(--text-secondary); margin-top: 4px; }
.assistant .msg-time { text-align: left; }
.user .msg-time { text-align: right; }
/* 代码块 */
pre {
background: var(--code-bg); border-radius: var(--radius-sm); padding: 12px;
overflow-x: auto; margin: 8px 0; font-family: var(--mono); font-size: 13px;
position: relative;
}
code { font-family: var(--mono); }
.copy-btn {
position: absolute; top: 8px; right: 8px;
background: var(--bg-tertiary); border-radius: 4px;
padding: 4px 8px; font-size: 11px; cursor: pointer; display: none;
}
pre:hover .copy-btn { display: block; }
/* 输入区 */
footer {
padding: 16px 20px; border-top: 1px solid var(--border-light);
background: var(--bg-primary); display: flex; gap: 12px; align-items: flex-end;
}
textarea {
flex: 1; resize: none; border: 1px solid var(--border);
border-radius: var(--radius); padding: 12px; font-family: var(--font);
background: var(--bg-secondary); color: var(--text-primary);
max-height: 120px; line-height: 1.5; transition: border-color 0.2s;
}
textarea:focus { border-color: var(--accent); outline: none; box-shadow: 0 0 0 2px rgba(0,113,227,0.2); }
.send-btn { width: 48px; height: 48px; border-radius: 50%; background: var(--accent); color: white; font-size: 20px; }
.send-btn:disabled { opacity: 0.5; cursor: default; }
/* 自定义下拉(模型选择器) */
.custom-select { position: relative; min-width: 200px; }
.select-selected {
padding: 8px 14px; border: 1px solid var(--border); border-radius: var(--radius-sm);
cursor: pointer; display: flex; justify-content: space-between; align-items: center;
background: var(--bg-primary); white-space: nowrap;
}
.select-selected:hover { border-color: var(--accent); }
.select-items {
position: absolute; top: 110%; left: 0; right: 0; z-index: 100;
background: var(--bg-primary); border: 1px solid var(--border);
border-radius: var(--radius-sm); max-height: 320px; overflow-y: auto;
box-shadow: var(--shadow); display: none;
}
.model-option {
padding: 10px 14px; cursor: pointer; display: flex; justify-content: space-between;
align-items: center; border-bottom: 1px solid var(--border-light);
transition: background 0.15s;
}
.model-option:hover { background: var(--bg-secondary); }
.model-option:last-child { border-bottom: none; }
.model-name { font-weight: 500; }
.model-provider { font-size: 0.8em; color: var(--text-secondary); margin-left: 8px; flex: 1; }
.model-actions { display: flex; gap: 4px; margin-left: 8px; }
.model-actions button {
background: none; border: 1px solid var(--border); border-radius: 4px;
padding: 2px 6px; font-size: 12px;
}
.model-actions button:hover { background: var(--bg-tertiary); }
.add-model-btn {
background: var(--accent); color: white; border-radius: 50%; width: 28px; height: 28px;
font-size: 18px; display: flex; align-items: center; justify-content: center;
margin-left: 8px; flex-shrink: 0;
}
/* 弹窗 */
.modal-sheet {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.4); display: flex; align-items: center;
justify-content: center; z-index: 1000; display: none;
}
.modal-content {
background: var(--bg-primary); border-radius: var(--radius); padding: 24px;
max-width: 400px; width: 90%; box-shadow: 0 12px 40px rgba(0,0,0,0.2);
display: flex; flex-direction: column; gap: 12px;
}
.modal-content h3 { font-size: 18px; }
.modal-content input {
padding: 10px; border: 1px solid var(--border); border-radius: var(--radius-sm);
background: var(--bg-secondary); color: var(--text-primary);
}
.modal-actions { display: flex; gap: 8px; }
.modal-actions button { flex: 1; padding: 10px; border-radius: var(--radius-sm); font-weight: 500; }
/* Toast */
.toast {
position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%);
background: var(--text-primary); color: var(--bg-primary); padding: 10px 20px;
border-radius: 20px; font-size: 14px; opacity: 0; transition: opacity 0.3s; z-index: 2000;
}
.toast.show { opacity: 1; }
/* 文件浏览器 */
.file-tree { list-style: none; padding: 0; }
.file-tree li { padding: 8px 12px; cursor: pointer; display: flex; align-items: center; gap: 8px; border-radius: 4px; }
.file-tree li:hover { background: var(--bg-secondary); }
.breadcrumb { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; font-size: 14px; }
/* 响应式 */
@media (max-width: 600px) {
.message-bubble { max-width: 95%; }
.custom-select { min-width: 140px; }
}
</style>
</head>
<body>
<!-- 连接状态 -->
<div id="connection-status">已连接</div>
<!-- 头部 -->
<header>
<div class="brand">CmdCode</div>
<div class="header-actions">
<!-- 自定义模型选择器 -->
<div class="custom-select" id="model-select-container">
<div class="select-selected" id="model-select-trigger">
<span id="selected-model-name">MiniMax-M2.7</span>
<span class="arrow">▼</span>
</div>
<div class="select-items" id="model-select-dropdown"></div>
</div>
<button class="add-model-btn" id="add-model-btn" title="添加自定义模型">+</button>
<button class="icon-btn" id="theme-toggle" title="切换主题">🌓</button>
<button class="icon-btn" id="settings-btn" title="设置">⚙️</button>
<button class="icon-btn" id="memory-btn" title="记忆搜索">🧠</button>
<button class="icon-btn" id="files-btn" title="文件浏览">📁</button>
</div>
</header>
<!-- 聊天消息容器 -->
<main id="chat-container">
<div class="welcome" id="welcome-screen">
<h2>欢迎使用 CmdCode</h2>
<p>输入问题开始对话。</p>
</div>
</main>
<!-- 输入区域 -->
<footer>
<textarea id="user-input" rows="1" placeholder="输入消息… (Enter 发送, Shift+Enter 换行)"></textarea>
<button class="send-btn" id="send-btn" disabled>➤</button>
</footer>
<!-- Toast -->
<div class="toast" id="toast"></div>
<!-- 设置弹窗 -->
<div class="modal-sheet" id="settings-modal">
<div class="modal-content">
<h3>API 设置</h3>
<input type="password" id="api-key-input" placeholder="API Key(留空不更改)">
<input type="text" id="base-url-input" placeholder="接口地址 (https://api.x.com/v1)">
<input type="text" id="system-prompt-input" placeholder="系统提示词(可选)">
<div class="modal-actions">
<button class="btn-primary" id="save-settings">保存</button>
<button id="close-settings">取消</button>
</div>
</div>
</div>
<!-- 添加模型弹窗 -->
<div class="modal-sheet" id="add-model-modal">
<div class="modal-content">
<h3>添加自定义模型</h3>
<input type="text" id="new-model-name" placeholder="显示名称 (如 My-GPT)">
<input type="text" id="new-model-id" placeholder="模型 ID (如 my-gpt-4)">
<input type="text" id="new-model-provider" placeholder="厂商 (如 OpenAI)">
<input type="text" id="new-model-url" placeholder="接口地址 (https://api.x.com/v1)">
<input type="password" id="new-model-key" placeholder="API Key">
<div class="modal-actions">
<button class="btn-primary" id="confirm-add-model">添加</button>
<button id="cancel-add-model">取消</button>
</div>
</div>
</div>
<!-- 编辑模型弹窗 -->
<div class="modal-sheet" id="edit-model-modal">
<div class="modal-content">
<h3>编辑模型</h3>
<input type="hidden" id="edit-model-id">
<input type="text" id="edit-model-name" placeholder="显示名称">
<input type="text" id="edit-model-provider" placeholder="厂商">
<input type="text" id="edit-model-url" placeholder="接口地址">
<input type="password" id="edit-model-key" placeholder="API Key(留空不修改)">
<div class="modal-actions">
<button class="btn-primary" id="confirm-edit-model">保存</button>
<button id="cancel-edit-model">取消</button>
</div>
</div>
</div>
<!-- 文件浏览器弹窗 -->
<div class="modal-sheet" id="files-modal">
<div class="modal-content" style="max-width: 600px;">
<h3>文件浏览器</h3>
<div class="breadcrumb" id="file-breadcrumb"></div>
<ul class="file-tree" id="file-list"></ul>
<div style="text-align: right; margin-top: 8px;">
<button id="close-files">关闭</button>
</div>
</div>
</div>
<!-- 记忆搜索弹窗 -->
<div class="modal-sheet" id="memory-modal">
<div class="modal-content" style="max-width: 500px;">
<h3>记忆搜索</h3>
<input type="text" id="memory-query" placeholder="搜索关键词...">
<div id="memory-results" style="max-height: 300px; overflow-y: auto;"></div>
<div class="modal-actions" style="margin-top: 12px;">
<button class="btn-primary" id="search-memory-btn">搜索</button>
<button id="close-memory">关闭</button>
</div>
</div>
</div>
<script>
// ==================== 全局变量 ====================
const apiBase = window.location.origin === 'http://localhost:3010' ? 'http://localhost:3010' : 'https://你的后端域名'; // 修改为实际后端地址
let isProcessing = false;
let selectedModel = localStorage.getItem('selectedModel') || 'minimax-m2.7';
let currentFilePath = '/'; // 文件浏览当前路径
// ==================== 工具函数 ====================
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg; t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 2000);
}
function formatFileSize(bytes) {
if (!bytes) return '0 B';
const k = 1024; const sizes = ['B','KB','MB','GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
function getFileIcon(name) {
const ext = name.split('.').pop().toLowerCase();
const map = { js:'📜', ts:'📘', py:'🐍', html:'🌐', css:'🎨', json:'📋', md:'📝', txt:'📄', jsx:'⚛️', tsx:'⚛️' };
return map[ext] || '📄';
}
function scrollToBottom() {
const main = document.getElementById('chat-container');
main.scrollTop = main.scrollHeight;
}
// ==================== 主题 ====================
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('theme', theme);
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme');
applyTheme(current === 'dark' ? 'light' : 'dark');
}
(function initTheme() {
const saved = localStorage.getItem('theme') || 'light';
applyTheme(saved);
})();
// ==================== 模型管理 ====================
async function loadModels() {
try {
const res = await fetch(`${apiBase}/api/models`);
const data = await res.json();
const dropdown = document.getElementById('model-select-dropdown');
dropdown.innerHTML = '';
data.models.forEach(model => {
const item = document.createElement('div');
item.className = 'model-option';
item.innerHTML = `
<span class="model-name">${model.custom ? '⭐ ' : ''}${model.name}</span>
<span class="model-provider">${model.provider || ''}</span>
${model.custom ? `
<span class="model-actions">
<button class="edit-btn" data-id="${model.id}" title="编辑">✏️</button>
<button class="delete-btn" data-id="${model.id}" title="删除">🗑️</button>
</span>` : ''}
`;
// 选择模型
item.querySelector('.model-name').addEventListener('click', () => {
document.getElementById('selected-model-name').textContent = model.name;
selectedModel = model.id;
localStorage.setItem('selectedModel', model.id);
dropdown.style.display = 'none';
});
// 编辑
item.querySelector('.edit-btn')?.addEventListener('click', (e) => {
e.stopPropagation();
showEditModelForm(model);
});
// 删除
item.querySelector('.delete-btn')?.addEventListener('click', async (e) => {
e.stopPropagation();
if (!confirm(`确认删除模型 "${model.name}"?`)) return;
await fetch(`${apiBase}/api/models/delete`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ modelId: model.id })
});
loadModels();
});
dropdown.appendChild(item);
});
// 恢复选中状态
const saved = data.models.find(m => m.id === selectedModel);
if (saved) document.getElementById('selected-model-name').textContent = saved.name;
} catch(e) { console.error('加载模型失败', e); }
}
// 下拉开关
document.getElementById('model-select-trigger').addEventListener('click', (e) => {
e.stopPropagation();
const dd = document.getElementById('model-select-dropdown');
dd.style.display = dd.style.display === 'block' ? 'none' : 'block';
});
document.addEventListener('click', (e) => {
if (!e.target.closest('#model-select-container')) {
document.getElementById('model-select-dropdown').style.display = 'none';
}
});
// 添加模型
document.getElementById('add-model-btn').addEventListener('click', () => {
document.getElementById('add-model-modal').style.display = 'flex';
});
document.getElementById('cancel-add-model').addEventListener('click', () => {
document.getElementById('add-model-modal').style.display = 'none';
});
document.getElementById('confirm-add-model').addEventListener('click', async () => {
const name = document.getElementById('new-model-name').value.trim();
const id = document.getElementById('new-model-id').value.trim();
const provider = document.getElementById('new-model-provider').value.trim();
const url = document.getElementById('new-model-url').value.trim();
const key = document.getElementById('new-model-key').value.trim();
if (!name || !id) return alert('名称和ID为必填');
const res = await fetch(`${apiBase}/api/models/add`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ name, id, provider, url, key })
});
const data = await res.json();
if (data.success) {
document.getElementById('add-model-modal').style.display = 'none';
loadModels();
showToast('模型已添加');
['new-model-name','new-model-id','new-model-provider','new-model-url','new-model-key'].forEach(x => document.getElementById(x).value = '');
} else alert('添加失败: ' + data.error);
});
// 编辑模型
function showEditModelForm(model) {
document.getElementById('edit-model-id').value = model.id;
document.getElementById('edit-model-name').value = model.name;
document.getElementById('edit-model-provider').value = model.provider || '';
document.getElementById('edit-model-url').value = model.url || '';
document.getElementById('edit-model-key').value = '';
document.getElementById('edit-model-modal').style.display = 'flex';
}
document.getElementById('cancel-edit-model').addEventListener('click', () => {
document.getElementById('edit-model-modal').style.display = 'none';
});
document.getElementById('confirm-edit-model').addEventListener('click', async () => {
const modelId = document.getElementById('edit-model-id').value;
const updates = {};
const name = document.getElementById('edit-model-name').value.trim();
const provider = document.getElementById('edit-model-provider').value.trim();
const url = document.getElementById('edit-model-url').value.trim();
const key = document.getElementById('edit-model-key').value.trim();
if (name) updates.name = name;
if (provider) updates.provider = provider;
if (url) updates.baseUrl = url;
if (key) updates.apiKey = key;
const res = await fetch(`${apiBase}/api/models/update`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ modelId, updates })
});
const data = await res.json();
if (data.success) {
document.getElementById('edit-model-modal').style.display = 'none';
loadModels();
showToast('模型已更新');
} else alert('更新失败: ' + data.error);
});
// 初始加载模型列表
loadModels();
// ==================== 设置 ====================
document.getElementById('settings-btn').addEventListener('click', () => {
document.getElementById('settings-modal').style.display = 'flex';
});
document.getElementById('close-settings').addEventListener('click', () => {
document.getElementById('settings-modal').style.display = 'none';
});
document.getElementById('save-settings').addEventListener('click', async () => {
const key = document.getElementById('api-key-input').value;
const url = document.getElementById('base-url-input').value;
const prompt = document.getElementById('system-prompt-input').value;
await fetch(`${apiBase}/api/settings`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ apiKey: key, baseUrl: url, systemPrompt: prompt })
});
showToast('设置已保存');
document.getElementById('settings-modal').style.display = 'none';
});
// ==================== 文件浏览 ====================
document.getElementById('files-btn').addEventListener('click', () => {
document.getElementById('files-modal').style.display = 'flex';
loadFileTree('/');
});
document.getElementById('close-files').addEventListener('click', () => {
document.getElementById('files-modal').style.display = 'none';
});
async function loadFileTree(path) {
try {
const res = await fetch(`${apiBase}/api/files?path=${encodeURIComponent(path)}`);
const data = await res.json();
currentFilePath = path;
renderBreadcrumb(path);
const list = document.getElementById('file-list');
list.innerHTML = '';
if (path !== '/') {
const up = document.createElement('li');
up.innerHTML = '📁 ..';
up.addEventListener('click', () => {
const parent = path.split('/').slice(0, -1).join('/') || '/';
loadFileTree(parent);
});
list.appendChild(up);
}
data.files.forEach(f => {
const li = document.createElement('li');
li.innerHTML = `${f.type === 'dir' ? '📁' : getFileIcon(f.name)} ${f.name}`;
li.addEventListener('click', () => {
if (f.type === 'dir') loadFileTree(path + f.name + '/');
else showFileContent(path + f.name);
});
list.appendChild(li);
});
} catch(e) { showToast('加载文件失败'); }
}
function renderBreadcrumb(path) {
const parts = path.split('/').filter(p => p);
const bc = document.getElementById('file-breadcrumb');
bc.innerHTML = '<span class="crumb" data-path="/">根目录</span>';
let accum = '';
parts.forEach(part => {
accum += '/' + part;
bc.innerHTML += ` / <span class="crumb" data-path="${accum}">${part}</span>`;
});
bc.querySelectorAll('.crumb').forEach(crumb => {
crumb.addEventListener('click', () => loadFileTree(crumb.dataset.path));
});
}
async function showFileContent(filePath) {
try {
const res = await fetch(`${apiBase}/api/files/read?path=${encodeURIComponent(filePath)}`);
const data = await res.json();
alert(`内容预览:\n${data.content.substring(0, 1000)}...`);
} catch(e) { showToast('读取失败'); }
}
// ==================== 记忆搜索 ====================
document.getElementById('memory-btn').addEventListener('click', () => {
document.getElementById('memory-modal').style.display = 'flex';
});
document.getElementById('close-memory').addEventListener('click', () => {
document.getElementById('memory-modal').style.display = 'none';
});
document.getElementById('search-memory-btn').addEventListener('click', async () => {
const query = document.getElementById('memory-query').value.trim();
if (!query) return;
const res = await fetch(`${apiBase}/api/memory/search`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ query, topK: 5 })
});
const data = await res.json();
const container = document.getElementById('memory-results');
container.innerHTML = data.results?.map(r =>
`<div style="padding:8px; border-bottom:1px solid var(--border-light);">
<strong>${r.content?.substring(0,50)}</strong><br>
<small>相似度: ${(r.score*100).toFixed(1)}% | ${new Date(r.timestamp).toLocaleString()}</small>
</div>`
).join('') || '无结果';
});
// ==================== 聊天核心 ====================
const input = document.getElementById('user-input');
const sendBtn = document.getElementById('send-btn');
input.addEventListener('input', () => {
sendBtn.disabled = input.value.trim().length === 0 || isProcessing;
autoResize(input);
});
function autoResize(el) {
el.style.height = 'auto';
el.style.height = Math.min(el.scrollHeight, 120) + 'px';
}
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!sendBtn.disabled) sendMessage();
}
});
sendBtn.addEventListener('click', sendMessage);
async function sendMessage() {
const content = input.value.trim();
if (!content || isProcessing) return;
isProcessing = true;
sendBtn.disabled = true;
input.value = '';
autoResize(input);
removeWelcome();
addMessage('user', content);
const typing = addTypingMessage();
try {
const assistantContent = await callChatAPI(content);
removeTypingMessage(typing);
addMessage('assistant', assistantContent);
} catch(e) {
removeTypingMessage(typing);
addMessage('assistant', `❌ 错误:${e.message}`);
} finally {
isProcessing = false;
sendBtn.disabled = false;
input.focus();
}
}
async function callChatAPI(message, retries = 3) {
let lastError;
for (let i = 0; i < retries; i++) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 60000);
const res = await fetch(`${apiBase}/api/chat`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ message, model: selectedModel, stream: true }),
signal: controller.signal
});
clearTimeout(timeout);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let result = '';
let lastActivity = Date.now();
while (true) {
const {done, value} = await reader.read();
if (done) break;
const chunk = decoder.decode(value, {stream: true});
// 过滤 SSE 心跳注释
const lines = chunk.split('\n').filter(l => l.trim() !== '' && !l.startsWith(':'));
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') break;
try {
const parsed = JSON.parse(data);
if (parsed.content) result += parsed.content;
} catch {}
}
}
lastActivity = Date.now();
// 更新打字效果
updateTypingMessage(result);
// 超时检测(无数据60秒断开)
if (Date.now() - lastActivity > 60000) throw new Error('流超时');
}
return result;
} catch(e) {
lastError = e;
if (i < retries - 1) await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)));
}
}
throw lastError;
}
function addMessage(role, content) {
const main = document.getElementById('chat-container');
const row = document.createElement('div');
row.className = `message-row ${role}`;
const bubble = document.createElement('div');
bubble.className = 'message-bubble';
// 简单 Markdown 处理(代码块)
if (content.includes('