Files
spring-ai-skill/src/main/resources/static/js/chat-main.js
T
hughhuangandClaude Sonnet 4.5 fd09a55614 feat: 实现会话管理和 AI 回复保存功能
## 新增功能
- 实现会话持久化存储(JSON 文件)
- 支持会话列表显示、切换、创建、删除
- 自动保存用户消息和 AI 回复
- 优化 Markdown 渲染样式(标题、列表、代码块、表格等)
- 添加过程数据可视化(思考步骤、工具调用、响应)

## 技术改进
- 新增 ConversationMessage、ConversationMetadata 模型
- 新增 ConversationStorageService 服务(JSON 文件存储)
- 在 ChatService 中添加流式响应完成后保存 AI 回复的逻辑
- 优化删除会话逻辑:删除当前会话后切换到现有会话,而非自动创建新会话
- 优化应用初始化:优先使用现有会话,仅在没有会话时才创建新会话

## 依赖更新
- 添加 jackson-datatype-jsr310 支持 Java 8 DateTime

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-31 22:03:28 +08:00

299 lines
8.4 KiB
JavaScript

/**
* 主程序入口
* 整合所有模块,处理事件绑定和业务流程
*/
const ChatApp = {
conversationId: null,
isProcessing: false,
/**
* 初始化应用
*/
async init() {
// 初始化 DOM 元素
ChatUI.init();
// 先加载会话列表
const conversations = await ChatAPI.listConversations();
// 初始化会话 ID
const localConvId = ChatUtils.getOrCreateConversationId();
// 检查本地会话是否存在
const existingConv = await ChatAPI.getConversation(localConvId);
if (existingConv) {
// 本地会话存在,使用它
this.conversationId = localConvId;
ChatAPI.init(this.conversationId);
} else if (conversations.length > 0) {
// 本地会话不存在,但有其他会话,使用最近的会话
this.conversationId = conversations[0].id;
ChatAPI.init(this.conversationId);
// 更新本地存储
localStorage.setItem('conversationId', this.conversationId);
} else {
// 没有任何会话,创建新会话
const newConv = await ChatAPI.createConversation('新对话');
this.conversationId = newConv.id;
}
// 绑定事件
this.bindEvents();
// 加载会话列表(更新选中状态)
await ChatUI.loadConversationList();
// 加载当前会话的历史消息
await this.loadCurrentConversation();
console.log('ChatApp 初始化完成,当前会话:', this.conversationId);
},
/**
* 绑定所有事件
*/
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());
// 工具开关变化
ui.toolToggle.addEventListener('change', () => {
const enabled = ui.toolToggle.checked;
console.log('工具调用已', enabled ? '开启' : '关闭');
});
// 页面卸载前保存会话 ID
window.addEventListener('beforeunload', () => {
localStorage.setItem('conversationId', this.conversationId);
});
},
/**
* 加载当前会话的历史消息
*/
async loadCurrentConversation() {
try {
const messages = await ChatAPI.getMessages(this.conversationId);
// 清空现有消息
ChatUI.elements.messagesContainer.innerHTML = '';
// 如果有历史消息,渲染它们
if (messages && messages.length > 0) {
messages.forEach(msg => {
if (msg.role === 'user') {
ChatUI.renderUserMessage(msg.content);
} else if (msg.role === 'assistant') {
ChatUI.renderAssistantMessage(msg.content);
}
});
} else {
// 没有消息则显示欢迎界面
ChatUI.clearMessages();
}
} catch (error) {
console.error('加载当前会话失败:', error);
ChatUI.clearMessages();
}
},
/**
* 处理表单提交
*/
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);
}
// 刷新会话列表(更新时间和消息数)
await ChatUI.loadConversationList();
// 恢复输入状态
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);
// 创建 AI 消息容器
ChatUI.createAssistantMessageContainer();
let content = '';
try {
for await (const event of ChatAPI.streamMessage(message)) {
if (event.type === 'text') {
content += event.content;
} else if (event.type === 'error') {
ChatUI.showError(event.message);
}
}
// 设置最终回复
ChatUI.setFinalResponse(content);
} catch (error) {
console.error('流式响应错误:', error);
ChatUI.showError('连接错误: ' + error.message);
} finally {
ChatUI.updateConnectionStatus(false);
}
},
/**
* 处理伪流式响应(支持工具调用)
*/
async handleStreamWithTools(message) {
ChatUI.updateConnectionStatus(true);
// 创建 AI 消息容器
ChatUI.createAssistantMessageContainer();
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.addThinkingStep(data.content);
break;
case 'final_response':
// 设置最终回复
ChatUI.setFinalResponse(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.addToolCallStep(tool_name, args, isTodoWrite);
},
/**
* 处理工具响应
*/
handleToolResponse(data) {
const { tool_name, response } = data;
const isTodoWrite = tool_name === 'TodoWrite';
ChatUI.addToolResponseStep(tool_name, response, isTodoWrite);
},
/**
* 处理清空对话
*/
async handleClear() {
if (!confirm('确定要清空对话吗?')) return;
try {
await ChatAPI.clearConversation();
// 生成新会话 ID
this.conversationId = ChatAPI.regenerateConversationId();
// 清空界面
ChatUI.clearMessages();
// 刷新列表
await ChatUI.loadConversationList();
// 显示重置消息
ChatUI.createAssistantMessageContainer();
ChatUI.setFinalResponse('对话已清空,我们可以重新开始!');
} catch (error) {
console.error('清空对话错误:', error);
ChatUI.showError('清空对话失败: ' + error.message);
}
}
};
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
ChatApp.init();
});
// 导出(用于测试)
window.ChatApp = ChatApp;