Files
spring-ai-skill/src/main/resources/static/js/chat-main.js
T

298 lines
8.4 KiB
JavaScript
Raw Normal View History

/**
* 主程序入口
* 整合所有模块,处理事件绑定和业务流程
*/
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;