初始化仓库及v1.0.0提交
This commit is contained in:
0
assets/js/.gitkeep
Normal file
0
assets/js/.gitkeep
Normal file
74
assets/js/api.js
Normal file
74
assets/js/api.js
Normal file
@@ -0,0 +1,74 @@
|
||||
const api = {
|
||||
async request(url, options = {}) {
|
||||
const token = Storage.getToken();
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { 'Authorization': 'Bearer ' + token } : {}),
|
||||
...options.headers
|
||||
};
|
||||
|
||||
const response = await fetch('/api' + url, {
|
||||
...options,
|
||||
headers
|
||||
});
|
||||
|
||||
// 401 自动跳转登录
|
||||
if (response.status === 401) {
|
||||
Storage.clearToken();
|
||||
window.location.href = '/login.php';
|
||||
throw new Error('请先登录');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '请求失败');
|
||||
}
|
||||
return data;
|
||||
},
|
||||
|
||||
get(url) {
|
||||
return this.request(url, { method: 'GET' });
|
||||
},
|
||||
|
||||
post(url, data) {
|
||||
return this.request(url, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
},
|
||||
|
||||
put(url, data) {
|
||||
return this.request(url, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
},
|
||||
|
||||
delete(url) {
|
||||
return this.request(url, { method: 'DELETE' });
|
||||
},
|
||||
|
||||
// 文件上传(不用 JSON Content-Type)
|
||||
async upload(url, formData) {
|
||||
const token = Storage.getToken();
|
||||
const headers = token ? { 'Authorization': 'Bearer ' + token } : {};
|
||||
|
||||
const response = await fetch('/api' + url, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: formData
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
Storage.clearToken();
|
||||
window.location.href = '/login.php';
|
||||
throw new Error('请先登录');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '上传失败');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
};
|
||||
308
assets/js/chat.js
Normal file
308
assets/js/chat.js
Normal file
@@ -0,0 +1,308 @@
|
||||
const ChatManager = {
|
||||
isStreaming: false,
|
||||
messages: [],
|
||||
|
||||
init() {
|
||||
const input = document.getElementById('messageInput');
|
||||
if (input) {
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter' && e.ctrlKey) {
|
||||
e.preventDefault();
|
||||
this.sendMessage();
|
||||
}
|
||||
});
|
||||
// 自适应高度
|
||||
input.addEventListener('input', () => {
|
||||
input.style.height = 'auto';
|
||||
input.style.height = Math.min(input.scrollHeight, 120) + 'px';
|
||||
});
|
||||
}
|
||||
|
||||
const sendBtn = document.getElementById('sendBtn');
|
||||
if (sendBtn) {
|
||||
sendBtn.addEventListener('click', () => this.sendMessage());
|
||||
}
|
||||
|
||||
UploadManager.init();
|
||||
},
|
||||
|
||||
async loadMessages(sessionId) {
|
||||
try {
|
||||
const res = await api.get('/sessions/' + sessionId + '/messages');
|
||||
this.messages = res.data || [];
|
||||
this.renderMessages();
|
||||
Storage.setCachedMessages(sessionId, this.messages);
|
||||
} catch (err) {
|
||||
// 尝试从缓存加载
|
||||
const cached = Storage.getCachedMessages(sessionId);
|
||||
if (cached) {
|
||||
this.messages = cached;
|
||||
this.renderMessages();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
renderMessages() {
|
||||
const container = document.getElementById('messagesContainer');
|
||||
if (!container) return;
|
||||
|
||||
if (this.messages.length === 0) {
|
||||
container.innerHTML = '<div class="empty-state"><h3>开始新的对话</h3><p>输入消息开始聊天</p></div>';
|
||||
return;
|
||||
}
|
||||
|
||||
container.innerHTML = this.messages.map(msg => {
|
||||
if (msg.role === 'user') {
|
||||
return `<div class="message user">${this.escapeHtml(msg.content)}</div>`;
|
||||
} else {
|
||||
let html = `<div class="message assistant">`;
|
||||
if (msg.thinking_content) {
|
||||
html += `<div class="thinking-toggle" onclick="this.nextElementSibling.classList.toggle('expanded')">💭 思考过程 ▾</div>`;
|
||||
html += `<div class="thinking-content">${MarkdownRenderer.render(msg.thinking_content)}</div>`;
|
||||
}
|
||||
html += `<div class="markdown-body">${MarkdownRenderer.render(msg.content)}</div>`;
|
||||
html += `</div>`;
|
||||
return html;
|
||||
}
|
||||
}).join('');
|
||||
|
||||
container.scrollTop = container.scrollHeight;
|
||||
},
|
||||
|
||||
async sendMessage() {
|
||||
if (this.isStreaming) return;
|
||||
|
||||
const input = document.getElementById('messageInput');
|
||||
const content = input.value.trim();
|
||||
if (!content) return;
|
||||
|
||||
if (!SessionManager.currentSessionId) {
|
||||
await SessionManager.createSession();
|
||||
}
|
||||
|
||||
// 清空输入
|
||||
input.value = '';
|
||||
input.style.height = 'auto';
|
||||
|
||||
// 构建消息
|
||||
const userMessage = { role: 'user', content };
|
||||
if (UploadManager.getFiles().length > 0) {
|
||||
userMessage.file_info = UploadManager.getFiles();
|
||||
}
|
||||
this.messages.push(userMessage);
|
||||
this.renderMessages();
|
||||
|
||||
// 保存用户消息到数据库
|
||||
api.post('/sessions/' + SessionManager.currentSessionId + '/messages', userMessage).catch(console.error);
|
||||
|
||||
// 清除文件
|
||||
UploadManager.clearFiles();
|
||||
|
||||
// 获取当前配置
|
||||
const provider = document.getElementById('providerSelect')?.value || 'newapi';
|
||||
const model = document.getElementById('modelSelect')?.value || 'gpt-3.5-turbo';
|
||||
const thinkingMode = document.getElementById('thinkingMode')?.checked || false;
|
||||
|
||||
// SSE 流式请求
|
||||
this.isStreaming = true;
|
||||
this.updateSendButton();
|
||||
|
||||
try {
|
||||
await this.streamChat(provider, model, thinkingMode);
|
||||
} catch (err) {
|
||||
this.addErrorMessage(err.message);
|
||||
} finally {
|
||||
this.isStreaming = false;
|
||||
this.updateSendButton();
|
||||
}
|
||||
},
|
||||
|
||||
async streamChat(provider, model, thinkingMode) {
|
||||
const token = Storage.getToken();
|
||||
|
||||
// 构建消息历史(只取 role 和 content)
|
||||
const messages = this.messages.map(m => ({
|
||||
role: m.role,
|
||||
content: m.content
|
||||
}));
|
||||
|
||||
// 添加 AI 消息占位
|
||||
const assistantEl = this.addAssistantPlaceholder();
|
||||
let fullContent = '';
|
||||
let thinkingContent = '';
|
||||
|
||||
const response = await fetch('/api/chat/completions', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer ' + token
|
||||
},
|
||||
body: JSON.stringify({
|
||||
provider, model, messages, stream: true, thinkingMode
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json();
|
||||
throw new Error(err.message || 'AI 请求失败');
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (!line.startsWith('data: ')) continue;
|
||||
const data = line.slice(6).trim();
|
||||
|
||||
if (data === '[DONE]') {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
|
||||
if (parsed.type === 'error') {
|
||||
throw new Error(parsed.message);
|
||||
}
|
||||
|
||||
if (parsed.thinking) {
|
||||
thinkingContent += parsed.thinking;
|
||||
this.updateThinkingContent(assistantEl, thinkingContent);
|
||||
}
|
||||
|
||||
if (parsed.content) {
|
||||
fullContent += parsed.content;
|
||||
this.updateAssistantContent(assistantEl, fullContent);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.message && !e.message.includes('JSON')) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 流结束,保存 AI 消息
|
||||
const assistantMessage = {
|
||||
role: 'assistant',
|
||||
content: fullContent,
|
||||
thinking_content: thinkingContent || null
|
||||
};
|
||||
this.messages.push(assistantMessage);
|
||||
|
||||
// 保存到数据库
|
||||
api.post('/sessions/' + SessionManager.currentSessionId + '/messages', assistantMessage).catch(console.error);
|
||||
|
||||
// 缓存到 localStorage
|
||||
Storage.setCachedMessages(SessionManager.currentSessionId, this.messages);
|
||||
|
||||
// 移除打字机光标
|
||||
this.removeTypingCursor(assistantEl);
|
||||
},
|
||||
|
||||
addAssistantPlaceholder() {
|
||||
const container = document.getElementById('messagesContainer');
|
||||
const empty = container.querySelector('.empty-state');
|
||||
if (empty) empty.remove();
|
||||
|
||||
const el = document.createElement('div');
|
||||
el.className = 'message assistant';
|
||||
el.innerHTML = '<span class="typing-cursor"></span>';
|
||||
container.appendChild(el);
|
||||
container.scrollTop = container.scrollHeight;
|
||||
return el;
|
||||
},
|
||||
|
||||
updateAssistantContent(el, content) {
|
||||
const cursor = el.querySelector('.typing-cursor');
|
||||
const body = el.querySelector('.markdown-body');
|
||||
|
||||
if (body) {
|
||||
body.innerHTML = MarkdownRenderer.render(content);
|
||||
if (cursor) body.appendChild(cursor);
|
||||
} else {
|
||||
const thinking = el.querySelector('.thinking-content, .thinking-toggle');
|
||||
const md = document.createElement('div');
|
||||
md.className = 'markdown-body';
|
||||
md.innerHTML = MarkdownRenderer.render(content);
|
||||
if (cursor) md.appendChild(cursor);
|
||||
|
||||
if (thinking) {
|
||||
el.appendChild(md);
|
||||
} else {
|
||||
el.innerHTML = '';
|
||||
el.appendChild(md);
|
||||
}
|
||||
}
|
||||
|
||||
el.parentElement.scrollTop = el.parentElement.scrollHeight;
|
||||
},
|
||||
|
||||
updateThinkingContent(el, content) {
|
||||
let toggle = el.querySelector('.thinking-toggle');
|
||||
let container = el.querySelector('.thinking-content');
|
||||
|
||||
if (!toggle) {
|
||||
toggle = document.createElement('div');
|
||||
toggle.className = 'thinking-toggle expanded';
|
||||
toggle.textContent = '💭 思考过程 ▾';
|
||||
toggle.onclick = function() {
|
||||
container.classList.toggle('expanded');
|
||||
this.textContent = container.classList.contains('expanded') ? '💭 思考过程 ▴' : '💭 思考过程 ▾';
|
||||
};
|
||||
el.insertBefore(toggle, el.firstChild);
|
||||
}
|
||||
|
||||
if (!container) {
|
||||
container = document.createElement('div');
|
||||
container.className = 'thinking-content expanded';
|
||||
el.insertBefore(container, toggle.nextSibling);
|
||||
}
|
||||
|
||||
container.innerHTML = MarkdownRenderer.render(content);
|
||||
el.parentElement.scrollTop = el.parentElement.scrollHeight;
|
||||
},
|
||||
|
||||
removeTypingCursor(el) {
|
||||
const cursor = el.querySelector('.typing-cursor');
|
||||
if (cursor) cursor.remove();
|
||||
},
|
||||
|
||||
addErrorMessage(message) {
|
||||
const container = document.getElementById('messagesContainer');
|
||||
const el = document.createElement('div');
|
||||
el.className = 'message assistant';
|
||||
el.innerHTML = `<div class="alert alert-error">❌ ${this.escapeHtml(message)} <button class="btn btn-sm btn-secondary" onclick="ChatManager.retryLast()">重试</button></div>`;
|
||||
container.appendChild(el);
|
||||
container.scrollTop = container.scrollHeight;
|
||||
},
|
||||
|
||||
clearMessages() {
|
||||
const container = document.getElementById('messagesContainer');
|
||||
if (container) {
|
||||
container.innerHTML = '<div class="empty-state"><h3>开始新的对话</h3><p>输入消息开始聊天</p></div>';
|
||||
}
|
||||
this.messages = [];
|
||||
},
|
||||
|
||||
updateSendButton() {
|
||||
const btn = document.getElementById('sendBtn');
|
||||
if (btn) {
|
||||
btn.disabled = this.isStreaming;
|
||||
btn.textContent = this.isStreaming ? '回复中...' : '发送';
|
||||
}
|
||||
},
|
||||
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
};
|
||||
34
assets/js/markdown.js
Normal file
34
assets/js/markdown.js
Normal file
@@ -0,0 +1,34 @@
|
||||
const MarkdownRenderer = {
|
||||
init() {
|
||||
// 配置 marked.js
|
||||
marked.setOptions({
|
||||
highlight: function(code, lang) {
|
||||
if (lang && hljs.getLanguage(lang)) {
|
||||
return hljs.highlight(code, { language: lang }).value;
|
||||
}
|
||||
return hljs.highlightAuto(code).value;
|
||||
},
|
||||
breaks: true,
|
||||
gfm: true
|
||||
});
|
||||
},
|
||||
|
||||
render(text) {
|
||||
if (!text) return '';
|
||||
let html = marked.parse(text);
|
||||
// 为代码块添加复制按钮
|
||||
html = html.replace(/<pre><code/g, '<pre><button class="copy-btn" onclick="MarkdownRenderer.copyCode(this)">复制</button><code');
|
||||
return html;
|
||||
},
|
||||
|
||||
copyCode(btn) {
|
||||
const code = btn.nextElementSibling;
|
||||
navigator.clipboard.writeText(code.textContent).then(() => {
|
||||
btn.textContent = '已复制';
|
||||
setTimeout(() => { btn.textContent = '复制'; }, 2000);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 初始化
|
||||
MarkdownRenderer.init();
|
||||
72
assets/js/session.js
Normal file
72
assets/js/session.js
Normal file
@@ -0,0 +1,72 @@
|
||||
const SessionManager = {
|
||||
sessions: [],
|
||||
currentSessionId: null,
|
||||
|
||||
async loadSessions() {
|
||||
try {
|
||||
const res = await api.get('/sessions');
|
||||
this.sessions = res.data || [];
|
||||
this.renderSessionList();
|
||||
} catch (err) {
|
||||
console.error('加载会话失败:', err);
|
||||
}
|
||||
},
|
||||
|
||||
renderSessionList() {
|
||||
const list = document.getElementById('sessionList');
|
||||
if (!list) return;
|
||||
|
||||
list.innerHTML = this.sessions.map(s => `
|
||||
<div class="session-item ${s.id === this.currentSessionId ? 'active' : ''}"
|
||||
onclick="SessionManager.switchSession(${s.id})">
|
||||
<span class="session-name">${this.escapeHtml(s.name)}</span>
|
||||
<button class="session-delete" onclick="event.stopPropagation(); SessionManager.deleteSession(${s.id})" title="删除">×</button>
|
||||
</div>
|
||||
`).join('');
|
||||
},
|
||||
|
||||
async createSession() {
|
||||
try {
|
||||
const res = await api.post('/sessions', {});
|
||||
this.sessions.unshift(res.data);
|
||||
this.currentSessionId = res.data.id;
|
||||
this.renderSessionList();
|
||||
ChatManager.clearMessages();
|
||||
return res.data;
|
||||
} catch (err) {
|
||||
console.error('创建会话失败:', err);
|
||||
}
|
||||
},
|
||||
|
||||
async switchSession(id) {
|
||||
this.currentSessionId = id;
|
||||
this.renderSessionList();
|
||||
await ChatManager.loadMessages(id);
|
||||
},
|
||||
|
||||
async deleteSession(id) {
|
||||
if (!confirm('确定要删除这个会话吗?')) return;
|
||||
try {
|
||||
await api.delete('/sessions/' + id);
|
||||
this.sessions = this.sessions.filter(s => s.id !== id);
|
||||
Storage.clearCachedMessages(id);
|
||||
|
||||
if (this.currentSessionId === id) {
|
||||
this.currentSessionId = null;
|
||||
ChatManager.clearMessages();
|
||||
if (this.sessions.length > 0) {
|
||||
await this.switchSession(this.sessions[0].id);
|
||||
}
|
||||
}
|
||||
this.renderSessionList();
|
||||
} catch (err) {
|
||||
alert('删除会话失败: ' + err.message);
|
||||
}
|
||||
},
|
||||
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
};
|
||||
22
assets/js/storage.js
Normal file
22
assets/js/storage.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const Storage = {
|
||||
getToken() {
|
||||
return localStorage.getItem('token');
|
||||
},
|
||||
setToken(token) {
|
||||
localStorage.setItem('token', token);
|
||||
},
|
||||
clearToken() {
|
||||
localStorage.removeItem('token');
|
||||
},
|
||||
// 消息缓存
|
||||
getCachedMessages(sessionId) {
|
||||
const data = localStorage.getItem('messages_' + sessionId);
|
||||
return data ? JSON.parse(data) : null;
|
||||
},
|
||||
setCachedMessages(sessionId, messages) {
|
||||
localStorage.setItem('messages_' + sessionId, JSON.stringify(messages));
|
||||
},
|
||||
clearCachedMessages(sessionId) {
|
||||
localStorage.removeItem('messages_' + sessionId);
|
||||
}
|
||||
};
|
||||
67
assets/js/upload.js
Normal file
67
assets/js/upload.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const UploadManager = {
|
||||
files: [], // 待发送的文件列表
|
||||
allowedTypes: '.jpg,.jpeg,.png,.gif,.webp,.js,.ts,.py,.java,.cpp,.c,.html,.css,.json,.xml,.txt,.md,.go,.rs,.php,.rb,.sql,.yaml,.yml,.sh,.bat',
|
||||
|
||||
init() {
|
||||
const btn = document.getElementById('uploadBtn');
|
||||
if (btn) {
|
||||
btn.addEventListener('click', () => this.openFileSelector());
|
||||
}
|
||||
},
|
||||
|
||||
openFileSelector() {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = this.allowedTypes;
|
||||
input.multiple = true;
|
||||
input.onchange = (e) => this.handleFiles(e.target.files);
|
||||
input.click();
|
||||
},
|
||||
|
||||
async handleFiles(fileList) {
|
||||
for (const file of fileList) {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
try {
|
||||
const res = await api.upload('/upload', formData);
|
||||
this.files.push(res.data);
|
||||
this.renderPreview();
|
||||
} catch (err) {
|
||||
alert('文件上传失败: ' + err.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
renderPreview() {
|
||||
const preview = document.getElementById('filePreview');
|
||||
if (!preview) return;
|
||||
|
||||
preview.innerHTML = this.files.map((f, i) => `
|
||||
<div class="file-preview-item">
|
||||
<span>📎 ${this.escapeHtml(f.name)}</span>
|
||||
<span class="remove-file" onclick="UploadManager.removeFile(${i})">×</span>
|
||||
</div>
|
||||
`).join('');
|
||||
},
|
||||
|
||||
removeFile(index) {
|
||||
this.files.splice(index, 1);
|
||||
this.renderPreview();
|
||||
},
|
||||
|
||||
getFiles() {
|
||||
return this.files;
|
||||
},
|
||||
|
||||
clearFiles() {
|
||||
this.files = [];
|
||||
this.renderPreview();
|
||||
},
|
||||
|
||||
escapeHtml(text) {
|
||||
const div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user