v1.0.4修复优化

This commit is contained in:
2026-05-06 17:25:06 +08:00
parent dec5f8c4d4
commit 2edf393b15
9 changed files with 717 additions and 586 deletions

View File

@@ -31,15 +31,15 @@
<input type="checkbox" id="thinkingMode">
<span class="slider"></span>
</label>
<span style="font-size:12px;color:var(--text-secondary)">思考</span>
<span class="toolbar-think-label">思考</span>
<select id="personalitySelect">
<option value="">默认人格</option>
<!-- loadPersonalities() 动态填充 -->
</select>
<a href="/config.php" class="btn btn-secondary btn-sm" style="margin-left:auto;">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><circle cx="12" cy="12" r="3"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
<a href="/config.php" class="btn btn-secondary btn-sm settings-link">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon-inline"><circle cx="12" cy="12" r="3"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>
设置
</a>
</div>
@@ -56,7 +56,7 @@
<div class="input-area">
<div class="file-preview" id="filePreview"></div>
<div class="input-wrapper">
<button id="uploadBtn" title="上传文件" style="background:none;border:none;color:var(--text-secondary);cursor:pointer;padding:4px;">
<button id="uploadBtn" title="上传文件" class="upload-btn">
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/></svg>
</button>
<textarea id="messageInput" rows="1" placeholder="输入消息Ctrl+Enter 发送..."></textarea>
@@ -65,107 +65,3 @@
</div>
</div>
</div>
<script>
// 切换侧边栏
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('collapsed');
}
// 供应商/模型数据缓存
let providersData = [];
let personalitiesData = [];
// 加载供应商配置
async function loadProviders() {
try {
const res = await api.get('/config');
providersData = res.data.providers || [];
const select = document.getElementById('providerSelect');
select.innerHTML = '<option value="">选择供应商</option>';
providersData.forEach((p, i) => {
if (p.enabled) {
const option = document.createElement('option');
option.value = i;
option.textContent = p.name;
select.appendChild(option);
}
});
// 如果只有一个供应商,自动选择
if (providersData.filter(p => p.enabled).length === 1) {
select.value = providersData.findIndex(p => p.enabled);
onProviderChange();
}
} catch (err) {
console.error('加载供应商配置失败:', err);
}
}
// 供应商切换时更新模型列表
function onProviderChange() {
const index = document.getElementById('providerSelect').value;
const modelSelect = document.getElementById('modelSelect');
modelSelect.innerHTML = '<option value="">选择模型</option>';
if (index !== '' && providersData[index]) {
const provider = providersData[index];
(provider.models || []).forEach(m => {
const option = document.createElement('option');
option.value = m;
option.textContent = m;
modelSelect.appendChild(option);
});
// 如果只有一个模型,自动选择
if (provider.models && provider.models.length === 1) {
modelSelect.value = provider.models[0];
}
// 如果有默认模型,自动选择
if (provider.defaultModel) {
modelSelect.value = provider.defaultModel;
}
}
}
// 加载人格列表
async function loadPersonalities() {
try {
const res = await api.get('/personalities');
personalitiesData = res.data || [];
const select = document.getElementById('personalitySelect');
select.innerHTML = '<option value="">默认人格</option>';
personalitiesData.forEach(p => {
const option = document.createElement('option');
option.value = p.id;
option.textContent = (p.icon ? p.icon + ' ' : '') + p.name;
select.appendChild(option);
});
} catch (err) {
console.error('加载人格列表失败:', err);
}
}
// 页面初始化
(async function() {
// 检查认证
const token = Storage.getToken();
if (!token) {
window.location.href = '/login.php';
return;
}
// 初始化聊天管理器
ChatManager.init();
// 加载数据
await Promise.all([
loadProviders(),
loadPersonalities(),
SessionManager.loadSessions()
]);
// 如果有会话,自动选择第一个
if (SessionManager.sessions.length > 0) {
await SessionManager.switchSession(SessionManager.sessions[0].id);
}
})();
</script>

View File

@@ -1,11 +1,11 @@
<div class="config-container">
<div class="config-header">
<h1>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-4px;margin-right:8px;"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
<svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon-inline-md"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/></svg>
系统配置
</h1>
<a href="/chat.php" class="btn btn-secondary">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-2px;margin-right:4px;"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon-inline"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
返回聊天
</a>
</div>
@@ -16,7 +16,7 @@
<div id="providerList">
<!-- JS 动态渲染 -->
</div>
<button class="btn btn-secondary" onclick="ConfigPage.addProvider()" style="margin-top:12px;">+ 添加供应商</button>
<button class="btn btn-secondary config-add-btn" onclick="ConfigPage.addProvider()">+ 添加供应商</button>
</div>
<!-- 人格管理 -->
@@ -25,7 +25,7 @@
<div id="personalityList">
<!-- JS 动态渲染 -->
</div>
<h3 style="margin-top:20px;">添加自定义人格</h3>
<h3>添加自定义人格</h3>
<div class="form-group">
<label>名称</label>
<input type="text" id="newPersonalityName" placeholder="人格名称">
@@ -48,208 +48,4 @@
<div id="configMessage"></div>
<script>
const ConfigPage = {
providers: [],
personalities: [],
async init() {
// 检查认证和管理员权限
const token = Storage.getToken();
if (!token) {
window.location.href = '/login.php';
return;
}
try {
// 验证管理员权限
const userRes = await api.get('/auth/me');
if (userRes.data.role !== 'admin') {
window.location.href = '/chat.php';
return;
}
} catch (err) {
window.location.href = '/login.php';
return;
}
await this.loadProviders();
await this.loadPersonalities();
},
async loadProviders() {
try {
const res = await api.get('/config');
this.providers = res.data.providers || [];
this.renderProviders();
} catch (err) {
this.showMessage('加载供应商配置失败: ' + err.message, 'error');
}
},
renderProviders() {
const list = document.getElementById('providerList');
if (this.providers.length === 0) {
list.innerHTML = '<p style="color:var(--text-secondary)">暂无供应商配置</p>';
return;
}
list.innerHTML = this.providers.map((p, i) => `
<div class="provider-item" style="background:var(--bg-secondary);padding:16px;border-radius:var(--radius);margin-bottom:12px;">
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
<strong>${this.escapeHtml(p.name)}</strong>
<div>
<label class="toggle-switch">
<input type="checkbox" ${p.enabled ? 'checked' : ''} onchange="ConfigPage.toggleProvider(${i}, this.checked)">
<span class="slider"></span>
</label>
<button class="btn btn-danger btn-sm" onclick="ConfigPage.deleteProvider(${i})" style="margin-left:8px;">删除</button>
</div>
</div>
<div class="form-group">
<label>API URL</label>
<input type="text" value="${this.escapeHtml(p.apiUrl || '')}" onchange="ConfigPage.updateProvider(${i}, 'apiUrl', this.value)">
</div>
<div class="form-group">
<label>API Key</label>
<input type="password" value="${this.escapeHtml(p.apiKey || '')}" onchange="ConfigPage.updateProvider(${i}, 'apiKey', this.value)" placeholder="API 密钥">
</div>
<div class="form-group">
<label>可用模型(逗号分隔)</label>
<input type="text" value="${this.escapeHtml((p.models || []).join(', '))}" onchange="ConfigPage.updateProviderModels(${i}, this.value)">
</div>
<div class="form-group">
<label>供应商类型</label>
<select onchange="ConfigPage.updateProvider(${i}, 'type', this.value)">
<option value="newapi" ${p.type === 'newapi' ? 'selected' : ''}>OpenAI 兼容</option>
<option value="openai" ${p.type === 'openai' ? 'selected' : ''}>OpenAI 官方</option>
<option value="claude" ${p.type === 'claude' ? 'selected' : ''}>Claude (Anthropic)</option>
</select>
</div>
</div>
`).join('');
},
addProvider() {
this.providers.push({
name: '新供应商',
apiUrl: '',
apiKey: '',
models: [],
type: 'newapi',
enabled: true
});
this.renderProviders();
this.saveProviders();
},
updateProvider(index, field, value) {
this.providers[index][field] = value;
this.saveProviders();
},
updateProviderModels(index, value) {
this.providers[index].models = value.split(',').map(m => m.trim()).filter(m => m);
this.saveProviders();
},
toggleProvider(index, enabled) {
this.providers[index].enabled = enabled;
this.saveProviders();
},
deleteProvider(index) {
if (!confirm('确定要删除供应商 "' + this.providers[index].name + '" 吗?')) return;
this.providers.splice(index, 1);
this.renderProviders();
this.saveProviders();
},
async saveProviders() {
try {
await api.put('/config', { providers: this.providers });
this.showMessage('供应商配置已保存', 'success');
} catch (err) {
this.showMessage('保存失败: ' + err.message, 'error');
}
},
async loadPersonalities() {
try {
const res = await api.get('/personalities');
this.personalities = res.data || [];
this.renderPersonalities();
} catch (err) {
this.showMessage('加载人格列表失败: ' + err.message, 'error');
}
},
renderPersonalities() {
const list = document.getElementById('personalityList');
if (this.personalities.length === 0) {
list.innerHTML = '<p style="color:var(--text-secondary)">暂无人格</p>';
return;
}
list.innerHTML = this.personalities.map(p => `
<div style="display:flex;justify-content:space-between;align-items:center;padding:12px;background:var(--bg-secondary);border-radius:var(--radius);margin-bottom:8px;">
<div>
<span>${p.icon ? '<span style="margin-right:4px;">' + this.escapeHtml(p.icon) + '</span>' : ''}${this.escapeHtml(p.name)}</span>
${p.is_preset ? '<span style="color:var(--warning);font-size:12px;margin-left:8px;">预设</span>' : '<span style="color:var(--success);font-size:12px;margin-left:8px;">自定义</span>'}
</div>
${!p.is_preset ? '<button class="btn btn-danger btn-sm" onclick="ConfigPage.deletePersonality(' + p.id + ')">删除</button>' : ''}
</div>
`).join('');
},
async createPersonality() {
const name = document.getElementById('newPersonalityName').value.trim();
const prompt = document.getElementById('newPersonalityPrompt').value.trim();
const icon = document.getElementById('newPersonalityIcon').value.trim();
const description = document.getElementById('newPersonalityDesc').value.trim();
if (!name || !prompt) {
this.showMessage('名称和提示词不能为空', 'error');
return;
}
try {
await api.post('/personalities', { name, prompt, icon, description });
this.showMessage('人格创建成功', 'success');
// 清空表单
document.getElementById('newPersonalityName').value = '';
document.getElementById('newPersonalityPrompt').value = '';
document.getElementById('newPersonalityIcon').value = '';
document.getElementById('newPersonalityDesc').value = '';
await this.loadPersonalities();
} catch (err) {
this.showMessage('创建失败: ' + err.message, 'error');
}
},
async deletePersonality(id) {
if (!confirm('确定要删除这个人格吗?')) return;
try {
await api.delete('/personalities/' + id);
this.showMessage('人格已删除', 'success');
await this.loadPersonalities();
} catch (err) {
this.showMessage('删除失败: ' + err.message, 'error');
}
},
showMessage(text, type) {
const el = document.getElementById('configMessage');
el.innerHTML = `<div class="alert alert-${type === 'error' ? 'error' : 'success'}" style="position:fixed;bottom:20px;right:20px;z-index:1000;min-width:200px;">${this.escapeHtml(text)}</div>`;
setTimeout(() => { el.innerHTML = ''; }, 3000);
},
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
};
ConfigPage.init();
</script>
<script src="/assets/js/config.js"></script>

View File

@@ -10,7 +10,7 @@
<h1>AI Chat</h1>
<p class="login-subtitle">登录你的 AI 对话平台</p>
</div>
<div id="loginError" class="alert alert-error" style="display:none;"></div>
<div id="loginError" class="alert alert-error hidden"></div>
<form id="loginForm">
<div class="form-group">
<label for="username">用户名</label>
@@ -20,59 +20,8 @@
<label for="password">密码</label>
<input type="password" id="password" name="password" required autocomplete="current-password" placeholder="请输入密码">
</div>
<button type="submit" class="btn btn-primary btn-block" id="loginBtn" style="margin-top:8px;">登录</button>
<button type="submit" class="btn btn-primary btn-block" id="loginBtn">登录</button>
</form>
</div>
</div>
<script>
// 页面加载时检查是否已登录
(function() {
const token = localStorage.getItem('token');
if (token) {
window.location.href = '/chat.php';
}
})();
// 登录表单提交
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
const btn = document.getElementById('loginBtn');
const errorEl = document.getElementById('loginError');
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
if (!username || !password) {
errorEl.textContent = '请输入用户名和密码';
errorEl.style.display = 'block';
return;
}
btn.disabled = true;
btn.textContent = '登录中...';
errorEl.style.display = 'none';
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.success) {
localStorage.setItem('token', data.data.token);
window.location.href = '/chat.php';
} else {
errorEl.textContent = data.message || '登录失败';
errorEl.style.display = 'block';
}
} catch (err) {
errorEl.textContent = '网络错误,请稍后重试';
errorEl.style.display = 'block';
} finally {
btn.disabled = false;
btn.textContent = '登录';
}
});
</script>
<script src="/assets/js/login.js"></script>

View File

@@ -649,3 +649,125 @@ body {
font-size: 22px;
}
}
/* ========================================
工具类
======================================== */
.hidden { display: none !important; }
.ml-auto { margin-left: auto; }
.mt-sm { margin-top: 12px; }
.mt-md { margin-top: 16px; }
.mt-lg { margin-top: 24px; }
.full-width { width: 100%; }
.text-muted { color: var(--text-secondary); }
.text-xs { font-size: 12px; }
.text-center { text-align: center; }
.col-flex-2 { flex: 2; }
.col-flex-1 { flex: 1; }
/* 内联 SVG 图标对齐 */
.icon-inline {
vertical-align: -2px;
margin-right: 4px;
}
.icon-inline-md {
vertical-align: -4px;
margin-right: 8px;
}
/* ========================================
聊天页工具栏组件
======================================== */
.toolbar-think-label {
font-size: 12px;
color: var(--text-secondary);
}
.upload-btn {
background: none;
border: none;
color: var(--text-secondary);
cursor: pointer;
padding: 4px;
}
.settings-link {
margin-left: auto;
}
/* ========================================
配置页组件
======================================== */
.config-add-btn {
margin-top: 12px;
}
.config-section h3 {
margin-top: 20px;
margin-bottom: 16px;
font-size: 15px;
font-weight: 600;
}
.config-empty {
color: var(--text-secondary);
}
.config-provider-card {
background: var(--bg-secondary);
padding: 16px;
border-radius: var(--radius);
margin-bottom: 12px;
}
.config-provider-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
}
.config-provider-header strong {
font-size: 15px;
}
.config-provider-header .toggle-switch {
margin-right: 8px;
}
.personality-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px 16px;
background: var(--bg-secondary);
border-radius: var(--radius);
margin-bottom: 8px;
}
.personality-icon {
margin-right: 4px;
}
.personality-badge {
font-size: 12px;
margin-left: 8px;
}
.personality-badge.preset {
color: var(--warning);
}
.personality-badge.custom {
color: var(--success);
}
/* 固定定位消息提示(配置页用) */
.toast-message {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
min-width: 200px;
}

View File

@@ -306,3 +306,109 @@ const ChatManager = {
return div.innerHTML;
}
};
// ========================================
// 聊天页面初始化
// ========================================
// 切换侧边栏
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('collapsed');
}
// 供应商/模型数据缓存
let providersData = [];
let personalitiesData = [];
// 加载供应商配置
async function loadProviders() {
try {
const res = await api.get('/config');
providersData = res.data.providers || [];
const select = document.getElementById('providerSelect');
select.innerHTML = '<option value="">选择供应商</option>';
providersData.forEach((p, i) => {
if (p.enabled) {
const option = document.createElement('option');
option.value = i;
option.textContent = p.name;
select.appendChild(option);
}
});
// 如果只有一个供应商,自动选择
if (providersData.filter(p => p.enabled).length === 1) {
select.value = providersData.findIndex(p => p.enabled);
onProviderChange();
}
} catch (err) {
console.error('加载供应商配置失败:', err);
}
}
// 供应商切换时更新模型列表
function onProviderChange() {
const index = document.getElementById('providerSelect').value;
const modelSelect = document.getElementById('modelSelect');
modelSelect.innerHTML = '<option value="">选择模型</option>';
if (index !== '' && providersData[index]) {
const provider = providersData[index];
(provider.models || []).forEach(m => {
const option = document.createElement('option');
option.value = m;
option.textContent = m;
modelSelect.appendChild(option);
});
// 如果只有一个模型,自动选择
if (provider.models && provider.models.length === 1) {
modelSelect.value = provider.models[0];
}
// 如果有默认模型,自动选择
if (provider.defaultModel) {
modelSelect.value = provider.defaultModel;
}
}
}
// 加载人格列表
async function loadPersonalities() {
try {
const res = await api.get('/personalities');
personalitiesData = res.data || [];
const select = document.getElementById('personalitySelect');
select.innerHTML = '<option value="">默认人格</option>';
personalitiesData.forEach(p => {
const option = document.createElement('option');
option.value = p.id;
option.textContent = (p.icon ? p.icon + ' ' : '') + p.name;
select.appendChild(option);
});
} catch (err) {
console.error('加载人格列表失败:', err);
}
}
// 页面初始化
(async function() {
// 检查认证
const token = Storage.getToken();
if (!token) {
window.location.href = '/login.php';
return;
}
// 初始化聊天管理器
ChatManager.init();
// 加载数据
await Promise.all([
loadProviders(),
loadPersonalities(),
SessionManager.loadSessions()
]);
// 如果有会话,自动选择第一个
if (SessionManager.sessions.length > 0) {
await SessionManager.switchSession(SessionManager.sessions[0].id);
}
})();

203
assets/js/config.js Normal file
View File

@@ -0,0 +1,203 @@
const ConfigPage = {
providers: [],
personalities: [],
async init() {
// 检查认证和管理员权限
const token = Storage.getToken();
if (!token) {
window.location.href = '/login.php';
return;
}
try {
// 验证管理员权限
const userRes = await api.get('/auth/me');
if (userRes.data.role !== 'admin') {
window.location.href = '/chat.php';
return;
}
} catch (err) {
window.location.href = '/login.php';
return;
}
await this.loadProviders();
await this.loadPersonalities();
},
async loadProviders() {
try {
const res = await api.get('/config');
this.providers = res.data.providers || [];
this.renderProviders();
} catch (err) {
this.showMessage('加载供应商配置失败: ' + err.message, 'error');
}
},
renderProviders() {
const list = document.getElementById('providerList');
if (this.providers.length === 0) {
list.innerHTML = '<p class="config-empty">暂无供应商配置</p>';
return;
}
list.innerHTML = this.providers.map((p, i) => `
<div class="config-provider-card">
<div class="config-provider-header">
<strong>${this.escapeHtml(p.name)}</strong>
<div>
<label class="toggle-switch">
<input type="checkbox" ${p.enabled ? 'checked' : ''} onchange="ConfigPage.toggleProvider(${i}, this.checked)">
<span class="slider"></span>
</label>
<button class="btn btn-danger btn-sm" onclick="ConfigPage.deleteProvider(${i})">删除</button>
</div>
</div>
<div class="form-group">
<label>API URL</label>
<input type="text" value="${this.escapeHtml(p.apiUrl || '')}" onchange="ConfigPage.updateProvider(${i}, 'apiUrl', this.value)">
</div>
<div class="form-group">
<label>API Key</label>
<input type="password" value="${this.escapeHtml(p.apiKey || '')}" onchange="ConfigPage.updateProvider(${i}, 'apiKey', this.value)" placeholder="API 密钥">
</div>
<div class="form-group">
<label>可用模型(逗号分隔)</label>
<input type="text" value="${this.escapeHtml((p.models || []).join(', '))}" onchange="ConfigPage.updateProviderModels(${i}, this.value)">
</div>
<div class="form-group">
<label>供应商类型</label>
<select onchange="ConfigPage.updateProvider(${i}, 'type', this.value)">
<option value="newapi" ${p.type === 'newapi' ? 'selected' : ''}>OpenAI 兼容</option>
<option value="openai" ${p.type === 'openai' ? 'selected' : ''}>OpenAI 官方</option>
<option value="claude" ${p.type === 'claude' ? 'selected' : ''}>Claude (Anthropic)</option>
</select>
</div>
</div>
`).join('');
},
addProvider() {
this.providers.push({
name: '新供应商',
apiUrl: '',
apiKey: '',
models: [],
type: 'newapi',
enabled: true
});
this.renderProviders();
this.saveProviders();
},
updateProvider(index, field, value) {
this.providers[index][field] = value;
this.saveProviders();
},
updateProviderModels(index, value) {
this.providers[index].models = value.split(',').map(m => m.trim()).filter(m => m);
this.saveProviders();
},
toggleProvider(index, enabled) {
this.providers[index].enabled = enabled;
this.saveProviders();
},
deleteProvider(index) {
if (!confirm('确定要删除供应商 "' + this.providers[index].name + '" 吗?')) return;
this.providers.splice(index, 1);
this.renderProviders();
this.saveProviders();
},
async saveProviders() {
try {
await api.put('/config', { providers: this.providers });
this.showMessage('供应商配置已保存', 'success');
} catch (err) {
this.showMessage('保存失败: ' + err.message, 'error');
}
},
async loadPersonalities() {
try {
const res = await api.get('/personalities');
this.personalities = res.data || [];
this.renderPersonalities();
} catch (err) {
this.showMessage('加载人格列表失败: ' + err.message, 'error');
}
},
renderPersonalities() {
const list = document.getElementById('personalityList');
if (this.personalities.length === 0) {
list.innerHTML = '<p class="config-empty">暂无人格</p>';
return;
}
list.innerHTML = this.personalities.map(p => `
<div class="personality-item">
<div>
<span>${p.icon ? '<span class="personality-icon">' + this.escapeHtml(p.icon) + '</span>' : ''}${this.escapeHtml(p.name)}</span>
${p.is_preset ? '<span class="personality-badge preset">预设</span>' : '<span class="personality-badge custom">自定义</span>'}
</div>
${!p.is_preset ? '<button class="btn btn-danger btn-sm" onclick="ConfigPage.deletePersonality(' + p.id + ')">删除</button>' : ''}
</div>
`).join('');
},
async createPersonality() {
const name = document.getElementById('newPersonalityName').value.trim();
const prompt = document.getElementById('newPersonalityPrompt').value.trim();
const icon = document.getElementById('newPersonalityIcon').value.trim();
const description = document.getElementById('newPersonalityDesc').value.trim();
if (!name || !prompt) {
this.showMessage('名称和提示词不能为空', 'error');
return;
}
try {
await api.post('/personalities', { name, prompt, icon, description });
this.showMessage('人格创建成功', 'success');
// 清空表单
document.getElementById('newPersonalityName').value = '';
document.getElementById('newPersonalityPrompt').value = '';
document.getElementById('newPersonalityIcon').value = '';
document.getElementById('newPersonalityDesc').value = '';
await this.loadPersonalities();
} catch (err) {
this.showMessage('创建失败: ' + err.message, 'error');
}
},
async deletePersonality(id) {
if (!confirm('确定要删除这个人格吗?')) return;
try {
await api.delete('/personalities/' + id);
this.showMessage('人格已删除', 'success');
await this.loadPersonalities();
} catch (err) {
this.showMessage('删除失败: ' + err.message, 'error');
}
},
showMessage(text, type) {
const el = document.getElementById('configMessage');
el.innerHTML = `<div class="alert alert-${type === 'error' ? 'error' : 'success'} toast-message">${this.escapeHtml(text)}</div>`;
setTimeout(() => { el.innerHTML = ''; }, 3000);
},
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
};
ConfigPage.init();

201
assets/js/install.js Normal file
View File

@@ -0,0 +1,201 @@
const InstallWizard = {
currentStep: 1,
totalSteps: 5,
init() {
this.checkEnv();
this.addProvider(); // 默认添加一个供应商表单
},
checkEnv() {
const checks = document.getElementById('envCheckData');
if (!checks) return;
const data = JSON.parse(checks.textContent);
const container = document.getElementById('envChecks');
container.innerHTML = data.map(c => `
<div class="check-item ${c.pass ? 'pass' : 'fail'}">
<span class="check-name">${c.name}</span>
<span class="check-status">
${c.pass
? '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> 通过'
: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg> 未通过'
}
</span>
</div>
`).join('');
},
nextStep() {
if (this.currentStep === 4) {
// 验证管理员密码
const pwd = document.getElementById('adminPassword').value;
const confirm = document.getElementById('adminPasswordConfirm').value;
const username = document.getElementById('adminUsername').value;
if (!username) { alert('请输入管理员用户名'); return; }
if (pwd.length < 6) { alert('密码至少6位'); return; }
if (pwd !== confirm) { alert('两次密码不一致'); return; }
}
if (this.currentStep < this.totalSteps) {
this.currentStep++;
this.updateSteps();
}
},
prevStep() {
if (this.currentStep > 1) {
this.currentStep--;
this.updateSteps();
}
},
updateSteps() {
document.querySelectorAll('.step-content').forEach((el, i) => {
el.classList.toggle('active', i + 1 === this.currentStep);
});
document.querySelectorAll('.step-indicator .step').forEach((el, i) => {
el.classList.remove('active', 'completed');
if (i + 1 === this.currentStep) el.classList.add('active');
if (i + 1 < this.currentStep) el.classList.add('completed');
});
},
async testDb() {
const result = document.getElementById('dbTestResult');
try {
const response = await fetch('/api/install/test-db', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
host: document.getElementById('dbHost').value,
port: parseInt(document.getElementById('dbPort').value),
user: document.getElementById('dbUser').value,
password: document.getElementById('dbPassword').value,
database: document.getElementById('dbName').value
})
});
const data = await response.json();
result.innerHTML = `<div class="alert ${data.success ? 'alert-success' : 'alert-error'}">${data.message}</div>`;
} catch (err) {
result.innerHTML = '<div class="alert alert-error">连接失败: ' + err.message + '</div>';
}
},
addProvider() {
const list = document.getElementById('providerList');
const index = list.children.length;
const html = `
<div class="provider-item" data-index="${index}">
<div class="provider-item-header">
<span class="provider-item-title">供应商 #${index + 1}</span>
${index > 0 ? '<button class="btn btn-danger btn-sm" onclick="this.closest(\'.provider-item\').remove()">删除</button>' : ''}
</div>
<div class="form-row">
<div class="form-group col-flex-1">
<label>供应商名称</label>
<input type="text" class="provider-name" placeholder="如OpenAI、DeepSeek">
</div>
<div class="form-group col-flex-1">
<label>供应商类型</label>
<select class="provider-type">
<option value="newapi">OpenAI 兼容</option>
<option value="openai">OpenAI 官方</option>
<option value="claude">Claude (Anthropic)</option>
</select>
</div>
</div>
<div class="form-group">
<label>API URL</label>
<input type="text" class="provider-url" placeholder="如https://api.openai.com">
</div>
<div class="form-group">
<label>API Key</label>
<input type="password" class="provider-key" placeholder="API 密钥">
</div>
<div class="form-group">
<label>可用模型(逗号分隔)</label>
<input type="text" class="provider-models" placeholder="如gpt-3.5-turbo, gpt-4">
</div>
</div>
`;
list.insertAdjacentHTML('beforeend', html);
},
generateSecret() {
const chars = '0123456789abcdef';
let result = '';
for (let i = 0; i < 64; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
},
async runInstall() {
const btn = document.getElementById('installBtn');
const result = document.getElementById('installResult');
// 收集供应商数据
const providers = [];
document.querySelectorAll('.provider-item').forEach(item => {
const models = item.querySelector('.provider-models').value.split(',').map(m => m.trim()).filter(m => m);
providers.push({
name: item.querySelector('.provider-name').value,
apiUrl: item.querySelector('.provider-url').value,
apiKey: item.querySelector('.provider-key').value,
models: models,
type: item.querySelector('.provider-type').value,
enabled: true
});
});
if (providers.length === 0 || !providers[0].name || !providers[0].apiKey) {
alert('请至少配置一个完整的供应商');
return;
}
btn.disabled = true;
btn.textContent = '安装中...';
const setupData = {
username: document.getElementById('adminUsername').value,
password: document.getElementById('adminPassword').value,
dbConfig: {
host: document.getElementById('dbHost').value,
port: parseInt(document.getElementById('dbPort').value),
user: document.getElementById('dbUser').value,
password: document.getElementById('dbPassword').value,
database: document.getElementById('dbName').value
},
appConfig: {
jwtSecret: document.getElementById('jwtSecret').value || undefined,
jwtExpiry: parseInt(document.getElementById('jwtExpiry').value) || 86400
},
providers: providers
};
try {
const response = await fetch('/api/install/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(setupData)
});
const data = await response.json();
if (data.success) {
result.innerHTML = '<div class="alert alert-success">安装成功!正在跳转到登录页...</div>';
setTimeout(() => { window.location.href = '/login.php'; }, 2000);
} else {
result.innerHTML = '<div class="alert alert-error">安装失败: ' + data.message + '</div>';
btn.disabled = false;
btn.textContent = '完成安装';
}
} catch (err) {
result.innerHTML = '<div class="alert alert-error">安装失败: ' + err.message + '</div>';
btn.disabled = false;
btn.textContent = '完成安装';
}
}
};
InstallWizard.init();

50
assets/js/login.js Normal file
View File

@@ -0,0 +1,50 @@
// 页面加载时检查是否已登录
(function() {
const token = localStorage.getItem('token');
if (token) {
window.location.href = '/chat.php';
}
})();
// 登录表单提交
document.getElementById('loginForm').addEventListener('submit', async function(e) {
e.preventDefault();
const btn = document.getElementById('loginBtn');
const errorEl = document.getElementById('loginError');
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
if (!username || !password) {
errorEl.textContent = '请输入用户名和密码';
errorEl.classList.remove('hidden');
return;
}
btn.disabled = true;
btn.textContent = '登录中...';
errorEl.classList.add('hidden');
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (data.success) {
localStorage.setItem('token', data.data.token);
window.location.href = '/chat.php';
} else {
errorEl.textContent = data.message || '登录失败';
errorEl.classList.remove('hidden');
}
} catch (err) {
errorEl.textContent = '网络错误,请稍后重试';
errorEl.classList.remove('hidden');
} finally {
btn.disabled = false;
btn.textContent = '登录';
}
});

View File

@@ -5,6 +5,15 @@ if (file_exists($configFile)) {
header('Location: /login.php');
exit;
}
// 环境检查数据JSON 格式供 JS 使用)
$envChecks = json_encode([
['name' => 'PHP 版本 >= 8.0', 'pass' => version_compare(PHP_VERSION, '8.0.0', '>=')],
['name' => 'PDO 扩展', 'pass' => extension_loaded('pdo')],
['name' => 'cURL 扩展', 'pass' => extension_loaded('curl')],
['name' => 'uploads/ 目录可写', 'pass' => is_writable(__DIR__ . '/../uploads')],
['name' => 'config/ 目录可写', 'pass' => is_writable(__DIR__ . '/../config')],
]);
?>
<!DOCTYPE html>
<html lang="zh-CN">
@@ -15,6 +24,9 @@ if (file_exists($configFile)) {
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body>
<!-- 环境检查数据 -->
<script id="envCheckData" type="application/json"><?php echo $envChecks; ?></script>
<div class="install-container">
<!-- 标题区域 -->
<div class="install-header">
@@ -75,11 +87,11 @@ if (file_exists($configFile)) {
<p class="step-desc">填写 MySQL 数据库连接信息</p>
</div>
<div class="form-row">
<div class="form-group" style="flex:2">
<div class="form-group col-flex-2">
<label>主机地址</label>
<input type="text" id="dbHost" value="127.0.0.1" placeholder="数据库主机">
</div>
<div class="form-group" style="flex:1">
<div class="form-group col-flex-1">
<label>端口</label>
<input type="number" id="dbPort" value="3306" placeholder="端口号">
</div>
@@ -89,11 +101,11 @@ if (file_exists($configFile)) {
<input type="text" id="dbName" placeholder="数据库名称">
</div>
<div class="form-row">
<div class="form-group" style="flex:1">
<div class="form-group col-flex-1">
<label>用户名</label>
<input type="text" id="dbUser" placeholder="数据库用户名">
</div>
<div class="form-group" style="flex:1">
<div class="form-group col-flex-1">
<label>密码</label>
<input type="password" id="dbPassword" placeholder="数据库密码">
</div>
@@ -102,7 +114,7 @@ if (file_exists($configFile)) {
<div class="btn-group">
<button class="btn btn-secondary" onclick="InstallWizard.prevStep()">上一步</button>
<button class="btn btn-outline" onclick="InstallWizard.testDb()">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:4px;"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon-inline"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
测试连接
</button>
<button class="btn btn-primary" onclick="InstallWizard.nextStep()">下一步</button>
@@ -144,11 +156,11 @@ if (file_exists($configFile)) {
<input type="text" id="adminUsername" placeholder="管理员用户名">
</div>
<div class="form-row">
<div class="form-group" style="flex:1">
<div class="form-group col-flex-1">
<label>密码</label>
<input type="password" id="adminPassword" placeholder="至少6位密码">
</div>
<div class="form-group" style="flex:1">
<div class="form-group col-flex-1">
<label>确认密码</label>
<input type="password" id="adminPasswordConfirm" placeholder="再次输入密码">
</div>
@@ -168,11 +180,11 @@ if (file_exists($configFile)) {
<div id="providerList">
<!-- 由 JS 动态管理 -->
</div>
<button class="btn btn-outline" onclick="InstallWizard.addProvider()" style="margin-top:12px;width:100%;">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="margin-right:4px;"><path d="M12 5v14M5 12h14"/></svg>
<button class="btn btn-outline full-width mt-sm" onclick="InstallWizard.addProvider()">
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" class="icon-inline"><path d="M12 5v14M5 12h14"/></svg>
添加供应商
</button>
<div id="installResult" style="margin-top:16px;"></div>
<div id="installResult" class="mt-md"></div>
<div class="btn-group">
<button class="btn btn-secondary" onclick="InstallWizard.prevStep()">上一步</button>
<button class="btn btn-primary btn-lg" id="installBtn" onclick="InstallWizard.runInstall()">完成安装</button>
@@ -185,210 +197,6 @@ if (file_exists($configFile)) {
</div>
</div>
<script>
const InstallWizard = {
currentStep: 1,
totalSteps: 5,
init() {
this.checkEnv();
this.addProvider(); // 默认添加一个供应商表单
},
checkEnv() {
const checks = [
{ name: 'PHP 版本 >= 8.0', pass: <?php echo version_compare(PHP_VERSION, '8.0.0', '>=') ? 'true' : 'false'; ?> },
{ name: 'PDO 扩展', pass: <?php echo extension_loaded('pdo') ? 'true' : 'false'; ?> },
{ name: 'cURL 扩展', pass: <?php echo extension_loaded('curl') ? 'true' : 'false'; ?> },
{ name: 'uploads/ 目录可写', pass: <?php echo is_writable(__DIR__ . '/../uploads') ? 'true' : 'false'; ?> },
{ name: 'config/ 目录可写', pass: <?php echo is_writable(__DIR__ . '/../config') ? 'true' : 'false'; ?> }
];
const container = document.getElementById('envChecks');
container.innerHTML = checks.map(c => `
<div class="check-item ${c.pass ? 'pass' : 'fail'}">
<span class="check-name">${c.name}</span>
<span class="check-status">
${c.pass
? '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg> 通过'
: '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg> 未通过'
}
</span>
</div>
`).join('');
},
nextStep() {
if (this.currentStep === 4) {
const pwd = document.getElementById('adminPassword').value;
const confirm = document.getElementById('adminPasswordConfirm').value;
const username = document.getElementById('adminUsername').value;
if (!username) { alert('请输入管理员用户名'); return; }
if (pwd.length < 6) { alert('密码至少6位'); return; }
if (pwd !== confirm) { alert('两次密码不一致'); return; }
}
if (this.currentStep < this.totalSteps) {
this.currentStep++;
this.updateSteps();
}
},
prevStep() {
if (this.currentStep > 1) {
this.currentStep--;
this.updateSteps();
}
},
updateSteps() {
document.querySelectorAll('.step-content').forEach((el, i) => {
el.classList.toggle('active', i + 1 === this.currentStep);
});
document.querySelectorAll('.step-indicator .step').forEach((el, i) => {
el.classList.remove('active', 'completed');
if (i + 1 === this.currentStep) el.classList.add('active');
if (i + 1 < this.currentStep) el.classList.add('completed');
});
},
async testDb() {
const result = document.getElementById('dbTestResult');
try {
const response = await fetch('/api/install/test-db', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
host: document.getElementById('dbHost').value,
port: parseInt(document.getElementById('dbPort').value),
user: document.getElementById('dbUser').value,
password: document.getElementById('dbPassword').value,
database: document.getElementById('dbName').value
})
});
const data = await response.json();
result.innerHTML = `<div class="alert ${data.success ? 'alert-success' : 'alert-error'}">${data.message}</div>`;
} catch (err) {
result.innerHTML = '<div class="alert alert-error">连接失败: ' + err.message + '</div>';
}
},
addProvider() {
const list = document.getElementById('providerList');
const index = list.children.length;
const html = `
<div class="provider-item" data-index="${index}">
<div class="provider-item-header">
<span class="provider-item-title">供应商 #${index + 1}</span>
${index > 0 ? '<button class="btn btn-danger btn-sm" onclick="this.closest(\'.provider-item\').remove()">删除</button>' : ''}
</div>
<div class="form-row">
<div class="form-group" style="flex:1">
<label>供应商名称</label>
<input type="text" class="provider-name" placeholder="如OpenAI、DeepSeek">
</div>
<div class="form-group" style="flex:1">
<label>供应商类型</label>
<select class="provider-type">
<option value="newapi">OpenAI 兼容</option>
<option value="openai">OpenAI 官方</option>
<option value="claude">Claude (Anthropic)</option>
</select>
</div>
</div>
<div class="form-group">
<label>API URL</label>
<input type="text" class="provider-url" placeholder="如https://api.openai.com">
</div>
<div class="form-group">
<label>API Key</label>
<input type="password" class="provider-key" placeholder="API 密钥">
</div>
<div class="form-group">
<label>可用模型(逗号分隔)</label>
<input type="text" class="provider-models" placeholder="如gpt-3.5-turbo, gpt-4">
</div>
</div>
`;
list.insertAdjacentHTML('beforeend', html);
},
generateSecret() {
const chars = '0123456789abcdef';
let result = '';
for (let i = 0; i < 64; i++) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
},
async runInstall() {
const btn = document.getElementById('installBtn');
const result = document.getElementById('installResult');
// 收集供应商数据
const providers = [];
document.querySelectorAll('.provider-item').forEach(item => {
const models = item.querySelector('.provider-models').value.split(',').map(m => m.trim()).filter(m => m);
providers.push({
name: item.querySelector('.provider-name').value,
apiUrl: item.querySelector('.provider-url').value,
apiKey: item.querySelector('.provider-key').value,
models: models,
type: item.querySelector('.provider-type').value,
enabled: true
});
});
if (providers.length === 0 || !providers[0].name || !providers[0].apiKey) {
alert('请至少配置一个完整的供应商');
return;
}
btn.disabled = true;
btn.textContent = '安装中...';
const setupData = {
username: document.getElementById('adminUsername').value,
password: document.getElementById('adminPassword').value,
dbConfig: {
host: document.getElementById('dbHost').value,
port: parseInt(document.getElementById('dbPort').value),
user: document.getElementById('dbUser').value,
password: document.getElementById('dbPassword').value,
database: document.getElementById('dbName').value
},
appConfig: {
jwtSecret: document.getElementById('jwtSecret').value || undefined,
jwtExpiry: parseInt(document.getElementById('jwtExpiry').value) || 86400
},
providers: providers
};
try {
const response = await fetch('/api/install/setup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(setupData)
});
const data = await response.json();
if (data.success) {
result.innerHTML = '<div class="alert alert-success">安装成功!正在跳转到登录页...</div>';
setTimeout(() => { window.location.href = '/login.php'; }, 2000);
} else {
result.innerHTML = '<div class="alert alert-error">安装失败: ' + data.message + '</div>';
btn.disabled = false;
btn.textContent = '完成安装';
}
} catch (err) {
result.innerHTML = '<div class="alert alert-error">安装失败: ' + err.message + '</div>';
btn.disabled = false;
btn.textContent = '完成安装';
}
}
};
InstallWizard.init();
</script>
<script src="/assets/js/install.js"></script>
</body>
</html>