From 1ffd256c9df050d3b311aa8a8ae536ca437944ed Mon Sep 17 00:00:00 2001 From: hugh <1012760428@qq.com> Date: Fri, 30 Jan 2026 19:07:20 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E5=89=8D?= =?UTF-8?q?=E7=AB=AF=E4=BA=A4=E4=BA=92=E4=BB=A3=E7=A0=81=EF=BC=8C=E9=87=87?= =?UTF-8?q?=E7=94=A8=E6=A8=A1=E5=9D=97=E5=8C=96=E6=9E=B6=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 架构改进: - chat-utils.js: 工具函数模块 - chat-ui.js: UI渲染模块 - chat-api.js: API调用模块 - chat-main.js: 主程序入口 视觉优化: - 添加多种动画效果 - 工具卡片悬停效果 - 任务项悬停效果 - 进度条动态效果 - 打字指示器优化 交互优化: - 模块分离,职责清晰 - 更好的错误处理 - 支持生成器函数 - 统一工具渲染逻辑 备份:chat.js.backup 保留旧版本 --- src/main/resources/static/css/style.css | 279 ++++++- src/main/resources/static/index.html | 6 +- src/main/resources/static/js/chat-api.js | 158 ++++ src/main/resources/static/js/chat-main.js | 259 +++++++ src/main/resources/static/js/chat-ui.js | 442 ++++++++++++ src/main/resources/static/js/chat-utils.js | 112 +++ src/main/resources/static/js/chat.js | 801 --------------------- 7 files changed, 1250 insertions(+), 807 deletions(-) create mode 100644 src/main/resources/static/js/chat-api.js create mode 100644 src/main/resources/static/js/chat-main.js create mode 100644 src/main/resources/static/js/chat-ui.js create mode 100644 src/main/resources/static/js/chat-utils.js delete mode 100644 src/main/resources/static/js/chat.js diff --git a/src/main/resources/static/css/style.css b/src/main/resources/static/css/style.css index de4d5db..7b94b49 100644 --- a/src/main/resources/static/css/style.css +++ b/src/main/resources/static/css/style.css @@ -621,25 +621,294 @@ body { background: #94a3b8; } -/* 响应式设计 */ +/* ==================== 动画效果 ==================== */ + +/* 淡入动画 */ +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +/* 滑入动画 */ +@keyframes slideIn { + from { + opacity: 0; + transform: translateX(-20px); + } + to { + opacity: 1; + transform: translateX(0); + } +} + +/* 脉冲动画 */ +@keyframes pulse { + 0%, 100% { + transform: scale(1); + } + 50% { + transform: scale(1.05); + } +} + +/* 闪烁动画 */ +@keyframes shimmer { + 0% { + background-position: -1000px 0; + } + 100% { + background-position: 1000px 0; + } +} + +/* 弹跳动画 */ +@keyframes bounce { + 0%, 100% { + transform: translateY(0); + } + 50% { + transform: translateY(-5px); + } +} + +/* 应用动画类 */ +.animate-in { + animation: fadeInUp 0.4s cubic-bezier(0.4, 0, 0.2, 1) forwards; +} + +.animate-out { + animation: fadeInUp 0.3s cubic-bezier(0.4, 0, 0.2, 1) reverse forwards; +} + +/* 消息加载状态 */ +.message.loading { + opacity: 0.7; +} + +.message.loading .message-content { + background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); + background-size: 1000px 100%; + animation: shimmer 2s infinite linear; +} + +/* 打字指示器优化 */ +.typing-indicator { + display: flex; + gap: 6px; + padding: 8px 0; +} + +.typing-indicator span { + width: 10px; + height: 10px; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-radius: 50%; + animation: bounce 1.4s infinite ease-in-out both; +} + +.typing-indicator span:nth-child(1) { + animation-delay: -0.32s; +} + +.typing-indicator span:nth-child(2) { + animation-delay: -0.16s; +} + +/* 工具卡片悬停效果 */ +.tool-call:hover, +.tool-result:hover, +.todo-write-call:hover, +.todo-write-progress:hover { + transform: translateY(-3px); + box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15); + transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); +} + +/* 任务项悬停效果 */ +.todo-item { + transition: all 0.2s ease; + cursor: default; +} + +.todo-item:hover { + background: rgba(245, 158, 11, 0.1); + transform: translateX(5px); + border-radius: 6px; +} + +/* 进度条动画 */ +.progress-bar { + transition: width 0.5s cubic-bezier(0.4, 0, 0.2, 1); + background: linear-gradient(90deg, #ffffff 0%, #f0f0f0 50%, #ffffff 100%); + background-size: 200% 100%; + animation: shimmer 2s infinite; +} + +/* 发送按钮动画 */ +.btn-send:not(:disabled):hover { + transform: translateY(-2px); + box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4); +} + +.btn-send:not(:disabled):active { + transform: translateY(0); +} + +.btn-send:disabled { + opacity: 0.6; + cursor: not-allowed; +} + +/* 输入框聚焦效果 */ +.chat-input:focus { + outline: none; + border-color: #667eea; + box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1); + transition: all 0.3s ease; +} + +/* 复制按钮动画 */ +.copy-button { + transition: all 0.2s ease; +} + +.copy-button:hover { + background: rgba(255, 255, 255, 0.25); + transform: scale(1.05); +} + +.copy-button.copied { + background: #10b981; + animation: pulse 0.3s ease; +} + +/* 错误消息动画 */ +.error-message { + animation: fadeInUp 0.3s ease, slideIn 0.3s ease; +} + +/* 状态指示器动画 */ +.status-indicator { + transition: all 0.3s ease; +} + +.status-indicator.connected { + animation: pulse 2s infinite; +} + +/* 切换开关动画 */ +.toggle-switch { + transition: background 0.3s ease; +} + +.toggle-switch::before { + transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); +} + +/* 清空按钮动画 */ +.btn-secondary { + transition: all 0.2s ease; +} + +.btn-secondary:hover { + background: rgba(255, 255, 255, 0.3); + transform: translateY(-1px); +} + +/* 响应式优化 */ @media (max-width: 768px) { .header { padding: 15px 20px; + flex-wrap: wrap; + gap: 10px; } .header h1 { - font-size: 20px; + font-size: 18px; + } + + .header-controls { + width: 100%; + justify-content: flex-end; + flex-wrap: wrap; } .messages { - padding: 20px; + padding: 15px; } .message-content { - max-width: 85%; + max-width: 90%; + font-size: 14px; } .input-container { - padding: 15px 20px; + padding: 15px; + } + + .chat-form { + gap: 8px; + } + + .chat-input { + font-size: 16px; /* 防止 iOS 缩放 */ + } + + .btn-send { + padding: 12px 20px; + font-size: 14px; + } + + /* 移动端工具卡片优化 */ + .tool-call, + .tool-result, + .todo-write-call, + .todo-write-progress { + padding: 12px; + margin: 8px 0; + } + + .tool-call-details, + .tool-result-content { + font-size: 12px; + } + + /* 移动端任务列表优化 */ + .todo-item { + font-size: 13px; + padding: 6px 8px; + } + + .todo-progress-header { + font-size: 14px; + } +} + +/* 暗色模式支持(可选) */ +@media (prefers-color-scheme: dark) { + /* 可以在这里添加暗色模式样式 */ +} + +/* 打印样式 */ +@media print { + .header, + .input-container, + .copy-button { + display: none; + } + + .messages { + height: auto; + overflow: visible; + } + + .message { + break-inside: avoid; } } diff --git a/src/main/resources/static/index.html b/src/main/resources/static/index.html index 9c89c7c..76fd487 100644 --- a/src/main/resources/static/index.html +++ b/src/main/resources/static/index.html @@ -49,6 +49,10 @@ - + + + + + diff --git a/src/main/resources/static/js/chat-api.js b/src/main/resources/static/js/chat-api.js new file mode 100644 index 0000000..32fd60d --- /dev/null +++ b/src/main/resources/static/js/chat-api.js @@ -0,0 +1,158 @@ +/** + * API 调用模块 + * 负责所有后端通信 + */ + +const ChatAPI = { + baseUrl: '', + conversationId: null, + + /** + * 初始化 + */ + init(conversationId) { + this.conversationId = conversationId; + }, + + /** + * 更新会话 ID + */ + setConversationId(id) { + this.conversationId = id; + localStorage.setItem('conversationId', id); + }, + + /** + * 生成新的会话 ID + */ + regenerateConversationId() { + const newId = ChatUtils.generateConversationId(); + this.setConversationId(newId); + return newId; + }, + + // ==================== 流式 API ==================== + + /** + * 传统流式响应(无工具调用) + */ + async *streamMessage(message) { + const response = await fetch(`${this.baseUrl}/api/chat/stream?conversationId=${this.conversationId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message }) + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + const chunk = decoder.decode(value); + const events = ChatUtils.parseSSE(chunk); + + for (const event of events) { + if (event.type === 'text') { + const data = ChatUtils.safeJsonParse(event.data, {}); + yield { type: 'text', content: data.content }; + } else if (event.type === 'error') { + const data = ChatUtils.safeJsonParse(event.data, {}); + yield { type: 'error', message: data.message }; + } + } + } + } finally { + reader.releaseLock(); + } + }, + + /** + * 伪流式响应(支持工具调用) + */ + async *streamMessageWithTools(message) { + const response = await fetch(`${this.baseUrl}/api/chat/stream-with-tools?conversationId=${this.conversationId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message }) + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n\n'); + buffer = lines.pop() || ''; + + for (const line of lines) { + if (!line.trim()) continue; + + const eventMatch = line.match(/event: (\w+)/); + const dataMatch = line.match(/data: (.+)/); + + if (eventMatch && dataMatch) { + const eventType = eventMatch[1]; + const data = ChatUtils.safeJsonParse(dataMatch[1], {}); + + yield { type: eventType, data }; + } + } + } + } finally { + reader.releaseLock(); + } + }, + + // ==================== 普通 API ==================== + + /** + * 非流式聊天(已废弃,保留兼容) + */ + async sendMessage(message) { + const response = await fetch(`${this.baseUrl}/api/chat/chat?conversationId=${this.conversationId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ message }) + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + return await response.text(); + }, + + /** + * 清空对话历史 + */ + async clearConversation() { + const response = await fetch(`${this.baseUrl}/api/chat/clear?conversationId=${this.conversationId}`, { + method: 'DELETE' + }); + + if (!response.ok) { + throw new Error('清空对话失败'); + } + + return true; + } +}; + +// 导出模块 +window.ChatAPI = ChatAPI; diff --git a/src/main/resources/static/js/chat-main.js b/src/main/resources/static/js/chat-main.js new file mode 100644 index 0000000..4c6b643 --- /dev/null +++ b/src/main/resources/static/js/chat-main.js @@ -0,0 +1,259 @@ +/** + * 主程序入口 + * 整合所有模块,处理事件绑定和业务流程 + */ + +const ChatApp = { + conversationId: null, + isProcessing: false, + + /** + * 初始化应用 + */ + init() { + // 初始化 DOM 元素 + ChatUI.init(); + + // 初始化会话 ID + this.conversationId = ChatUtils.getOrCreateConversationId(); + ChatAPI.init(this.conversationId); + + // 绑定事件 + this.bindEvents(); + + // 显示欢迎消息 + this.showWelcomeMessage(); + + console.log('🚀 ChatApp 初始化完成'); + }, + + /** + * 绑定所有事件 + */ + bindEvents() { + const ui = ChatUI.elements; + + // 表单提交 + ui.chatForm.addEventListener('submit', (e) => this.handleSubmit(e)); + + // 输入框键盘事件 + ui.userInput.addEventListener('keydown', (e) => this.handleKeyDown(e)); + + // 输入框自动调整高度 + ui.userInput.addEventListener('input', () => ChatUI.autoResizeInput()); + + // 清空对话 + ui.clearBtn.addEventListener('click', () => this.handleClear()); + + // 页面卸载前保存会话 ID + window.addEventListener('beforeunload', () => { + localStorage.setItem('conversationId', this.conversationId); + }); + }, + + /** + * 处理表单提交 + */ + async handleSubmit(e) { + e.preventDefault(); + + const message = ChatUI.elements.userInput.value.trim(); + if (!message || this.isProcessing) return; + + // 设置处理状态 + this.isProcessing = true; + ChatUI.setInputState({ disabled: true, value: '' }); + + // 显示用户消息 + ChatUI.renderUserMessage(message); + + // 根据模式选择处理方式 + const useTools = ChatUI.isToolEnabled(); + if (useTools) { + await this.handleStreamWithTools(message); + } else { + await this.handleStream(message); + } + + // 恢复输入状态 + this.isProcessing = false; + ChatUI.setInputState({ disabled: false }); + ChatUI.elements.userInput.focus(); + }, + + /** + * 处理键盘事件 + */ + handleKeyDown(e) { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + ChatUI.elements.chatForm.dispatchEvent(new Event('submit')); + } + }, + + /** + * 处理传统流式响应 + */ + async handleStream(message) { + ChatUI.updateConnectionStatus(true); + + // 创建加载消息 + const messageEl = ChatUI.renderAssistantMessage('', { isLoading: true }); + let content = ''; + + try { + for await (const event of ChatAPI.streamMessage(message)) { + if (event.type === 'text') { + content += event.content; + ChatUI.updateMessage(messageEl, content); + } else if (event.type === 'error') { + ChatUI.showError(event.message); + } + } + } catch (error) { + console.error('流式响应错误:', error); + ChatUI.showError('连接错误: ' + error.message); + messageEl.remove(); + } finally { + ChatUI.updateConnectionStatus(false); + } + }, + + /** + * 处理伪流式响应(支持工具调用) + */ + async handleStreamWithTools(message) { + ChatUI.updateConnectionStatus(true); + + try { + for await (const event of ChatAPI.streamMessageWithTools(message)) { + await this.handleStreamEvent(event); + } + } catch (error) { + console.error('伪流式响应错误:', error); + ChatUI.showError('连接错误: ' + error.message); + } finally { + ChatUI.updateConnectionStatus(false); + } + }, + + /** + * 处理流式事件 + */ + async handleStreamEvent(event) { + const { type, data } = event; + + switch (type) { + case 'user_message': + // 用户消息已显示,跳过 + break; + + case 'tool_call': + this.handleToolCall(data); + break; + + case 'tool_response': + this.handleToolResponse(data); + break; + + case 'assistant_message': + ChatUI.renderAssistantMessage(data.content); + break; + + case 'final_response': + ChatUI.renderAssistantMessage(data.content); + break; + + case 'error': + ChatUI.showError(data.message); + break; + + default: + console.log('未知事件类型:', type, data); + } + }, + + /** + * 处理工具调用 + */ + handleToolCall(data) { + const { tool_name, arguments: args } = data; + const isTodoWrite = tool_name === 'TodoWrite'; + + ChatUI.renderToolCall(tool_name, args, { isTodoWrite }); + }, + + /** + * 处理工具响应 + */ + handleToolResponse(data) { + const { tool_name, response } = data; + const isTodoWrite = tool_name === 'TodoWrite'; + + ChatUI.renderToolResult(tool_name, response, { isTodoWrite }); + }, + + /** + * 处理清空对话 + */ + async handleClear() { + if (!confirm('确定要清空对话吗?')) return; + + try { + await ChatAPI.clearConversation(); + + // 生成新会话 ID + this.conversationId = ChatAPI.regenerateConversationId(); + + // 清空界面 + ChatUI.clearMessages(); + + // 显示重置消息 + ChatUI.renderAssistantMessage('对话已清空,我们可以重新开始!'); + } catch (error) { + console.error('清空对话错误:', error); + ChatUI.showError('清空对话失败: ' + error.message); + } + }, + + /** + * 显示欢迎消息 + */ + showWelcomeMessage() { + const welcomeMessage = `## 👋 欢迎使用 Spring AI Skills Chat + +我可以帮助你完成各种任务,包括: + +- 💬 **普通对话**(关闭"启用工具调用"使用传统流式响应) +- 🔧 **执行 Shell 命令** +- 📁 **读写文件** +- 🎯 **使用自定义 Skills** +- 📋 **任务管理**(TodoWrite) + +### 🌟 新功能:伪流式接口 + +开启"启用工具调用"后,你可以实时看到: +- 🔧 **工具调用**:AI 调用了哪些工具 +- ✅ **工具响应**:工具返回了什么结果 +- 💬 **AI 思考**:AI 的中间思考过程 +- 📊 **执行步骤**:完整的执行流程可视化 + +### 快速开始: + +1. **开启工具调用**:点击右上角的"启用工具调用"开关 +2. **发送指令**:例如"请帮我为某某公司执行完整的定价流程" +3. **实时观察**:工具调用和执行步骤会实时展示 + +现在就开始吧!🚀`; + + ChatUI.renderAssistantMessage(welcomeMessage); + } +}; + +// 页面加载完成后初始化 +document.addEventListener('DOMContentLoaded', () => { + ChatApp.init(); +}); + +// 导出(用于测试) +window.ChatApp = ChatApp; diff --git a/src/main/resources/static/js/chat-ui.js b/src/main/resources/static/js/chat-ui.js new file mode 100644 index 0000000..48443b4 --- /dev/null +++ b/src/main/resources/static/js/chat-ui.js @@ -0,0 +1,442 @@ +/** + * UI 渲染模块 + * 负责所有 DOM 操作和 UI 组件渲染 + */ + +const ChatUI = { + // DOM 元素缓存 + elements: {}, + + /** + * 初始化 DOM 元素缓存 + */ + init() { + this.elements = { + messagesContainer: document.getElementById('messages'), + chatForm: document.getElementById('chat-form'), + userInput: document.getElementById('user-input'), + sendBtn: document.getElementById('send-btn'), + clearBtn: document.getElementById('clear-btn'), + connectionStatus: document.getElementById('connection-status'), + toolToggle: document.getElementById('tool-toggle') + }; + + // 初始化 marked.js 配置 + this.initMarked(); + }, + + /** + * 获取 DOM 元素 + */ + get(id) { + return this.elements[id] || document.getElementById(id); + }, + + /** + * 初始化 Marked.js 配置 + */ + initMarked() { + marked.setOptions({ + breaks: true, + gfm: true, + highlight: (code, lang) => { + if (lang && hljs.getLanguage(lang)) { + try { + return hljs.highlight(code, { language: lang }).value; + } catch (err) { + console.error('代码高亮错误:', err); + } + } + return hljs.highlightAuto(code).value; + } + }); + }, + + // ==================== 消息渲染 ==================== + + /** + * 渲染用户消息 + */ + renderUserMessage(content) { + const messageDiv = document.createElement('div'); + messageDiv.className = 'message user animate-in'; + + const contentDiv = document.createElement('div'); + contentDiv.className = 'message-content'; + contentDiv.textContent = content; + + messageDiv.appendChild(contentDiv); + this.elements.messagesContainer.appendChild(messageDiv); + this.scrollToBottom(); + + return messageDiv; + }, + + /** + * 渲染 AI 消息 + */ + renderAssistantMessage(content, options = {}) { + const messageDiv = document.createElement('div'); + messageDiv.className = `message assistant animate-in ${options.isLoading ? 'loading' : ''}`; + + const contentDiv = document.createElement('div'); + contentDiv.className = 'message-content'; + + if (options.isLoading) { + contentDiv.innerHTML = this.getTypingIndicator(); + } else { + contentDiv.innerHTML = this.renderMarkdown(content); + this.addCodeCopyButtons(contentDiv); + } + + messageDiv.appendChild(contentDiv); + this.elements.messagesContainer.appendChild(messageDiv); + this.scrollToBottom(); + + return messageDiv; + }, + + /** + * 更新消息内容 + */ + updateMessage(messageElement, content) { + const contentDiv = messageElement.querySelector('.message-content'); + contentDiv.innerHTML = this.renderMarkdown(content); + this.addCodeCopyButtons(contentDiv); + this.scrollToBottom(); + }, + + /** + * 获取打字指示器 HTML + */ + getTypingIndicator() { + return '
'; + }, + + // ==================== 工具调用渲染 ==================== + + /** + * 渲染工具调用 + */ + renderToolCall(name, args, options = {}) { + const { isTodoWrite = false } = options; + const div = document.createElement('div'); + div.className = isTodoWrite ? 'todo-write-call animate-in' : 'tool-call animate-in'; + + const header = document.createElement('div'); + header.className = isTodoWrite ? 'todo-write-header' : 'tool-call-header'; + header.innerHTML = isTodoWrite + ? '📋 任务列表' + : `⚙️ 调用工具: ${name}`; + + div.appendChild(header); + + // 如果是 TodoWrite,渲染任务列表 + if (isTodoWrite) { + const todoList = this.renderTodoList(args); + if (todoList) { + div.appendChild(todoList); + } + } else { + // 普通工具调用,渲染参数 + const details = document.createElement('div'); + details.className = 'tool-call-details'; + details.textContent = '参数: ' + ChatUtils.formatJson(args); + div.appendChild(details); + } + + this.elements.messagesContainer.appendChild(div); + this.scrollToBottom(); + + return div; + }, + + /** + * 渲染工具响应 + */ + renderToolResult(name, result, options = {}) { + const { isTodoWrite = false } = options; + + if (isTodoWrite) { + return this.renderTodoProgress(result); + } + + const div = document.createElement('div'); + div.className = 'tool-result animate-in'; + + const header = document.createElement('div'); + header.className = 'tool-result-header'; + header.innerHTML = `📄 工具返回: ${name}`; + + const content = document.createElement('div'); + content.className = 'tool-result-content'; + content.textContent = typeof result === 'string' ? result : ChatUtils.formatJson(result); + + div.appendChild(header); + div.appendChild(content); + this.elements.messagesContainer.appendChild(div); + this.scrollToBottom(); + + return div; + }, + + // ==================== TodoWrite 渲染 ==================== + + /** + * 渲染 TodoWrite 任务列表 + */ + renderTodoList(args) { + try { + const data = typeof args === 'string' ? JSON.parse(args) : args; + const todos = this.extractTodos(data); + + if (!todos || todos.length === 0) return null; + + const listDiv = document.createElement('div'); + listDiv.className = 'todo-list'; + + todos.forEach(todo => { + const item = this.createTodoItem(todo); + listDiv.appendChild(item); + }); + + return listDiv; + } catch (e) { + console.error('渲染任务列表失败:', e); + return null; + } + }, + + /** + * 渲染 TodoWrite 进度 + */ + renderTodoProgress(response) { + try { + const data = typeof response === 'string' + ? this.extractJsonFromString(response) + : response; + + const todos = this.extractTodos(data); + if (!todos || todos.length === 0) { + return this.renderToolResult('TodoWrite', response); + } + + const div = document.createElement('div'); + div.className = 'todo-write-progress animate-in'; + + // 计算进度 + const total = todos.length; + const completed = todos.filter(t => t.status === 'completed').length; + const percentage = Math.round((completed / total) * 100); + + // 进度头部 + const header = document.createElement('div'); + header.className = 'todo-progress-header'; + header.innerHTML = `📊 任务进度: ${completed}/${total} (${percentage}%)`; + + // 进度条 + const progressBar = this.createProgressBar(percentage); + + // 任务列表 + const listDiv = document.createElement('div'); + listDiv.className = 'todo-list'; + todos.forEach(todo => { + listDiv.appendChild(this.createTodoItem(todo)); + }); + + div.appendChild(header); + div.appendChild(progressBar); + div.appendChild(listDiv); + + this.elements.messagesContainer.appendChild(div); + this.scrollToBottom(); + + return div; + } catch (e) { + console.error('渲染任务进度失败:', e); + return this.renderToolResult('TodoWrite', response); + } + }, + + /** + * 创建任务项 + */ + createTodoItem(todo) { + const item = document.createElement('div'); + item.className = `todo-item todo-${todo.status}`; + + const icons = { + pending: '[ ]', + in_progress: '[→]', + completed: '[✓]' + }; + + item.innerHTML = ` + ${icons[todo.status] || '[ ]'} + ${todo.content} + `; + + return item; + }, + + /** + * 创建进度条 + */ + createProgressBar(percentage) { + const container = document.createElement('div'); + container.className = 'progress-bar-container'; + + const bar = document.createElement('div'); + bar.className = 'progress-bar'; + bar.style.width = `${percentage}%`; + + container.appendChild(bar); + return container; + }, + + /** + * 从数据中提取 todos + */ + extractTodos(data) { + if (!data) return null; + if (data.todos) { + if (data.todos.todos) return data.todos.todos; + if (Array.isArray(data.todos)) return data.todos; + } + return null; + }, + + /** + * 从字符串中提取 JSON + */ + extractJsonFromString(str) { + const match = str.match(/\{[\s\S]*"todos"[\s\S]*\}/); + if (match) { + return ChatUtils.safeJsonParse(match[0], {}); + } + return {}; + }, + + // ==================== 辅助功能 ==================== + + /** + * 渲染 Markdown + */ + renderMarkdown(content) { + const html = marked.parse(content); + return DOMPurify.sanitize(html); + }, + + /** + * 添加代码复制按钮 + */ + addCodeCopyButtons(container) { + container.querySelectorAll('pre code').forEach((block) => { + hljs.highlightElement(block); + + const pre = block.parentElement; + const copyBtn = document.createElement('button'); + copyBtn.className = 'copy-button'; + copyBtn.textContent = '复制'; + + copyBtn.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(block.textContent); + copyBtn.textContent = '已复制!'; + copyBtn.classList.add('copied'); + setTimeout(() => { + copyBtn.textContent = '复制'; + copyBtn.classList.remove('copied'); + }, 2000); + } catch (err) { + copyBtn.textContent = '复制失败'; + } + }); + + pre.style.position = 'relative'; + pre.appendChild(copyBtn); + }); + }, + + /** + * 显示错误消息 + */ + showError(message, duration = 3000) { + const errorDiv = document.createElement('div'); + errorDiv.className = 'error-message animate-in'; + errorDiv.textContent = '❌ ' + message; + + this.elements.messagesContainer.appendChild(errorDiv); + this.scrollToBottom(); + + setTimeout(() => { + errorDiv.classList.add('animate-out'); + setTimeout(() => errorDiv.remove(), 300); + }, duration); + }, + + /** + * 更新连接状态 + */ + updateConnectionStatus(connected) { + const status = this.elements.connectionStatus; + if (connected) { + status.textContent = '已连接'; + status.className = 'status-indicator connected'; + } else { + status.textContent = '未连接'; + status.className = 'status-indicator disconnected'; + } + }, + + /** + * 清空消息区域 + */ + clearMessages() { + this.elements.messagesContainer.innerHTML = ''; + }, + + /** + * 滚动到底部 + */ + scrollToBottom() { + const container = this.elements.messagesContainer; + container.scrollTop = container.scrollHeight; + }, + + /** + * 设置输入框状态 + */ + setInputState(options) { + const { disabled = false, value = null } = options; + const input = this.elements.userInput; + const btn = this.elements.sendBtn; + + if (value !== null) { + input.value = value; + input.style.height = 'auto'; + } + + input.disabled = disabled; + btn.disabled = disabled || !input.value.trim(); + }, + + /** + * 自动调整输入框高度 + */ + autoResizeInput() { + const input = this.elements.userInput; + input.style.height = 'auto'; + input.style.height = Math.min(input.scrollHeight, 150) + 'px'; + }, + + /** + * 获取工具开关状态 + */ + isToolEnabled() { + return this.elements.toolToggle.checked; + } +}; + +// 导出模块 +window.ChatUI = ChatUI; diff --git a/src/main/resources/static/js/chat-utils.js b/src/main/resources/static/js/chat-utils.js new file mode 100644 index 0000000..77fc314 --- /dev/null +++ b/src/main/resources/static/js/chat-utils.js @@ -0,0 +1,112 @@ +/** + * 工具函数模块 + * 提供通用的辅助函数 + */ + +const ChatUtils = { + /** + * 生成唯一的会话 ID + */ + generateConversationId() { + return 'conv-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9); + }, + + /** + * 从 localStorage 获取或创建会话 ID + */ + getOrCreateConversationId() { + let conversationId = localStorage.getItem('conversationId'); + if (!conversationId) { + conversationId = this.generateConversationId(); + localStorage.setItem('conversationId', conversationId); + } + return conversationId; + }, + + /** + * 生成新的会话 ID 并保存 + */ + regenerateConversationId() { + const newId = this.generateConversationId(); + localStorage.setItem('conversationId', newId); + return newId; + }, + + /** + * 安全地解析 JSON + */ + safeJsonParse(str, defaultValue = null) { + try { + return JSON.parse(str); + } catch (e) { + console.warn('JSON 解析失败:', e); + return defaultValue; + } + }, + + /** + * 格式化 JSON 显示 + */ + formatJson(obj, indent = 2) { + if (typeof obj === 'string') { + try { + const parsed = JSON.parse(obj); + return JSON.stringify(parsed, null, indent); + } catch (e) { + return obj; + } + } + return JSON.stringify(obj, null, indent); + }, + + /** + * 截断文本 + */ + truncate(text, maxLength = 500) { + if (!text) return ''; + if (text.length <= maxLength) return text; + return text.substring(0, maxLength) + '...'; + }, + + /** + * 解析 SSE 事件流 + */ + parseSSE(chunk) { + const events = []; + const lines = chunk.split('\n'); + let currentEvent = { type: '', data: '' }; + + for (const line of lines) { + if (line.startsWith('event: ')) { + currentEvent.type = line.substring(7); + } else if (line.startsWith('data: ')) { + currentEvent.data = line.substring(6); + if (currentEvent.type && currentEvent.data) { + events.push({ ...currentEvent }); + currentEvent = { type: '', data: '' }; + } + } + } + + return events; + }, + + /** + * 深度合并对象 + */ + deepMerge(target, source) { + for (const key in source) { + if (source.hasOwnProperty(key)) { + if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) { + target[key] = this.deepMerge(target[key] || {}, source[key]); + } else { + target[key] = source[key]; + } + } + } + return target; + } +}; + +// 导出模块 +window.ChatUtils = ChatUtils; diff --git a/src/main/resources/static/js/chat.js b/src/main/resources/static/js/chat.js deleted file mode 100644 index 8d26395..0000000 --- a/src/main/resources/static/js/chat.js +++ /dev/null @@ -1,801 +0,0 @@ -// 获取 DOM 元素 -const messagesContainer = document.getElementById('messages'); -const chatForm = document.getElementById('chat-form'); -const userInput = document.getElementById('user-input'); -const sendBtn = document.getElementById('send-btn'); -const clearBtn = document.getElementById('clear-btn'); -const connectionStatus = document.getElementById('connection-status'); -const toolToggle = document.getElementById('tool-toggle'); - -// 会话 ID 管理 -let conversationId = localStorage.getItem('conversationId'); - -if (!conversationId) { - conversationId = generateConversationId(); - localStorage.setItem('conversationId', conversationId); -} - -// 生成新的会话 ID -function generateConversationId() { - return 'conv-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9); -} - -// 自动调整文本框高度 -userInput.addEventListener('input', function() { - this.style.height = 'auto'; - this.style.height = Math.min(this.scrollHeight, 150) + 'px'; - - // 启用/禁用发送按钮 - sendBtn.disabled = this.value.trim() === ''; -}); - -// 处理 Shift+Enter 换行,Enter 发送 -userInput.addEventListener('keydown', function(e) { - if (e.key === 'Enter' && !e.shiftKey) { - e.preventDefault(); - if (this.value.trim() !== '') { - chatForm.dispatchEvent(new Event('submit')); - } - } -}); - -// 表单提交 -chatForm.addEventListener('submit', async function(e) { - e.preventDefault(); - - const message = userInput.value.trim(); - if (!message) return; - - // 清空输入框 - userInput.value = ''; - userInput.style.height = 'auto'; - sendBtn.disabled = true; - - // 添加用户消息到界面 - appendMessage('user', message); - - // 根据切换状态选择接口 - const useTools = toolToggle.checked; - if (useTools) { - // 使用伪流式接口(实时展示工具调用步骤) - await streamMessageWithTools(message); - } else { - // 使用传统流式响应 - await streamMessage(message); - } -}); - -// 清空对话 -clearBtn.addEventListener('click', async function() { - if (!confirm('确定要清空对话吗?')) return; - - try { - const response = await fetch(`/api/chat/clear?conversationId=${conversationId}`, { - method: 'DELETE' - }); - - if (response.ok) { - // 生成新的会话 ID - conversationId = generateConversationId(); - localStorage.setItem('conversationId', conversationId); - - // 清空消息区域 - messagesContainer.innerHTML = ''; - appendMessage('assistant', '对话已清空,我们可以重新开始!'); - } else { - showError('清空对话失败'); - } - } catch (error) { - console.error('清空对话错误:', error); - showError('清空对话时发生错误'); - } -}); - -// 流式发送消息 -async function streamMessage(message) { - updateConnectionStatus(true); - - // 创建助手消息元素 - const assistantMessageElement = createAssistantMessage(); - - try { - const response = await fetch(`/api/chat/stream?conversationId=${conversationId}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ message }) - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let currentContent = ''; - - while (true) { - const { done, value } = await reader.read(); - - if (done) break; - - const chunk = decoder.decode(value); - const events = parseSSE(chunk); - - for (const event of events) { - if (event.type === 'text') { - const data = JSON.parse(event.data); - const content = data.content; - currentContent += content; - updateAssistantMessage(assistantMessageElement, currentContent); - } else if (event.type === 'error') { - const data = JSON.parse(event.data); - showError(data.message); - } - } - } - - // 滚动到底部 - scrollToBottom(); - - } catch (error) { - console.error('流式响应错误:', error); - showError('连接错误: ' + error.message); - assistantMessageElement.remove(); - } finally { - updateConnectionStatus(false); - } -} - -// 伪流式发送消息(支持工具调用的实时展示) -async function streamMessageWithTools(message) { - updateConnectionStatus(true); - - try { - const response = await fetch(`/api/chat/stream-with-tools?conversationId=${conversationId}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ message }) - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const reader = response.body.getReader(); - const decoder = new TextDecoder(); - let buffer = ''; - let assistantMessageElement = null; - - while (true) { - const { done, value } = await reader.read(); - - if (done) break; - - buffer += decoder.decode(value, { stream: true }); - const lines = buffer.split('\n\n'); - buffer = lines.pop(); // 保留不完整的行 - - for (const line of lines) { - if (!line.trim()) continue; - - const eventMatch = line.match(/event: (\w+)/); - const dataMatch = line.match(/data: (.+)/); - - if (eventMatch && dataMatch) { - const eventType = eventMatch[1]; - const data = JSON.parse(dataMatch[1]); - - // 根据事件类型处理 - switch(eventType) { - case 'user_message': - // 用户消息已经显示,跳过 - break; - - case 'tool_call': - // 特殊处理 TodoWrite 工具调用 - if (data.tool_name === 'TodoWrite') { - appendTodoWriteCall(data.arguments); - } else { - // 显示普通工具调用 - appendToolCall(data.tool_name, data.arguments); - } - break; - - case 'tool_response': - // 特殊处理 TodoWrite 工具响应 - if (data.tool_name === 'TodoWrite') { - appendTodoWriteProgress(data.response); - } else { - // 显示普通工具响应 - appendToolResult(data.tool_name, data.response); - } - break; - - case 'assistant_message': - // 每个 AI 响应都创建新的元素 - const newAssistantElement = createAssistantMessageWithoutLoading(); - updateAssistantMessage(newAssistantElement, data.content); - break; - - case 'final_response': - // 最终响应也创建新的元素 - const finalAssistantElement = createAssistantMessageWithoutLoading(); - updateAssistantMessage(finalAssistantElement, data.content); - break; - - case 'error': - // 显示错误 - showError(data.message); - break; - } - } - } - } - - scrollToBottom(); - - } catch (error) { - console.error('伪流式响应错误:', error); - showError('连接错误: ' + error.message); - } finally { - updateConnectionStatus(false); - } -} - -// 非流式发送消息(支持工具调用)- 已废弃,保留用于兼容 -async function sendMessageWithTools(message) { - updateConnectionStatus(true); - - try { - const response = await fetch(`/api/chat/chat?conversationId=${conversationId}`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ message }) - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - let content = await response.text(); - - // 提取工具调用信息 - let toolCalls = null; - if (content.includes('__TOOL_CALLS__:')) { - const parts = content.split('__TOOL_CALLS__:'); - content = parts[0].trim(); // 移除末尾的空白 - try { - toolCalls = JSON.parse(parts[1]); - } catch (e) { - console.error('解析工具调用信息失败:', e); - } - } - - // 先显示工具调用(如果有) - if (toolCalls && toolCalls.length > 0) { - toolCalls.forEach(toolCall => { - if (toolCall.type === 'tool_call') { - appendToolCall(toolCall.name, toolCall.arguments); - } else if (toolCall.type === 'tool_result' && toolCall.result) { - appendToolResult(toolCall.name, toolCall.result); - } - }); - } - - // 然后显示 AI 回复 - const assistantMessageElement = createAssistantMessageWithoutLoading(); - updateAssistantMessage(assistantMessageElement, content); - - scrollToBottom(); - - } catch (error) { - console.error('工具调用错误:', error); - showError('连接错误: ' + error.message); - } finally { - updateConnectionStatus(false); - } -} - -// 创建助手消息元素(不显示加载动画) -function createAssistantMessageWithoutLoading() { - const messageDiv = document.createElement('div'); - messageDiv.className = 'message assistant'; - - const contentDiv = document.createElement('div'); - contentDiv.className = 'message-content'; - - messageDiv.appendChild(contentDiv); - messagesContainer.appendChild(messageDiv); - - scrollToBottom(); - - return messageDiv; -} - -// 显示工具调用(已废弃,直接在 sendMessageWithTools 中处理) - -// 添加 TodoWrite 工具调用展示 -function appendTodoWriteCall(arguments) { - try { - // 解析参数中的 todos - let todos = []; - if (typeof arguments === 'string') { - const data = JSON.parse(arguments); - // 处理嵌套结构:{todos: {todos: [...]}} 或 {todos: [...]} - if (data.todos) { - if (data.todos.todos) { - // 嵌套结构 - todos = data.todos.todos; - } else if (Array.isArray(data.todos)) { - // 直接数组 - todos = data.todos; - } - } - } else if (arguments.todos) { - if (arguments.todos.todos) { - // 嵌套结构 - todos = arguments.todos.todos; - } else if (Array.isArray(arguments.todos)) { - // 直接数组 - todos = arguments.todos; - } - } - - if (todos.length === 0) { - // 如果无法解析,显示简单标题 - const todoCallDiv = document.createElement('div'); - todoCallDiv.className = 'todo-write-call'; - const headerDiv = document.createElement('div'); - headerDiv.className = 'todo-write-header'; - headerDiv.innerHTML = '📋 任务列表'; - todoCallDiv.appendChild(headerDiv); - messagesContainer.appendChild(todoCallDiv); - scrollToBottom(); - return; - } - - // 创建任务列表展示 - const todoCallDiv = document.createElement('div'); - todoCallDiv.className = 'todo-write-call'; - - const headerDiv = document.createElement('div'); - headerDiv.className = 'todo-write-header'; - headerDiv.innerHTML = '📋 任务列表'; - - // 任务列表 - const todoListDiv = document.createElement('div'); - todoListDiv.className = 'todo-list'; - - todos.forEach(todo => { - const todoItem = document.createElement('div'); - todoItem.className = `todo-item todo-${todo.status}`; - - let statusIcon = '[ ]'; - if (todo.status === 'completed') { - statusIcon = '[✓]'; - } else if (todo.status === 'in_progress') { - statusIcon = '[→]'; - } - - todoItem.innerHTML = `${statusIcon} ${todo.content}`; - todoListDiv.appendChild(todoItem); - }); - - todoCallDiv.appendChild(headerDiv); - todoCallDiv.appendChild(todoListDiv); - messagesContainer.appendChild(todoCallDiv); - scrollToBottom(); - - } catch (error) { - console.error('解析 TodoWrite 参数失败:', error); - // 降级到简单展示 - const todoCallDiv = document.createElement('div'); - todoCallDiv.className = 'todo-write-call'; - const headerDiv = document.createElement('div'); - headerDiv.className = 'todo-write-header'; - headerDiv.innerHTML = '📋 任务列表'; - todoCallDiv.appendChild(headerDiv); - messagesContainer.appendChild(todoCallDiv); - scrollToBottom(); - } -} - -// 添加 TodoWrite 进度展示 -function appendTodoWriteProgress(response) { - try { - // 尝试解析 JSON 响应 - let todos = []; - if (typeof response === 'string') { - // 如果响应包含 JSON,尝试提取 - const jsonMatch = response.match(/\{[\s\S]*"todos"[\s\S]*\}/); - if (jsonMatch) { - const data = JSON.parse(jsonMatch[0]); - // 处理嵌套结构:{todos: {todos: [...]}} 或 {todos: [...]} - if (data.todos) { - if (data.todos.todos) { - // 嵌套结构 - todos = data.todos.todos; - } else if (Array.isArray(data.todos)) { - // 直接数组 - todos = data.todos; - } - } - } - } else if (response.todos) { - if (response.todos.todos) { - // 嵌套结构 - todos = response.todos.todos; - } else if (Array.isArray(response.todos)) { - // 直接数组 - todos = response.todos; - } - } - - if (todos.length === 0) { - // 如果无法解析,显示原始响应 - appendToolResult('TodoWrite', response); - return; - } - - // 计算进度 - const total = todos.length; - const completed = todos.filter(t => t.status === 'completed').length; - const inProgress = todos.filter(t => t.status === 'in_progress').length; - const percentage = total > 0 ? Math.round((completed / total) * 100) : 0; - - // 创建进度展示元素 - const progressDiv = document.createElement('div'); - progressDiv.className = 'todo-write-progress'; - - // 进度头部 - const headerDiv = document.createElement('div'); - headerDiv.className = 'todo-progress-header'; - headerDiv.innerHTML = `📊 任务进度: ${completed}/${total} 已完成 (${percentage}%)`; - - // 进度条 - const progressBarContainer = document.createElement('div'); - progressBarContainer.className = 'progress-bar-container'; - - const progressBar = document.createElement('div'); - progressBar.className = 'progress-bar'; - progressBar.style.width = `${percentage}%`; - - progressBarContainer.appendChild(progressBar); - - // 任务列表 - const todoListDiv = document.createElement('div'); - todoListDiv.className = 'todo-list'; - - todos.forEach(todo => { - const todoItem = document.createElement('div'); - todoItem.className = `todo-item todo-${todo.status}`; - - let statusIcon = '[ ]'; - if (todo.status === 'completed') { - statusIcon = '[✓]'; - } else if (todo.status === 'in_progress') { - statusIcon = '[→]'; - } - - todoItem.innerHTML = `${statusIcon} ${todo.content}`; - todoListDiv.appendChild(todoItem); - }); - - progressDiv.appendChild(headerDiv); - progressDiv.appendChild(progressBarContainer); - progressDiv.appendChild(todoListDiv); - - messagesContainer.appendChild(progressDiv); - scrollToBottom(); - - } catch (error) { - console.error('解析 TodoWrite 响应失败:', error); - // 降级到普通工具响应展示 - appendToolResult('TodoWrite', response); - } -} - -// 添加工具调用展示 -function appendToolCall(name, arguments) { - const toolCallDiv = document.createElement('div'); - toolCallDiv.className = 'tool-call'; - - const headerDiv = document.createElement('div'); - headerDiv.className = 'tool-call-header'; - headerDiv.innerHTML = '⚙️ 调用工具: ' + name; - - const detailsDiv = document.createElement('div'); - detailsDiv.className = 'tool-call-details'; - - // 格式化参数显示 - let argsText = ''; - if (typeof arguments === 'string') { - argsText = arguments; - } else { - argsText = JSON.stringify(arguments, null, 2); - } - detailsDiv.textContent = '参数: ' + argsText; - - toolCallDiv.appendChild(headerDiv); - toolCallDiv.appendChild(detailsDiv); - - messagesContainer.appendChild(toolCallDiv); - scrollToBottom(); -} - -// 添加工具结果展示 -function appendToolResult(name, result) { - const toolResultDiv = document.createElement('div'); - toolResultDiv.className = 'tool-result'; - - const headerDiv = document.createElement('div'); - headerDiv.className = 'tool-result-header'; - headerDiv.innerHTML = '📄 工具返回: ' + name; - - const contentDiv = document.createElement('div'); - contentDiv.className = 'tool-result-content'; - - // 格式化结果显示 - let resultText = ''; - if (typeof result === 'string') { - resultText = result; - } else { - resultText = JSON.stringify(result, null, 2); - } - contentDiv.textContent = resultText; - - toolResultDiv.appendChild(headerDiv); - toolResultDiv.appendChild(contentDiv); - - messagesContainer.appendChild(toolResultDiv); - scrollToBottom(); -} - -// 解析 SSE 事件 -function parseSSE(chunk) { - const events = []; - const lines = chunk.split('\n'); - - let currentEvent = { type: '', data: '' }; - - for (const line of lines) { - if (line.startsWith('event: ')) { - currentEvent.type = line.substring(7); - } else if (line.startsWith('data: ')) { - currentEvent.data = line.substring(6); - - if (currentEvent.type && currentEvent.data) { - events.push({ ...currentEvent }); - currentEvent = { type: '', data: '' }; - } - } - } - - return events; -} - -// 添加消息到界面 -function appendMessage(role, content) { - const messageDiv = document.createElement('div'); - messageDiv.className = `message ${role}`; - - const contentDiv = document.createElement('div'); - contentDiv.className = 'message-content'; - - if (role === 'assistant') { - // 渲染 Markdown - const htmlContent = marked.parse(content); - const cleanHtml = DOMPurify.sanitize(htmlContent); - contentDiv.innerHTML = cleanHtml; - - // 高亮代码块并添加复制按钮 - setTimeout(() => { - contentDiv.querySelectorAll('pre code').forEach((block) => { - hljs.highlightElement(block); - - // 添加复制按钮 - const pre = block.parentElement; - const copyBtn = document.createElement('button'); - copyBtn.className = 'copy-button'; - copyBtn.textContent = '复制'; - - copyBtn.addEventListener('click', async () => { - try { - await navigator.clipboard.writeText(block.textContent); - copyBtn.textContent = '已复制!'; - copyBtn.classList.add('copied'); - - setTimeout(() => { - copyBtn.textContent = '复制'; - copyBtn.classList.remove('copied'); - }, 2000); - } catch (err) { - console.error('复制失败:', err); - copyBtn.textContent = '复制失败'; - } - }); - - pre.style.position = 'relative'; - pre.appendChild(copyBtn); - }); - }, 0); - } else { - // 用户消息不渲染 Markdown - contentDiv.textContent = content; - } - - messageDiv.appendChild(contentDiv); - messagesContainer.appendChild(messageDiv); - - scrollToBottom(); -} - -// 创建助手消息元素 -function createAssistantMessage() { - const messageDiv = document.createElement('div'); - messageDiv.className = 'message assistant'; - - const contentDiv = document.createElement('div'); - contentDiv.className = 'message-content'; - contentDiv.innerHTML = '
'; - - messageDiv.appendChild(contentDiv); - messagesContainer.appendChild(messageDiv); - - scrollToBottom(); - - return messageDiv; -} - -// 更新助手消息内容 -function updateAssistantMessage(messageElement, content) { - const contentDiv = messageElement.querySelector('.message-content'); - - // 渲染 Markdown - const htmlContent = marked.parse(content); - - // 清理 HTML(防止 XSS 攻击) - const cleanHtml = DOMPurify.sanitize(htmlContent); - - contentDiv.innerHTML = cleanHtml; - - // 高亮代码块并添加复制按钮 - contentDiv.querySelectorAll('pre code').forEach((block) => { - hljs.highlightElement(block); - - // 添加复制按钮 - const pre = block.parentElement; - const copyBtn = document.createElement('button'); - copyBtn.className = 'copy-button'; - copyBtn.textContent = '复制'; - - copyBtn.addEventListener('click', async () => { - try { - await navigator.clipboard.writeText(block.textContent); - copyBtn.textContent = '已复制!'; - copyBtn.classList.add('copied'); - - setTimeout(() => { - copyBtn.textContent = '复制'; - copyBtn.classList.remove('copied'); - }, 2000); - } catch (err) { - console.error('复制失败:', err); - copyBtn.textContent = '复制失败'; - } - }); - - pre.style.position = 'relative'; - pre.appendChild(copyBtn); - }); - - scrollToBottom(); -} - -// 显示错误消息 -function showError(message) { - const errorDiv = document.createElement('div'); - errorDiv.className = 'error-message'; - errorDiv.textContent = '❌ 错误: ' + message; - - messagesContainer.appendChild(errorDiv); - scrollToBottom(); - - // 3秒后自动移除 - setTimeout(() => { - errorDiv.remove(); - }, 3000); -} - -// 更新连接状态 -function updateConnectionStatus(connected) { - if (connected) { - connectionStatus.textContent = '已连接'; - connectionStatus.className = 'status-indicator connected'; - } else { - connectionStatus.textContent = '未连接'; - connectionStatus.className = 'status-indicator disconnected'; - } -} - -// 滚动到底部 -function scrollToBottom() { - messagesContainer.scrollTop = messagesContainer.scrollHeight; -} - -// 页面加载时聚焦输入框 -window.addEventListener('load', () => { - userInput.focus(); - - // 配置 marked.js - marked.setOptions({ - breaks: true, // 支持 GFM 换行 - gfm: true, // 启用 GitHub Flavored Markdown - highlight: function(code, lang) { - if (lang && hljs.getLanguage(lang)) { - try { - return hljs.highlight(code, { language: lang }).value; - } catch (err) { - console.error('代码高亮错误:', err); - } - } - return hljs.highlightAuto(code).value; - } - }); - - // 添加欢迎消息 - const welcomeMessage = `## 👋 欢迎使用 Spring AI Skills Chat - -我可以帮助你完成各种任务,包括: - -- 💬 **普通对话**(关闭"启用工具调用"使用传统流式响应) -- 🔧 **执行 Shell 命令** -- 📁 **读写文件** -- 🎯 **使用自定义 Skills** -- 📋 **任务管理**(TodoWrite) - -### 🌟 新功能:伪流式接口 - -开启"启用工具调用"后,你可以实时看到: -- 🔧 **工具调用**:AI 调用了哪些工具 -- ✅ **工具响应**:工具返回了什么结果 -- 💬 **AI 思考**:AI 的中间思考过程 -- 📊 **执行步骤**:完整的执行流程可视化 - -### 快速开始: - -1. **开启工具调用**:点击右上角的"启用工具调用"开关 -2. **发送指令**:例如"请帮我为某某公司执行完整的定价流程" -3. **实时观察**:工具调用和执行步骤会实时展示 - -现在就开始吧!🚀`; - - const assistantDiv = document.createElement('div'); - assistantDiv.className = 'message assistant'; - const contentDiv = document.createElement('div'); - contentDiv.className = 'message-content'; - - const htmlContent = marked.parse(welcomeMessage); - const cleanHtml = DOMPurify.sanitize(htmlContent); - contentDiv.innerHTML = cleanHtml; - - setTimeout(() => { - contentDiv.querySelectorAll('pre code').forEach((block) => { - hljs.highlightElement(block); - }); - }, 0); - - assistantDiv.appendChild(contentDiv); - messagesContainer.appendChild(assistantDiv); -}); - -// 页面卸载时保存会话 ID -window.addEventListener('beforeunload', () => { - localStorage.setItem('conversationId', conversationId); -});