From fd09a55614c41575aa0c8651733d96a3afa32248 Mon Sep 17 00:00:00 2001 From: hugh <1012760428@qq.com> Date: Sat, 31 Jan 2026 22:03:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E5=92=8C=20AI=20=E5=9B=9E=E5=A4=8D=E4=BF=9D?= =?UTF-8?q?=E5=AD=98=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 新增功能 - 实现会话持久化存储(JSON 文件) - 支持会话列表显示、切换、创建、删除 - 自动保存用户消息和 AI 回复 - 优化 Markdown 渲染样式(标题、列表、代码块、表格等) - 添加过程数据可视化(思考步骤、工具调用、响应) ## 技术改进 - 新增 ConversationMessage、ConversationMetadata 模型 - 新增 ConversationStorageService 服务(JSON 文件存储) - 在 ChatService 中添加流式响应完成后保存 AI 回复的逻辑 - 优化删除会话逻辑:删除当前会话后切换到现有会话,而非自动创建新会话 - 优化应用初始化:优先使用现有会话,仅在没有会话时才创建新会话 ## 依赖更新 - 添加 jackson-datatype-jsr310 支持 Java 8 DateTime Co-Authored-By: Claude Sonnet 4.5 --- .gitignore | 3 + pom.xml | 6 + .../skills/controller/ChatController.java | 118 +- .../skills/model/ConversationMessage.java | 64 + .../skills/model/ConversationMetadata.java | 67 + .../skills/service/ChatService.java | 25 +- .../service/ConversationStorageService.java | 227 ++ src/main/resources/static/css/style.css | 2162 +++++++++++------ src/main/resources/static/js/chat-api.js | 80 + src/main/resources/static/js/chat-main.js | 135 +- src/main/resources/static/js/chat-ui.js | 803 ++++-- 11 files changed, 2697 insertions(+), 993 deletions(-) create mode 100644 src/main/java/org/springaicommunity/skills/model/ConversationMessage.java create mode 100644 src/main/java/org/springaicommunity/skills/model/ConversationMetadata.java create mode 100644 src/main/java/org/springaicommunity/skills/service/ConversationStorageService.java diff --git a/.gitignore b/.gitignore index 30bfc6c..d081433 100644 --- a/.gitignore +++ b/.gitignore @@ -33,4 +33,7 @@ target/ # Claude Code local settings .claude/ +# Conversation storage +conversations/ + spring-ai-agent-util-examples/ \ No newline at end of file diff --git a/pom.xml b/pom.xml index fe280f4..1e9ce64 100644 --- a/pom.xml +++ b/pom.xml @@ -80,6 +80,12 @@ org.springframework.boot spring-boot-starter-actuator + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + diff --git a/src/main/java/org/springaicommunity/skills/controller/ChatController.java b/src/main/java/org/springaicommunity/skills/controller/ChatController.java index 3340c25..0fbdea2 100644 --- a/src/main/java/org/springaicommunity/skills/controller/ChatController.java +++ b/src/main/java/org/springaicommunity/skills/controller/ChatController.java @@ -1,17 +1,15 @@ package org.springaicommunity.skills.controller; +import java.util.List; +import java.util.Map; import java.util.UUID; import org.springaicommunity.skills.model.ChatRequest; import org.springaicommunity.skills.service.ChatService; +import org.springaicommunity.skills.service.ConversationStorageService; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; @@ -20,9 +18,11 @@ import reactor.core.publisher.Flux; public class ChatController { private final ChatService chatService; + private final ConversationStorageService storageService; - public ChatController(ChatService chatService) { + public ChatController(ChatService chatService, ConversationStorageService storageService) { this.chatService = chatService; + this.storageService = storageService; } /** @@ -33,6 +33,11 @@ public class ChatController { @RequestParam(required = false) String conversationId, @RequestBody ChatRequest request) { String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString(); + + // 保存用户消息 + storageService.saveMessage(finalConversationId, + new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage())); + return chatService.chatStream(finalConversationId, request.getMessage()); } @@ -44,7 +49,21 @@ public class ChatController { @RequestParam(required = false) String conversationId, @RequestBody ChatRequest request) { String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString(); - return chatService.chatStreamWithTools(finalConversationId, request.getMessage()); + + // 保存用户消息 + storageService.saveMessage(finalConversationId, + new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage())); + + return chatService.chatStreamWithTools(finalConversationId, request.getMessage()) + .doOnComplete(() -> { + // 流完成后,从内存中加载会话历史并保存 + // 注意:这里需要从 ChatMemory 或其他地方获取完整的对话 + // 暂时简化处理 + logger.info("会话流完成: {}", finalConversationId); + }) + .doOnError(error -> { + logger.error("会话流错误: {}", error.getMessage()); + }); } /** @@ -55,7 +74,17 @@ public class ChatController { @RequestParam(required = false) String conversationId, @RequestBody ChatRequest request) { String finalConversationId = conversationId != null ? conversationId : UUID.randomUUID().toString(); + + // 保存用户消息 + storageService.saveMessage(finalConversationId, + new org.springaicommunity.skills.model.ConversationMessage("user", request.getMessage())); + String response = chatService.chat(finalConversationId, request.getMessage()); + + // 保存 AI 响应 + storageService.saveMessage(finalConversationId, + new org.springaicommunity.skills.model.ConversationMessage("assistant", response)); + return ResponseEntity.ok(response); } @@ -65,6 +94,79 @@ public class ChatController { @DeleteMapping("/clear") public ResponseEntity clear(@RequestParam String conversationId) { chatService.clear(conversationId); + storageService.deleteConversation(conversationId); return ResponseEntity.ok("Conversation cleared: " + conversationId); } + + // ==================== 会话管理 API ==================== + + /** + * 获取所有会话列表 + */ + @GetMapping("/conversations") + public ResponseEntity> listConversations() { + return ResponseEntity.ok(storageService.listConversations()); + } + + /** + * 创建新会话 + */ + @PostMapping("/conversations") + public ResponseEntity createConversation( + @RequestBody Map request) { + String title = request.getOrDefault("title", "新对话"); + org.springaicommunity.skills.model.ConversationMetadata metadata = storageService.createConversation(title); + return ResponseEntity.ok(metadata); + } + + /** + * 获取会话消息 + */ + @GetMapping("/conversations/{conversationId}/messages") + public ResponseEntity> getMessages( + @PathVariable String conversationId) { + return ResponseEntity.ok(storageService.loadMessages(conversationId)); + } + + /** + * 获取会话元数据 + */ + @GetMapping("/conversations/{conversationId}") + public ResponseEntity getConversation( + @PathVariable String conversationId) { + org.springaicommunity.skills.model.ConversationMetadata metadata = storageService.getMetadata(conversationId); + if (metadata == null) { + return ResponseEntity.notFound().build(); + } + return ResponseEntity.ok(metadata); + } + + /** + * 更新会话标题 + */ + @PutMapping("/conversations/{conversationId}") + public ResponseEntity updateConversation( + @PathVariable String conversationId, + @RequestBody Map request) { + String title = request.get("title"); + if (title != null) { + storageService.updateTitle(conversationId, title); + } + return ResponseEntity.ok().build(); + } + + /** + * 删除会话 + */ + @DeleteMapping("/conversations/{conversationId}") + public ResponseEntity deleteConversation(@PathVariable String conversationId) { + boolean deleted = storageService.deleteConversation(conversationId); + if (deleted) { + return ResponseEntity.ok().build(); + } + return ResponseEntity.notFound().build(); + } + + private static final org.slf4j.Logger logger = + org.slf4j.LoggerFactory.getLogger(ChatController.class); } diff --git a/src/main/java/org/springaicommunity/skills/model/ConversationMessage.java b/src/main/java/org/springaicommunity/skills/model/ConversationMessage.java new file mode 100644 index 0000000..8778017 --- /dev/null +++ b/src/main/java/org/springaicommunity/skills/model/ConversationMessage.java @@ -0,0 +1,64 @@ +package org.springaicommunity.skills.model; + +import java.time.LocalDateTime; + +/** + * 会话消息模型 + */ +public class ConversationMessage { + + private String role; // user 或 assistant + private String content; // 消息内容 + private LocalDateTime timestamp; // 时间戳 + private String type; // 消息类型:text, tool_call, tool_response + + public ConversationMessage() { + } + + public ConversationMessage(String role, String content) { + this.role = role; + this.content = content; + this.timestamp = LocalDateTime.now(); + this.type = "text"; + } + + public ConversationMessage(String role, String content, String type) { + this.role = role; + this.content = content; + this.timestamp = LocalDateTime.now(); + this.type = type; + } + + // Getters and Setters + public String getRole() { + return role; + } + + public void setRole(String role) { + this.role = role; + } + + public String getContent() { + return content; + } + + public void setContent(String content) { + this.content = content; + } + + public LocalDateTime getTimestamp() { + return timestamp; + } + + public void setTimestamp(LocalDateTime timestamp) { + this.timestamp = timestamp; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/src/main/java/org/springaicommunity/skills/model/ConversationMetadata.java b/src/main/java/org/springaicommunity/skills/model/ConversationMetadata.java new file mode 100644 index 0000000..bd15f42 --- /dev/null +++ b/src/main/java/org/springaicommunity/skills/model/ConversationMetadata.java @@ -0,0 +1,67 @@ +package org.springaicommunity.skills.model; + +import java.time.LocalDateTime; + +/** + * 会话元数据 + */ +public class ConversationMetadata { + + private String id; // 会话ID + private String title; // 会话标题 + private LocalDateTime createdAt; // 创建时间 + private LocalDateTime updatedAt; // 更新时间 + private int messageCount; // 消息数量 + + public ConversationMetadata() { + } + + public ConversationMetadata(String id, String title) { + this.id = id; + this.title = title; + this.createdAt = LocalDateTime.now(); + this.updatedAt = LocalDateTime.now(); + this.messageCount = 0; + } + + // Getters and Setters + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public LocalDateTime getCreatedAt() { + return createdAt; + } + + public void setCreatedAt(LocalDateTime createdAt) { + this.createdAt = createdAt; + } + + public LocalDateTime getUpdatedAt() { + return updatedAt; + } + + public void setUpdatedAt(LocalDateTime updatedAt) { + this.updatedAt = updatedAt; + } + + public int getMessageCount() { + return messageCount; + } + + public void setMessageCount(int messageCount) { + this.messageCount = messageCount; + } +} diff --git a/src/main/java/org/springaicommunity/skills/service/ChatService.java b/src/main/java/org/springaicommunity/skills/service/ChatService.java index dc65c62..30d24e2 100644 --- a/src/main/java/org/springaicommunity/skills/service/ChatService.java +++ b/src/main/java/org/springaicommunity/skills/service/ChatService.java @@ -21,16 +21,19 @@ public class ChatService { private final ChatClient.Builder chatClientBuilder; // 用于创建带自定义 Advisor 的客户端 private final ChatMemory chatMemory; private final ObjectMapper objectMapper; + private final ConversationStorageService storageService; public ChatService( @Qualifier("streamChatClient") ChatClient streamChatClient, @Qualifier("chatClient") ChatClient chatClient, @Qualifier("chatClientBuilder") ChatClient.Builder chatClientBuilder, - ChatMemory chatMemory) { + ChatMemory chatMemory, + ConversationStorageService storageService) { this.streamChatClient = streamChatClient; this.chatClient = chatClient; this.chatClientBuilder = chatClientBuilder; this.chatMemory = chatMemory; + this.storageService = storageService; this.objectMapper = new ObjectMapper(); } @@ -38,11 +41,27 @@ public class ChatService { * 流式聊天,返回 SSE 格式的响应(不支持工具调用) */ public Flux chatStream(String conversationId, String userMessage) { + // 收集完整内容用于保存 + StringBuilder fullContent = new StringBuilder(); + return streamChatClient.prompt() .user(userMessage) .advisors(a -> a.param("conversation_id", conversationId)) .stream() .content() + .doOnNext(chunk -> { + // 收集内容片段 + if (chunk != null) { + fullContent.append(chunk); + } + }) + .doOnComplete(() -> { + // 流完成时保存完整响应 + if (fullContent.length() > 0) { + storageService.saveMessage(conversationId, + new org.springaicommunity.skills.model.ConversationMessage("assistant", fullContent.toString())); + } + }) .map(this::mapToSSE); } @@ -81,6 +100,10 @@ public class ChatService { ); sink.tryEmitNext(finalEvent); + // 保存 AI 响应 + storageService.saveMessage(conversationId, + new org.springaicommunity.skills.model.ConversationMessage("assistant", content)); + // 完成流 sink.tryEmitComplete(); diff --git a/src/main/java/org/springaicommunity/skills/service/ConversationStorageService.java b/src/main/java/org/springaicommunity/skills/service/ConversationStorageService.java new file mode 100644 index 0000000..4ab664c --- /dev/null +++ b/src/main/java/org/springaicommunity/skills/service/ConversationStorageService.java @@ -0,0 +1,227 @@ +package org.springaicommunity.skills.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import jakarta.annotation.PostConstruct; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springaicommunity.skills.model.ConversationMessage; +import org.springaicommunity.skills.model.ConversationMetadata; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.nio.file.*; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * 会话存储服务 - 使用 JSON 文件存储会话数据 + */ +@Service +public class ConversationStorageService { + + private static final Logger logger = LoggerFactory.getLogger(ConversationStorageService.class); + + @Value("${conversation.storage.path:./conversations}") + private String storagePath; + + private Path storageDirectory; + private final ObjectMapper objectMapper; + + public ConversationStorageService() { + this.objectMapper = new ObjectMapper(); + this.objectMapper.registerModule(new JavaTimeModule()); + } + + @PostConstruct + public void init() { + try { + storageDirectory = Paths.get(storagePath); + if (!Files.exists(storageDirectory)) { + Files.createDirectories(storageDirectory); + logger.info("创建会话存储目录: {}", storageDirectory.toAbsolutePath()); + } + } catch (IOException e) { + logger.error("初始化会话存储目录失败: {}", e.getMessage(), e); + } + } + + /** + * 保存会话消息 + */ + public void saveMessage(String conversationId, ConversationMessage message) { + try { + Path messageFile = getMessageFilePath(conversationId); + List messages = loadMessages(conversationId); + messages.add(message); + + objectMapper.writerWithDefaultPrettyPrinter() + .writeValue(messageFile.toFile(), messages); + + // 更新元数据 + updateMetadata(conversationId, messages.size()); + + logger.debug("保存消息到会话 {}: {}", conversationId, message.getRole()); + } catch (IOException e) { + logger.error("保存消息失败: {}", e.getMessage(), e); + } + } + + /** + * 批量保存会话消息 + */ + public void saveMessages(String conversationId, List messages) { + try { + Path messageFile = getMessageFilePath(conversationId); + objectMapper.writerWithDefaultPrettyPrinter() + .writeValue(messageFile.toFile(), messages); + + updateMetadata(conversationId, messages.size()); + + logger.info("保存 {} 条消息到会话 {}", messages.size(), conversationId); + } catch (IOException e) { + logger.error("批量保存消息失败: {}", e.getMessage(), e); + } + } + + /** + * 加载会话消息 + */ + public List loadMessages(String conversationId) { + try { + Path messageFile = getMessageFilePath(conversationId); + if (!Files.exists(messageFile)) { + return new ArrayList<>(); + } + ConversationMessage[] array = objectMapper.readValue(messageFile.toFile(), ConversationMessage[].class); + return new ArrayList<>(Arrays.asList(array)); + } catch (IOException e) { + logger.error("加载消息失败: {}", e.getMessage(), e); + return new ArrayList<>(); + } + } + + /** + * 获取所有会话列表 + */ + public List listConversations() { + try (Stream paths = Files.list(storageDirectory)) { + return paths + .filter(path -> path.toString().endsWith("-metadata.json")) + .map(this::loadMetadata) + .filter(Objects::nonNull) + .sorted((a, b) -> b.getUpdatedAt().compareTo(a.getUpdatedAt())) + .collect(Collectors.toList()); + } catch (IOException e) { + logger.error("列出会话失败: {}", e.getMessage(), e); + return new ArrayList<>(); + } + } + + /** + * 获取会话元数据 + */ + public ConversationMetadata getMetadata(String conversationId) { + Path metadataFile = getMetadataFilePath(conversationId); + if (!Files.exists(metadataFile)) { + return null; + } + return loadMetadata(metadataFile); + } + + /** + * 创建新会话 + */ + public ConversationMetadata createConversation(String title) { + String id = UUID.randomUUID().toString(); + ConversationMetadata metadata = new ConversationMetadata(id, title); + saveMetadata(metadata); + return metadata; + } + + /** + * 删除会话 + */ + public boolean deleteConversation(String conversationId) { + try { + Path messageFile = getMessageFilePath(conversationId); + Path metadataFile = getMetadataFilePath(conversationId); + + boolean deleted = false; + if (Files.exists(messageFile)) { + Files.delete(messageFile); + deleted = true; + } + if (Files.exists(metadataFile)) { + Files.delete(metadataFile); + deleted = true; + } + + logger.info("删除会话 {}: {}", conversationId, deleted); + return deleted; + } catch (IOException e) { + logger.error("删除会话失败: {}", e.getMessage(), e); + return false; + } + } + + /** + * 更新会话标题 + */ + public void updateTitle(String conversationId, String title) { + ConversationMetadata metadata = getMetadata(conversationId); + if (metadata != null) { + metadata.setTitle(title); + metadata.setUpdatedAt(LocalDateTime.now()); + saveMetadata(metadata); + } + } + + // ==================== 私有方法 ==================== + + private Path getMessageFilePath(String conversationId) { + return storageDirectory.resolve(conversationId + "-messages.json"); + } + + private Path getMetadataFilePath(String conversationId) { + return storageDirectory.resolve(conversationId + "-metadata.json"); + } + + private void saveMetadata(ConversationMetadata metadata) { + try { + Path metadataFile = getMetadataFilePath(metadata.getId()); + objectMapper.writerWithDefaultPrettyPrinter() + .writeValue(metadataFile.toFile(), metadata); + } catch (IOException e) { + logger.error("保存元数据失败: {}", e.getMessage(), e); + } + } + + private ConversationMetadata loadMetadata(Path metadataFile) { + try { + return objectMapper.readValue(metadataFile.toFile(), ConversationMetadata.class); + } catch (IOException e) { + logger.error("加载元数据失败: {}", e.getMessage(), e); + return null; + } + } + + private void updateMetadata(String conversationId, int messageCount) { + ConversationMetadata metadata = getMetadata(conversationId); + if (metadata == null) { + // 如果没有元数据,创建一个默认的 + metadata = new ConversationMetadata(conversationId, "新对话 " + formatDate(LocalDateTime.now())); + } + metadata.setMessageCount(messageCount); + metadata.setUpdatedAt(LocalDateTime.now()); + saveMetadata(metadata); + } + + private String formatDate(LocalDateTime dateTime) { + return dateTime.format(DateTimeFormatter.ofPattern("MM-dd HH:mm")); + } +} diff --git a/src/main/resources/static/css/style.css b/src/main/resources/static/css/style.css index 7b94b49..ab2198a 100644 --- a/src/main/resources/static/css/style.css +++ b/src/main/resources/static/css/style.css @@ -1,518 +1,1018 @@ +/* ======================================== + Spring AI Skills Chat - Modern UI + Glassmorphism Design System + ======================================== */ + +/* CSS Variables */ +:root { + --primary: #6366f1; + --primary-light: #818cf8; + --primary-dark: #4f46e5; + --secondary: #10b981; + --accent: #f59e0b; + + --bg-primary: #0f172a; + --bg-secondary: #1e293b; + --bg-tertiary: #334155; + --bg-glass: rgba(30, 41, 59, 0.7); + --bg-glass-light: rgba(51, 65, 85, 0.5); + + --text-primary: #f8fafc; + --text-secondary: #cbd5e1; + --text-muted: #64748b; + + --border-color: rgba(148, 163, 184, 0.1); + --border-focus: rgba(99, 102, 241, 0.5); + + --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05); + --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1); + --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1); + --shadow-glow: 0 0 20px rgba(99, 102, 241, 0.3); + + --radius-sm: 6px; + --radius-md: 12px; + --radius-lg: 16px; + --radius-xl: 24px; + + --transition-fast: 150ms ease; + --transition-normal: 250ms ease; + --transition-slow: 350ms ease; + + --sidebar-width: 280px; + --header-height: 64px; + --input-area-height: auto; +} + +/* Reset & Base */ * { margin: 0; padding: 0; box-sizing: border-box; } -body { - font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - height: 100vh; - display: flex; - justify-content: center; - align-items: center; -} - -.container { - width: 100%; - max-width: 900px; - height: 100vh; - background: #ffffff; - display: flex; - flex-direction: column; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2); -} - -/* 头部样式 */ -.header { - padding: 20px 30px; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; - display: flex; - justify-content: space-between; - align-items: center; - box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); -} - -.header h1 { - font-size: 24px; - font-weight: 600; -} - -.header-controls { - display: flex; - align-items: center; - gap: 15px; -} - -.status-indicator { - padding: 6px 12px; - border-radius: 20px; +html, body { + height: 100%; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Inter', sans-serif; font-size: 14px; - font-weight: 500; -} - -.status-indicator.connected { - background: #10b981; - color: white; -} - -.status-indicator.disconnected { - background: #ef4444; - color: white; -} - -/* 消息区域 */ -.messages { - flex: 1; - overflow-y: auto; - padding: 30px; - display: flex; - flex-direction: column; - gap: 20px; - background: #f9fafb; -} - -.message { - display: flex; - gap: 12px; - animation: slideIn 0.3s ease-out; -} - -@keyframes slideIn { - from { - opacity: 0; - transform: translateY(10px); - } - to { - opacity: 1; - transform: translateY(0); - } -} - -.message.user { - justify-content: flex-end; -} - -.message-content { - max-width: 70%; - padding: 12px 18px; - border-radius: 12px; - line-height: 1.6; - word-wrap: break-word; -} - -.message.user .message-content { - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; - border-bottom-right-radius: 4px; -} - -.message.assistant .message-content { - background: white; - color: #1f2937; - border: 1px solid #e5e7eb; - border-bottom-left-radius: 4px; - box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1); -} - -/* Markdown 样式 */ -.message.assistant .message-content h1, -.message.assistant .message-content h2, -.message.assistant .message-content h3, -.message.assistant .message-content h4, -.message.assistant .message-content h5, -.message.assistant .message-content h6 { - margin-top: 16px; - margin-bottom: 8px; - font-weight: 600; - color: #111827; -} - -.message.assistant .message-content h1 { - font-size: 24px; - border-bottom: 2px solid #e5e7eb; - padding-bottom: 8px; -} - -.message.assistant .message-content h2 { - font-size: 20px; - border-bottom: 1px solid #e5e7eb; - padding-bottom: 6px; -} - -.message.assistant .message-content h3 { - font-size: 18px; -} - -.message.assistant .message-content p { - margin: 8px 0; - line-height: 1.6; -} - -.message.assistant .message-content ul, -.message.assistant .message-content ol { - margin: 8px 0; - padding-left: 24px; -} - -.message.assistant .message-content li { - margin: 4px 0; -} - -.message.assistant .message-content ul { - list-style-type: disc; -} - -.message.assistant .message-content ol { - list-style-type: decimal; -} - -.message.assistant .message-content code { - background: #f3f4f6; - padding: 2px 6px; - border-radius: 4px; - font-family: 'Courier New', monospace; - font-size: 14px; - color: #dc2626; -} - -.message.assistant .message-content pre { - background: #1e293b; - border-radius: 8px; - padding: 16px; - margin: 12px 0; - overflow-x: auto; - position: relative; -} - -.message.assistant .message-content pre .copy-button { - position: absolute; - top: 8px; - right: 8px; - background: rgba(255, 255, 255, 0.1); - color: white; - border: none; - border-radius: 4px; - padding: 4px 8px; - font-size: 12px; - cursor: pointer; - transition: background 0.2s; -} - -.message.assistant .message-content pre .copy-button:hover { - background: rgba(255, 255, 255, 0.2); -} - -.message.assistant .message-content pre .copy-button.copied { - background: #10b981; -} - -.message.assistant .message-content pre code { - background: transparent; - padding: 0; - color: #e2e8f0; - font-size: 13px; line-height: 1.5; -} - -.message.assistant .message-content blockquote { - border-left: 4px solid #667eea; - padding-left: 16px; - margin: 12px 0; - color: #6b7280; - font-style: italic; -} - -.message.assistant .message-content a { - color: #667eea; - text-decoration: none; -} - -.message.assistant .message-content a:hover { - text-decoration: underline; -} - -.message.assistant .message-content table { - border-collapse: collapse; - width: 100%; - margin: 12px 0; -} - -.message.assistant .message-content th, -.message.assistant .message-content td { - border: 1px solid #e5e7eb; - padding: 8px 12px; - text-align: left; -} - -.message.assistant .message-content th { - background: #f9fafb; - font-weight: 600; -} - -.message.assistant .message-content tr:hover { - background: #f9fafb; -} - -.message.assistant .message-content img { - max-width: 100%; - border-radius: 8px; - margin: 12px 0; -} - -.message.assistant .message-content hr { - border: none; - border-top: 2px solid #e5e7eb; - margin: 16px 0; -} - -/* 工具调用样式 */ -.tool-call { - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - border-radius: 12px; - padding: 16px; - margin: 12px 0; - box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2); - animation: slideIn 0.3s ease-out; -} - -/* TodoWrite 工具调用样式 */ -.todo-write-call { - background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); - border-radius: 12px; - padding: 16px; - margin: 12px 0; - box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2); - animation: slideIn 0.3s ease-out; -} - -.todo-write-header { - font-weight: 600; - color: white; - display: flex; - align-items: center; - gap: 8px; - font-size: 15px; -} - -/* TodoWrite 进度展示样式 */ -.todo-write-progress { - background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); - border-radius: 12px; - padding: 16px; - margin: 12px 0; - box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2); - animation: slideIn 0.3s ease-out; -} - -.todo-progress-header { - font-weight: 600; - color: white; - margin-bottom: 12px; - font-size: 15px; -} - -.progress-bar-container { - background: rgba(255, 255, 255, 0.3); - border-radius: 8px; - height: 8px; - margin-bottom: 12px; + color: var(--text-primary); + background: var(--bg-primary); overflow: hidden; } -.progress-bar { - background: white; - height: 100%; - border-radius: 8px; - transition: width 0.3s ease; +/* Scrollbar */ +::-webkit-scrollbar { + width: 6px; + height: 6px; } -.todo-list { - background: rgba(255, 255, 255, 0.95); - border-radius: 8px; +::-webkit-scrollbar-track { + background: transparent; +} + +::-webkit-scrollbar-thumb { + background: var(--bg-tertiary); + border-radius: 3px; +} + +::-webkit-scrollbar-thumb:hover { + background: var(--text-muted); +} + +/* App Layout */ +.app { + display: flex; + height: 100vh; + background: linear-gradient(135deg, var(--bg-primary) 0%, #1a1f2e 100%); +} + +/* ======================================== + Sidebar + ======================================== */ +.sidebar { + width: var(--sidebar-width); + display: flex; + flex-direction: column; + background: var(--bg-glass); + backdrop-filter: blur(20px); + border-right: 1px solid var(--border-color); + transition: transform var(--transition-normal); +} + +.sidebar-header { + padding: 20px; + border-bottom: 1px solid var(--border-color); +} + +.logo { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 16px; +} + +.logo-icon { + width: 32px; + height: 32px; + color: var(--primary-light); +} + +.logo-text { + font-size: 20px; + font-weight: 700; + background: linear-gradient(135deg, var(--primary-light), var(--secondary)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} + +.btn-new-chat { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + width: 100%; padding: 12px; + background: linear-gradient(135deg, var(--primary), var(--primary-dark)); + color: white; + border: none; + border-radius: var(--radius-md); + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all var(--transition-fast); } -.todo-item { - padding: 8px 12px; - margin: 4px 0; - border-radius: 6px; +.btn-new-chat:hover { + transform: translateY(-1px); + box-shadow: var(--shadow-glow); +} + +.sidebar-nav { + flex: 1; + padding: 16px; + overflow-y: auto; +} + +.nav-section { + margin-bottom: 24px; +} + +.nav-label { + display: block; + padding: 0 12px; + margin-bottom: 8px; + font-size: 12px; + font-weight: 500; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.nav-list { + list-style: none; +} + +.nav-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 12px; + border-radius: var(--radius-md); + cursor: pointer; + transition: all var(--transition-fast); + color: var(--text-secondary); +} + +.nav-item:hover { + background: var(--bg-glass-light); + color: var(--text-primary); +} + +.nav-item.active { + background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(16, 185, 129, 0.1)); + color: var(--primary-light); +} + +.nav-item-text { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.nav-item-empty { + padding: 20px 12px; + text-align: center; + color: var(--text-muted); + font-size: 13px; +} + +.btn-delete-conv { + width: 24px; + height: 24px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: none; + border-radius: var(--radius-sm); + color: var(--text-muted); + cursor: pointer; + opacity: 0; + transition: all var(--transition-fast); +} + +.nav-item:hover .btn-delete-conv { + opacity: 1; +} + +.btn-delete-conv:hover { + background: rgba(239, 68, 68, 0.2); + color: #f87171; +} + +.sidebar-footer { + padding: 16px 20px; + border-top: 1px solid var(--border-color); +} + +.connection-status { display: flex; align-items: center; gap: 8px; - font-size: 14px; - transition: background 0.2s; + font-size: 13px; + color: var(--text-secondary); } -.todo-item:hover { +.status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--secondary); + animation: pulse 2s infinite; +} + +/* ======================================== + Main Content + ======================================== */ +.main { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; +} + +/* Header */ +.header { + display: flex; + align-items: center; + justify-content: space-between; + height: var(--header-height); + padding: 0 24px; + background: var(--bg-glass); + backdrop-filter: blur(20px); + border-bottom: 1px solid var(--border-color); +} + +.header-left { + display: flex; + align-items: center; + gap: 16px; +} + +.menu-toggle { + display: none; +} + +.header-title { + font-size: 18px; + font-weight: 600; + color: var(--text-primary); +} + +.header-right { + display: flex; + align-items: center; + gap: 16px; +} + +/* Tool Toggle */ +.tool-toggle { + display: flex; + align-items: center; + gap: 10px; + cursor: pointer; +} + +.tool-toggle input { + display: none; +} + +.toggle-track { + position: relative; + width: 44px; + height: 24px; + background: var(--bg-tertiary); + border-radius: 12px; + transition: background var(--transition-fast); +} + +.tool-toggle input:checked + .toggle-track { + background: linear-gradient(135deg, var(--primary), var(--primary-dark)); +} + +.toggle-thumb { + position: absolute; + top: 2px; + left: 2px; + width: 20px; + height: 20px; + background: white; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: transform var(--transition-fast); +} + +.tool-toggle input:checked + .toggle-track .toggle-thumb { + transform: translateX(20px); +} + +.toggle-thumb i { + width: 12px; + height: 12px; + color: var(--primary); +} + +.toggle-label { + font-size: 13px; + color: var(--text-secondary); +} + +/* ======================================== + Chat Container + ======================================== */ +.chat-container { + flex: 1; + overflow: hidden; + position: relative; +} + +.messages { + height: 100%; + overflow-y: auto; + padding: 24px; + scroll-behavior: smooth; +} + +/* Welcome Message */ +.welcome-message { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + min-height: 60vh; + text-align: center; + animation: fadeInUp 0.6s ease; +} + +.welcome-icon { + width: 64px; + height: 64px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, var(--primary), var(--secondary)); + border-radius: var(--radius-xl); + margin-bottom: 24px; + box-shadow: var(--shadow-glow); +} + +.welcome-icon i { + width: 32px; + height: 32px; + color: white; +} + +.welcome-title { + font-size: 32px; + font-weight: 700; + margin-bottom: 12px; + background: linear-gradient(135deg, var(--text-primary), var(--text-secondary)); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; +} + +.welcome-subtitle { + font-size: 16px; + color: var(--text-muted); + margin-bottom: 32px; +} + +.quick-actions { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 12px; + max-width: 600px; + width: 100%; +} + +.quick-action-btn { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + background: var(--bg-glass); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + color: var(--text-secondary); + font-size: 14px; + cursor: pointer; + transition: all var(--transition-fast); +} + +.quick-action-btn:hover { + background: var(--bg-glass-light); + border-color: var(--primary); + color: var(--text-primary); + transform: translateY(-2px); +} + +.quick-action-btn i { + color: var(--primary-light); +} + +/* ======================================== + Messages + ======================================== */ +.message { + display: flex; + gap: 12px; + margin-bottom: 24px; + animation: fadeInUp 0.4s ease; +} + +.message.user { + flex-direction: row-reverse; +} + +.message-avatar { + width: 36px; + height: 36px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +.message.assistant .message-avatar { + background: linear-gradient(135deg, var(--primary), var(--primary-dark)); +} + +.message.user .message-avatar { + background: linear-gradient(135deg, var(--secondary), #059669); +} + +.message-avatar i { + width: 18px; + height: 18px; + color: white; +} + +.message-content { + max-width: 80%; + padding: 20px 24px; + background: linear-gradient(135deg, rgba(30, 41, 59, 0.9), rgba(30, 41, 59, 0.7)); + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + color: var(--text-primary); + line-height: 1.7; + box-shadow: var(--shadow-sm); +} + +.message.user .message-content { + background: linear-gradient(135deg, rgba(99, 102, 241, 0.25), rgba(16, 185, 129, 0.15)); + border-color: rgba(99, 102, 241, 0.4); +} + +/* ======================================== + Markdown Styles - Optimized + ======================================== */ + +/* Base typography for both containers */ +.message-content, +.final-response { + font-size: 14px; + line-height: 1.7; +} + +/* Headings */ +.message-content h1, .final-response h1, +.message-content h2, .final-response h2, +.message-content h3, .final-response h3, +.message-content h4, .final-response h4, +.message-content h5, .final-response h5, +.message-content h6, .final-response h6 { + margin-top: 24px; + margin-bottom: 12px; + font-weight: 600; + line-height: 1.3; + color: var(--text-primary); +} + +.message-content h1, .final-response h1 { + font-size: 24px; + padding-bottom: 8px; + border-bottom: 2px solid var(--primary); +} + +.message-content h2, .final-response h2 { + font-size: 20px; + padding-bottom: 6px; + border-bottom: 1px solid var(--border-color); +} + +.message-content h3, .final-response h3 { + font-size: 17px; + color: var(--primary-light); +} + +.message-content h4, .final-response h4 { font-size: 15px; } +.message-content h5, .final-response h5 { font-size: 14px; } +.message-content h6, .final-response h6 { + font-size: 13px; + color: var(--text-muted); +} + +/* Paragraphs */ +.message-content p, .final-response p { + margin-bottom: 14px; + line-height: 1.7; +} + +.message-content p:last-child, .final-response p:last-child { + margin-bottom: 0; +} + +/* Lists */ +.message-content ul, .final-response ul, +.message-content ol, .final-response ol { + margin-bottom: 14px; + padding-left: 8px; + list-style: none; +} + +.message-content ul li, .final-response ul li, +.message-content ol li, .final-response ol li { + margin-bottom: 8px; + padding-left: 20px; + position: relative; + line-height: 1.6; +} + +/* Custom bullet points */ +.message-content ul li::before, .final-response ul li::before { + content: ''; + position: absolute; + left: 0; + top: 10px; + width: 6px; + height: 6px; + background: var(--primary-light); + border-radius: 50%; +} + +.message-content ul li li::before, .final-response ul li li::before { + background: var(--accent); + border-radius: 0; + transform: rotate(45deg); +} + +/* Numbered lists */ +.message-content ol, .final-response ol { + counter-reset: item; +} + +.message-content ol li::before, .final-response ol li::before { + content: counter(item) '.'; + counter-increment: item; + position: absolute; + left: 0; + color: var(--primary-light); + font-weight: 600; + font-size: 13px; +} + +/* Nested lists */ +.message-content ul ul, .final-response ul ul, +.message-content ol ol, .final-response ol ol, +.message-content ul ol, .final-response ul ol, +.message-content ol ul, .final-response ol ul { + margin-top: 8px; + margin-bottom: 8px; +} + +/* Task Lists */ +.message-content input[type="checkbox"], .final-response input[type="checkbox"] { + appearance: none; + width: 16px; + height: 16px; + border: 2px solid var(--text-muted); + border-radius: 4px; + margin-right: 8px; + vertical-align: middle; + cursor: default; + position: relative; +} + +.message-content input[type="checkbox"]:checked, .final-response input[type="checkbox"]:checked { + background: var(--secondary); + border-color: var(--secondary); +} + +.message-content input[type="checkbox"]:checked::after, .final-response input[type="checkbox"]:checked::after { + content: '✓'; + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + color: white; + font-size: 11px; + font-weight: bold; +} + +/* Blockquotes */ +.message-content blockquote, .final-response blockquote { + margin: 16px 0; + padding: 12px 16px; + background: var(--bg-glass-light); + border-left: 4px solid var(--primary); + border-radius: 0 var(--radius-sm) var(--radius-sm) 0; + color: var(--text-secondary); + font-style: italic; +} + +.message-content blockquote p, .final-response blockquote p { + margin-bottom: 8px; +} + +.message-content blockquote p:last-child, .final-response blockquote p:last-child { + margin-bottom: 0; +} + +.message-content blockquote blockquote, .final-response blockquote blockquote { + margin: 8px 0; + border-left-color: var(--accent); +} + +/* Links */ +.message-content a, .final-response a { + color: var(--primary-light); + text-decoration: none; + border-bottom: 1px solid transparent; + transition: all var(--transition-fast); +} + +.message-content a:hover, .final-response a:hover { + border-bottom-color: var(--primary-light); +} + +/* Inline Code */ +.message-content code, .final-response code { + padding: 3px 8px; + background: rgba(99, 102, 241, 0.15); + border-radius: var(--radius-sm); + font-family: 'JetBrains Mono', 'Monaco', 'Consolas', monospace; + font-size: 13px; + color: var(--accent); + word-break: break-word; +} + +/* Code Blocks */ +.message-content pre, .final-response pre { + margin: 16px 0; + padding: 0; + background: #0d1117; + border-radius: var(--radius-md); + overflow-x: auto; + border: 1px solid var(--border-color); +} + +.message-content pre code, .final-response pre code { + display: block; + padding: 16px; + background: none; + color: #e6edf3; + font-size: 13px; + line-height: 1.6; + overflow-x: auto; +} + +/* Tables */ +.message-content table, .final-response table { + width: 100%; + margin: 16px 0; + border-collapse: collapse; + font-size: 13px; +} + +.message-content th, .final-response th, +.message-content td, .final-response td { + padding: 10px 12px; + border: 1px solid var(--border-color); + text-align: left; +} + +.message-content th, .final-response th { + background: var(--bg-glass-light); + font-weight: 600; + color: var(--text-primary); +} + +.message-content tr:nth-child(even), .final-response tr:nth-child(even) { + background: rgba(255, 255, 255, 0.02); +} + +.message-content tr:hover, .final-response tr:hover { + background: var(--bg-glass-light); +} + +/* Horizontal Rule */ +.message-content hr, .final-response hr { + margin: 24px 0; + border: none; + height: 1px; + background: linear-gradient( + 90deg, + transparent, + var(--border-color), + transparent + ); +} + +/* Strong and Emphasis */ +.message-content strong, .final-response strong { + color: var(--text-primary); + font-weight: 600; +} + +.message-content em, .final-response em { + color: var(--text-secondary); +} + +/* Images */ +.message-content img, .final-response img { + max-width: 100%; + height: auto; + border-radius: var(--radius-md); + margin: 16px 0; +} + +/* Definition Lists */ +.message-content dl, .final-response dl { + margin: 16px 0; +} + +.message-content dt, .final-response dt { + font-weight: 600; + color: var(--text-primary); + margin-top: 12px; +} + +.message-content dd, .final-response dd { + margin-left: 20px; + color: var(--text-secondary); +} + +/* Strikethrough */ +.message-content s, .final-response s, +.message-content del, .final-response del { + color: var(--text-muted); + text-decoration: line-through; +} + +/* ======================================== + Tool Cards + ======================================== */ +.tool-card { + margin: 16px 0; + background: var(--bg-glass); + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + overflow: hidden; + animation: fadeInUp 0.4s ease; + transition: all var(--transition-fast); +} + +.tool-card:hover { + transform: translateY(-2px); + box-shadow: var(--shadow-lg); +} + +.tool-card-header { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + background: rgba(99, 102, 241, 0.1); + border-bottom: 1px solid var(--border-color); +} + +.tool-card-icon { + width: 20px; + height: 20px; + color: var(--primary-light); +} + +.tool-card-title { + font-weight: 600; + color: var(--text-primary); +} + +.tool-card-body { + padding: 16px; +} + +.tool-card-label { + font-size: 12px; + color: var(--text-muted); + margin-bottom: 8px; +} + +.tool-card-content { + font-family: 'Monaco', 'Consolas', monospace; + font-size: 13px; + color: var(--text-secondary); + white-space: pre-wrap; + word-break: break-word; +} + +/* TodoWrite Specific */ +.todo-card .tool-card-header { background: rgba(245, 158, 11, 0.1); } -.todo-item.todo-pending { - color: #6b7280; +.todo-card .tool-card-icon { + color: var(--accent); } -.todo-item.todo-in_progress { - color: #2563eb; - font-weight: 500; +.todo-list { + display: flex; + flex-direction: column; + gap: 8px; } -.todo-item.todo-completed { - color: #059669; +.todo-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 12px; + background: var(--bg-glass-light); + border-radius: var(--radius-md); + transition: all var(--transition-fast); +} + +.todo-item:hover { + background: var(--bg-tertiary); } .todo-status { - font-family: 'Courier New', monospace; - font-weight: bold; - min-width: 24px; + font-family: 'Monaco', monospace; + font-weight: 600; + font-size: 13px; } +.todo-item.pending .todo-status { color: var(--text-muted); } +.todo-item.in_progress .todo-status { color: var(--primary-light); } +.todo-item.completed .todo-status { color: var(--secondary); } + .todo-content { flex: 1; -} - -.tool-call-header { - font-weight: 600; - color: white; - margin-bottom: 12px; - display: flex; - align-items: center; - gap: 8px; - font-size: 15px; -} - -.tool-call-details { - margin-top: 12px; - padding: 12px; - background: rgba(255, 255, 255, 0.95); - border-radius: 8px; - font-family: 'Courier New', monospace; + color: var(--text-secondary); font-size: 13px; - white-space: pre-wrap; - word-break: break-all; - color: #1f2937; - max-height: 200px; - overflow-y: auto; - border: 1px solid rgba(102, 126, 234, 0.2); } -.tool-result { - background: linear-gradient(135deg, #10b981 0%, #059669 100%); - border-radius: 12px; - padding: 16px; - margin: 12px 0; - box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2); - animation: slideIn 0.3s ease-out; +.todo-progress { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid var(--border-color); } -.tool-result-header { - font-weight: 600; - color: white; - margin-bottom: 12px; +.todo-progress-header { display: flex; + justify-content: space-between; align-items: center; - gap: 8px; - font-size: 15px; -} - -.tool-result-content { - margin-top: 12px; - padding: 12px; - background: rgba(255, 255, 255, 0.95); - border-radius: 8px; - font-family: 'Courier New', monospace; + margin-bottom: 10px; font-size: 13px; - white-space: pre-wrap; - max-height: 300px; - overflow-y: auto; - color: #1f2937; - border: 1px solid rgba(16, 185, 129, 0.2); + color: var(--text-secondary); } -/* 打字动画 */ -.typing-indicator { +.progress-bar { + height: 6px; + background: var(--bg-tertiary); + border-radius: 3px; + overflow: hidden; +} + +.progress-bar-fill { + height: 100%; + background: linear-gradient(90deg, var(--primary), var(--secondary)); + border-radius: 3px; + transition: width 0.5s ease; +} + +/* ======================================== + Input Area + ======================================== */ +.input-area { + padding: 20px 24px; + background: var(--bg-glass); + backdrop-filter: blur(20px); + border-top: 1px solid var(--border-color); +} + +.input-wrapper { + position: relative; display: flex; - gap: 4px; - padding: 12px 18px; -} - -.typing-indicator span { - width: 8px; - height: 8px; - background: #9ca3af; - border-radius: 50%; - animation: typing 1.4s infinite; -} - -.typing-indicator span:nth-child(2) { - animation-delay: 0.2s; -} - -.typing-indicator span:nth-child(3) { - animation-delay: 0.4s; -} - -@keyframes typing { - 0%, 60%, 100% { - transform: translateY(0); - } - 30% { - transform: translateY(-10px); - } -} - -/* 输入区域 */ -.input-container { - padding: 20px 30px; - background: white; - border-top: 1px solid #e5e7eb; -} - -.chat-form { - display: flex; - gap: 12px; align-items: flex-end; + gap: 12px; + padding: 12px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: var(--radius-xl); + transition: all var(--transition-fast); +} + +.input-wrapper:focus-within { + border-color: var(--border-focus); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1); } .chat-input { flex: 1; - padding: 12px 16px; - border: 2px solid #e5e7eb; - border-radius: 8px; - font-size: 15px; - font-family: inherit; + padding: 8px; + background: transparent; + border: none; + color: var(--text-primary); + font-size: 14px; + line-height: 1.5; resize: none; - min-height: 50px; max-height: 150px; - transition: border-color 0.2s; + min-height: 24px; +} + +.chat-input::placeholder { + color: var(--text-muted); } .chat-input:focus { outline: none; - border-color: #667eea; +} + +.input-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.btn-action { + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: none; + border-radius: var(--radius-md); + color: var(--text-muted); + cursor: pointer; + transition: all var(--transition-fast); +} + +.btn-action:hover { + background: var(--bg-tertiary); + color: var(--text-primary); } .btn-send { - padding: 12px 24px; - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, var(--primary), var(--primary-dark)); border: none; - border-radius: 8px; - font-size: 15px; - font-weight: 600; + border-radius: var(--radius-md); + color: white; cursor: pointer; - transition: transform 0.1s, box-shadow 0.2s; - min-width: 80px; + transition: all var(--transition-fast); } .btn-send:hover:not(:disabled) { - transform: translateY(-2px); - box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4); -} - -.btn-send:active:not(:disabled) { - transform: translateY(0); + transform: scale(1.05); + box-shadow: var(--shadow-glow); } .btn-send:disabled { @@ -520,110 +1020,44 @@ body { cursor: not-allowed; } -.btn-secondary { - padding: 8px 16px; - background: rgba(255, 255, 255, 0.2); - color: white; - border: 1px solid rgba(255, 255, 255, 0.3); - border-radius: 6px; - font-size: 14px; - font-weight: 500; - cursor: pointer; - transition: background 0.2s; +.input-hint { + margin-top: 8px; + text-align: center; + font-size: 12px; + color: var(--text-muted); } -.btn-secondary:hover { - background: rgba(255, 255, 255, 0.3); -} - -/* 切换按钮样式 */ -.toggle-container { +/* ======================================== + Buttons & Icons + ======================================== */ +.btn-icon { + width: 40px; + height: 40px; display: flex; align-items: center; - gap: 10px; + justify-content: center; + background: transparent; + border: none; + border-radius: var(--radius-md); + color: var(--text-muted); cursor: pointer; - padding: 6px 12px; - background: rgba(255, 255, 255, 0.2); - border-radius: 20px; - border: 1px solid rgba(255, 255, 255, 0.3); - transition: background 0.2s; + transition: all var(--transition-fast); } -.toggle-container:hover { - background: rgba(255, 255, 255, 0.3); +.btn-icon:hover { + background: var(--bg-glass-light); + color: var(--text-primary); } -.toggle-container input[type="checkbox"] { - display: none; -} +.icon-xs { width: 12px; height: 12px; } +.icon-sm { width: 16px; height: 16px; } +.icon-md { width: 20px; height: 20px; } +.icon-lg { width: 24px; height: 24px; } +.icon-xl { width: 32px; height: 32px; } -.toggle-label { - color: white; - font-size: 14px; - font-weight: 500; -} - -.toggle-switch { - position: relative; - width: 44px; - height: 24px; - background: rgba(255, 255, 255, 0.3); - border-radius: 12px; - transition: background 0.3s; -} - -.toggle-switch::before { - content: ''; - position: absolute; - width: 20px; - height: 20px; - left: 2px; - top: 2px; - background: white; - border-radius: 50%; - transition: transform 0.3s; -} - -.toggle-container input[type="checkbox"]:checked + .toggle-label + .toggle-switch { - background: #10b981; -} - -.toggle-container input[type="checkbox"]:checked + .toggle-label + .toggle-switch::before { - transform: translateX(20px); -} - -/* 错误消息 */ -.error-message { - background: #fef2f2; - border-left: 3px solid #ef4444; - padding: 12px; - margin: 10px 0; - border-radius: 6px; - color: #991b1b; - font-size: 14px; -} - -/* 滚动条样式 */ -.messages::-webkit-scrollbar { - width: 8px; -} - -.messages::-webkit-scrollbar-track { - background: #f1f1f1; -} - -.messages::-webkit-scrollbar-thumb { - background: #cbd5e1; - border-radius: 4px; -} - -.messages::-webkit-scrollbar-thumb:hover { - background: #94a3b8; -} - -/* ==================== 动画效果 ==================== */ - -/* 淡入动画 */ +/* ======================================== + Animations + ======================================== */ @keyframes fadeInUp { from { opacity: 0; @@ -635,29 +1069,15 @@ body { } } -/* 滑入动画 */ -@keyframes slideIn { - from { - opacity: 0; - transform: translateX(-20px); - } - to { - opacity: 1; - transform: translateX(0); - } -} - -/* 脉冲动画 */ @keyframes pulse { 0%, 100% { - transform: scale(1); + opacity: 1; } 50% { - transform: scale(1.05); + opacity: 0.5; } } -/* 闪烁动画 */ @keyframes shimmer { 0% { background-position: -1000px 0; @@ -667,248 +1087,418 @@ body { } } -/* 弹跳动画 */ -@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); -} - -/* 响应式优化 */ +/* ======================================== + Responsive Design + ======================================== */ @media (max-width: 768px) { - .header { - padding: 15px 20px; - flex-wrap: wrap; - gap: 10px; + .sidebar { + position: fixed; + left: 0; + top: 0; + bottom: 0; + z-index: 100; + transform: translateX(-100%); } - .header h1 { - font-size: 18px; + .sidebar.open { + transform: translateX(0); } - .header-controls { - width: 100%; - justify-content: flex-end; - flex-wrap: wrap; + .menu-toggle { + display: flex; } - .messages { - padding: 15px; + .header-title { + font-size: 16px; + } + + .quick-actions { + grid-template-columns: 1fr; } .message-content { max-width: 90%; - font-size: 14px; } - .input-container { - 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; + .tool-card { + margin: 12px -8px; } } -/* 暗色模式支持(可选) */ -@media (prefers-color-scheme: dark) { - /* 可以在这里添加暗色模式样式 */ +/* Loading States */ +.loading { + opacity: 0.7; + pointer-events: none; } -/* 打印样式 */ -@media print { - .header, - .input-container, - .copy-button { - display: none; - } - - .messages { - height: auto; - overflow: visible; - } - - .message { - break-inside: avoid; - } +.message.loading .message-content { + min-height: 40px; + display: flex; + align-items: center; +} + +.typing-indicator { + display: flex; + gap: 4px; + padding: 8px 0; +} + +.typing-indicator span { + width: 8px; + height: 8px; + background: var(--primary-light); + 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; } + +@keyframes bounce { + 0%, 80%, 100% { transform: scale(0); } + 40% { transform: scale(1); } +} + +@keyframes spin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } +} + +.spinning { + animation: spin 1s linear infinite; +} + +/* ======================================== + Message Group (New Process Flow) + ======================================== */ +.message-group { + display: flex; + gap: 12px; + margin-bottom: 24px; + animation: fadeInUp 0.4s ease; +} + +.message-group.assistant { + flex-direction: row; +} + +.message-body { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; +} + +/* Process Details (Collapsible) */ +.process-details { + background: var(--bg-glass); + border: 1px solid var(--border-color); + border-radius: var(--radius-md); + overflow: hidden; + transition: all var(--transition-fast); +} + +.process-details.collapsed .process-steps { + display: none; +} + +.process-details-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + cursor: pointer; + background: var(--bg-glass-light); + transition: background var(--transition-fast); +} + +.process-details-header:hover { + background: var(--bg-tertiary); +} + +.process-status { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + color: var(--text-secondary); +} + +.process-status .spinning { + animation: spin 1s linear infinite; +} + +.process-toggle { + color: var(--text-muted); + transition: transform var(--transition-fast); +} + +.process-details.collapsed .process-toggle { + transform: rotate(-90deg); +} + +.process-steps { + padding: 12px 16px; + display: flex; + flex-direction: column; + gap: 12px; +} + +/* Process Step */ +.process-step { + display: flex; + gap: 12px; + align-items: flex-start; + position: relative; +} + +.process-step:not(:last-child)::after { + content: ''; + position: absolute; + left: 11px; + top: 24px; + bottom: -12px; + width: 2px; + background: var(--border-color); +} + +.step-icon { + width: 24px; + height: 24px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + z-index: 1; +} + +.process-step.thinking .step-icon { + background: rgba(99, 102, 241, 0.2); + color: var(--primary-light); +} + +.process-step.tool-call .step-icon { + background: rgba(245, 158, 11, 0.2); + color: var(--accent); +} + +.process-step.tool-response .step-icon { + background: rgba(16, 185, 129, 0.2); + color: var(--secondary); +} + +.step-content { + flex: 1; + min-width: 0; + font-size: 13px; + color: var(--text-secondary); + line-height: 1.5; + padding-top: 3px; +} + +.step-title { + font-weight: 500; + color: var(--text-primary); + margin-bottom: 4px; +} + +.step-args { + font-family: 'Monaco', 'Consolas', monospace; + font-size: 12px; + background: var(--bg-tertiary); + padding: 8px; + border-radius: var(--radius-sm); + overflow-x: auto; + margin-top: 6px; +} + +.step-args code { + color: var(--text-secondary); +} + +.step-result { + font-size: 12px; + color: var(--text-muted); + margin-top: 4px; + line-height: 1.4; +} + +/* Todo List Compact */ +.todo-list-compact { + margin-top: 8px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.todo-item-compact { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: var(--text-secondary); +} + +.todo-item-compact.completed { + color: var(--secondary); +} + +.todo-item-compact.in_progress { + color: var(--primary-light); +} + +.todo-icon { + display: flex; + align-items: center; + justify-content: center; +} + +.todo-text { + flex: 1; +} + +.todo-more { + font-size: 11px; + color: var(--text-muted); + padding-left: 24px; +} + +/* Step Todo Progress */ +.step-todo-progress { + background: var(--bg-glass-light); + border-radius: var(--radius-sm); + padding: 10px 12px; + margin-top: 6px; +} + +.step-progress-bar { + height: 4px; + background: var(--bg-tertiary); + border-radius: 2px; + overflow: hidden; + margin-bottom: 6px; +} + +.step-progress-fill { + height: 100%; + background: linear-gradient(90deg, var(--primary), var(--secondary)); + border-radius: 2px; + transition: width 0.5s ease; +} + +.step-progress-info { + display: flex; + justify-content: space-between; + font-size: 11px; + color: var(--text-muted); + margin-bottom: 8px; +} + +/* Final Response */ +.final-response { + padding: 20px 24px; + background: linear-gradient(135deg, rgba(30, 41, 59, 0.8), rgba(30, 41, 59, 0.6)); + border: 1px solid var(--border-color); + border-radius: var(--radius-lg); + color: var(--text-primary); + line-height: 1.7; + font-size: 14px; +} + +.final-response.loading { + min-height: 60px; + display: flex; + align-items: center; +} + +/* First element in final response */ +.final-response > *:first-child { + margin-top: 0; +} + +/* Last element in final response */ +.final-response > *:last-child { + margin-bottom: 0; +} + +/* Error Message */ +.error-message { + padding: 12px 16px; + background: rgba(239, 68, 68, 0.1); + border: 1px solid rgba(239, 68, 68, 0.3); + border-radius: var(--radius-md); + color: #f87171; + font-size: 13px; + animation: fadeInUp 0.3s ease; +} + +/* Highlight.js Customization */ +.hljs { + background: transparent !important; + padding: 0 !important; +} + +/* Code Block Line Numbers (optional) */ +.message-content pre .line-numbers, +.final-response pre .line-numbers { + position: absolute; + left: 0; + top: 16px; + bottom: 16px; + width: 40px; + text-align: right; + color: var(--text-muted); + font-size: 12px; + line-height: 1.6; + user-select: none; + border-right: 1px solid var(--border-color); + padding-right: 12px; +} + +/* Code language badge */ +.message-content pre::before, +.final-response pre::before { + content: attr(data-language); + position: absolute; + top: 0; + right: 0; + padding: 4px 12px; + background: var(--bg-glass-light); + border-bottom-left-radius: var(--radius-sm); + font-size: 11px; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +/* Copy Button for Code Blocks */ +.copy-button { + position: absolute; + top: 8px; + right: 8px; + padding: 6px 10px; + background: var(--bg-glass-light); + border: 1px solid var(--border-color); + border-radius: var(--radius-sm); + color: var(--text-muted); + font-size: 12px; + cursor: pointer; + transition: all var(--transition-fast); + display: flex; + align-items: center; + gap: 4px; + z-index: 10; +} + +.copy-button:hover { + background: var(--bg-tertiary); + color: var(--text-primary); +} + +.copy-button.copied { + background: rgba(16, 185, 129, 0.2); + border-color: var(--secondary); + color: var(--secondary); } diff --git a/src/main/resources/static/js/chat-api.js b/src/main/resources/static/js/chat-api.js index 32fd60d..d36e3b9 100644 --- a/src/main/resources/static/js/chat-api.js +++ b/src/main/resources/static/js/chat-api.js @@ -150,6 +150,86 @@ const ChatAPI = { throw new Error('清空对话失败'); } + return true; + }, + + // ==================== 会话管理 API ==================== + + /** + * 获取所有会话列表 + */ + async listConversations() { + const response = await fetch(`${this.baseUrl}/api/chat/conversations`); + if (!response.ok) { + throw new Error('获取会话列表失败'); + } + return await response.json(); + }, + + /** + * 创建新会话 + */ + async createConversation(title = '新对话') { + const response = await fetch(`${this.baseUrl}/api/chat/conversations`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title }) + }); + if (!response.ok) { + throw new Error('创建会话失败'); + } + const data = await response.json(); + this.setConversationId(data.id); + return data; + }, + + /** + * 获取会话消息 + */ + async getMessages(conversationId) { + const response = await fetch(`${this.baseUrl}/api/chat/conversations/${conversationId}/messages`); + if (!response.ok) { + throw new Error('获取消息失败'); + } + return await response.json(); + }, + + /** + * 获取会话元数据 + */ + async getConversation(conversationId) { + const response = await fetch(`${this.baseUrl}/api/chat/conversations/${conversationId}`); + if (!response.ok) { + return null; + } + return await response.json(); + }, + + /** + * 更新会话标题 + */ + async updateConversation(conversationId, title) { + const response = await fetch(`${this.baseUrl}/api/chat/conversations/${conversationId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title }) + }); + if (!response.ok) { + throw new Error('更新会话失败'); + } + return true; + }, + + /** + * 删除会话 + */ + async deleteConversation(conversationId) { + const response = await fetch(`${this.baseUrl}/api/chat/conversations/${conversationId}`, { + method: 'DELETE' + }); + if (!response.ok) { + throw new Error('删除会话失败'); + } return true; } }; diff --git a/src/main/resources/static/js/chat-main.js b/src/main/resources/static/js/chat-main.js index 4c6b643..02595c5 100644 --- a/src/main/resources/static/js/chat-main.js +++ b/src/main/resources/static/js/chat-main.js @@ -10,21 +10,45 @@ const ChatApp = { /** * 初始化应用 */ - init() { + async init() { // 初始化 DOM 元素 ChatUI.init(); + // 先加载会话列表 + const conversations = await ChatAPI.listConversations(); + // 初始化会话 ID - this.conversationId = ChatUtils.getOrCreateConversationId(); - ChatAPI.init(this.conversationId); + 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(); - // 显示欢迎消息 - this.showWelcomeMessage(); + // 加载会话列表(更新选中状态) + await ChatUI.loadConversationList(); - console.log('🚀 ChatApp 初始化完成'); + // 加载当前会话的历史消息 + await this.loadCurrentConversation(); + + console.log('ChatApp 初始化完成,当前会话:', this.conversationId); }, /** @@ -45,12 +69,47 @@ const ChatApp = { // 清空对话 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(); + } + }, + /** * 处理表单提交 */ @@ -75,6 +134,9 @@ const ChatApp = { await this.handleStream(message); } + // 刷新会话列表(更新时间和消息数) + await ChatUI.loadConversationList(); + // 恢复输入状态 this.isProcessing = false; ChatUI.setInputState({ disabled: false }); @@ -97,23 +159,24 @@ const ChatApp = { async handleStream(message) { ChatUI.updateConnectionStatus(true); - // 创建加载消息 - const messageEl = ChatUI.renderAssistantMessage('', { isLoading: true }); + // 创建 AI 消息容器 + ChatUI.createAssistantMessageContainer(); + 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); } } + // 设置最终回复 + ChatUI.setFinalResponse(content); } catch (error) { console.error('流式响应错误:', error); ChatUI.showError('连接错误: ' + error.message); - messageEl.remove(); } finally { ChatUI.updateConnectionStatus(false); } @@ -125,6 +188,9 @@ const ChatApp = { async handleStreamWithTools(message) { ChatUI.updateConnectionStatus(true); + // 创建 AI 消息容器 + ChatUI.createAssistantMessageContainer(); + try { for await (const event of ChatAPI.streamMessageWithTools(message)) { await this.handleStreamEvent(event); @@ -157,11 +223,13 @@ const ChatApp = { break; case 'assistant_message': - ChatUI.renderAssistantMessage(data.content); + // 显示思考过程 + ChatUI.addThinkingStep(data.content); break; case 'final_response': - ChatUI.renderAssistantMessage(data.content); + // 设置最终回复 + ChatUI.setFinalResponse(data.content); break; case 'error': @@ -180,7 +248,7 @@ const ChatApp = { const { tool_name, arguments: args } = data; const isTodoWrite = tool_name === 'TodoWrite'; - ChatUI.renderToolCall(tool_name, args, { isTodoWrite }); + ChatUI.addToolCallStep(tool_name, args, isTodoWrite); }, /** @@ -190,7 +258,7 @@ const ChatApp = { const { tool_name, response } = data; const isTodoWrite = tool_name === 'TodoWrite'; - ChatUI.renderToolResult(tool_name, response, { isTodoWrite }); + ChatUI.addToolResponseStep(tool_name, response, isTodoWrite); }, /** @@ -208,45 +276,16 @@ const ChatApp = { // 清空界面 ChatUI.clearMessages(); + // 刷新列表 + await ChatUI.loadConversationList(); + // 显示重置消息 - ChatUI.renderAssistantMessage('对话已清空,我们可以重新开始!'); + ChatUI.createAssistantMessageContainer(); + ChatUI.setFinalResponse('对话已清空,我们可以重新开始!'); } 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); } }; diff --git a/src/main/resources/static/js/chat-ui.js b/src/main/resources/static/js/chat-ui.js index 48443b4..38c1b5a 100644 --- a/src/main/resources/static/js/chat-ui.js +++ b/src/main/resources/static/js/chat-ui.js @@ -7,6 +7,9 @@ const ChatUI = { // DOM 元素缓存 elements: {}, + // 当前活动的过程容器 + activeProcessContainer: null, + /** * 初始化 DOM 元素缓存 */ @@ -18,11 +21,17 @@ const ChatUI = { sendBtn: document.getElementById('send-btn'), clearBtn: document.getElementById('clear-btn'), connectionStatus: document.getElementById('connection-status'), - toolToggle: document.getElementById('tool-toggle') + toolToggle: document.getElementById('tool-toggle'), + menuToggle: document.getElementById('menu-toggle'), + sidebar: document.querySelector('.sidebar'), + newChatBtn: document.getElementById('new-chat-btn') }; // 初始化 marked.js 配置 this.initMarked(); + + // 绑定侧边栏事件 + this.bindSidebarEvents(); }, /** @@ -32,6 +41,49 @@ const ChatUI = { return this.elements[id] || document.getElementById(id); }, + /** + * 绑定侧边栏事件 + */ + bindSidebarEvents() { + const { menuToggle, sidebar, newChatBtn } = this.elements; + + // 移动端菜单切换 + if (menuToggle) { + menuToggle.addEventListener('click', () => { + sidebar.classList.toggle('open'); + }); + } + + // 点击外部关闭侧边栏 + document.addEventListener('click', (e) => { + if (sidebar && menuToggle && + !sidebar.contains(e.target) && + !menuToggle.contains(e.target) && + sidebar.classList.contains('open')) { + sidebar.classList.remove('open'); + } + }); + + // 快速操作按钮 + document.querySelectorAll('.quick-action-btn').forEach(btn => { + btn.addEventListener('click', () => { + const prompt = btn.dataset.prompt; + if (prompt) { + this.elements.userInput.value = prompt; + this.autoResizeInput(); + this.elements.userInput.focus(); + } + }); + }); + + // 新对话按钮 + if (newChatBtn) { + newChatBtn.addEventListener('click', () => { + this.handleNewChat(); + }); + } + }, + /** * 初始化 Marked.js 配置 */ @@ -58,126 +110,307 @@ const ChatUI = { * 渲染用户消息 */ renderUserMessage(content) { + this.hideWelcomeMessage(); + this.activeProcessContainer = null; // 重置活动容器 + const messageDiv = document.createElement('div'); - messageDiv.className = 'message user animate-in'; + messageDiv.className = 'message user'; + + const avatar = document.createElement('div'); + avatar.className = 'message-avatar'; + avatar.innerHTML = ''; const contentDiv = document.createElement('div'); contentDiv.className = 'message-content'; contentDiv.textContent = content; + messageDiv.appendChild(avatar); messageDiv.appendChild(contentDiv); this.elements.messagesContainer.appendChild(messageDiv); + + lucide.createIcons(); this.scrollToBottom(); return messageDiv; }, /** - * 渲染 AI 消息 + * 创建新的 AI 消息容器(包含过程详情和最终回复) */ - renderAssistantMessage(content, options = {}) { - const messageDiv = document.createElement('div'); - messageDiv.className = `message assistant animate-in ${options.isLoading ? 'loading' : ''}`; + createAssistantMessageContainer() { + this.hideWelcomeMessage(); - const contentDiv = document.createElement('div'); - contentDiv.className = 'message-content'; + const messageGroup = document.createElement('div'); + messageGroup.className = 'message-group assistant'; - if (options.isLoading) { - contentDiv.innerHTML = this.getTypingIndicator(); - } else { - contentDiv.innerHTML = this.renderMarkdown(content); - this.addCodeCopyButtons(contentDiv); + // 头像 + const avatar = document.createElement('div'); + avatar.className = 'message-avatar'; + avatar.innerHTML = ''; + + // 消息主体 + const messageBody = document.createElement('div'); + messageBody.className = 'message-body'; + + // 过程详情(可折叠) + const processDetails = document.createElement('div'); + processDetails.className = 'process-details'; + + // 头部(点击折叠/展开) + const detailsHeader = document.createElement('div'); + detailsHeader.className = 'process-details-header'; + detailsHeader.innerHTML = ` + + + 思考中... + + + + + `; + + // 步骤列表 + const stepsList = document.createElement('div'); + stepsList.className = 'process-steps'; + + // 点击折叠/展开 + detailsHeader.addEventListener('click', () => { + processDetails.classList.toggle('collapsed'); + const icon = detailsHeader.querySelector('.process-toggle i'); + if (processDetails.classList.contains('collapsed')) { + icon.setAttribute('data-lucide', 'chevron-right'); + } else { + icon.setAttribute('data-lucide', 'chevron-down'); + } + lucide.createIcons(); + }); + + processDetails.appendChild(detailsHeader); + processDetails.appendChild(stepsList); + + // 最终回复区域 + const finalResponse = document.createElement('div'); + finalResponse.className = 'final-response loading'; + finalResponse.innerHTML = '
'; + + messageBody.appendChild(processDetails); + messageBody.appendChild(finalResponse); + + messageGroup.appendChild(avatar); + messageGroup.appendChild(messageBody); + + this.elements.messagesContainer.appendChild(messageGroup); + + this.activeProcessContainer = { + group: messageGroup, + processDetails: processDetails, + stepsList: stepsList, + detailsHeader: detailsHeader, + finalResponse: finalResponse, + stepCount: 0 + }; + + lucide.createIcons(); + this.scrollToBottom(); + + return this.activeProcessContainer; + }, + + /** + * 添加思考步骤到过程详情 + */ + addThinkingStep(content) { + if (!this.activeProcessContainer) { + this.createAssistantMessageContainer(); } - messageDiv.appendChild(contentDiv); - this.elements.messagesContainer.appendChild(messageDiv); + const { stepsList, detailsHeader } = this.activeProcessContainer; + + const step = document.createElement('div'); + step.className = 'process-step thinking'; + step.innerHTML = ` +
+ +
+
${this.escapeHtml(content)}
+ `; + + stepsList.appendChild(step); + lucide.createIcons(); this.scrollToBottom(); - return messageDiv; + // 更新状态 + this.updateProcessStatus('thinking'); }, /** - * 更新消息内容 + * 添加工具调用步骤 */ - updateMessage(messageElement, content) { - const contentDiv = messageElement.querySelector('.message-content'); - contentDiv.innerHTML = this.renderMarkdown(content); - this.addCodeCopyButtons(contentDiv); - this.scrollToBottom(); - }, + addToolCallStep(toolName, args, isTodoWrite = false) { + if (!this.activeProcessContainer) { + this.createAssistantMessageContainer(); + } - /** - * 获取打字指示器 HTML - */ - getTypingIndicator() { - return '
'; - }, + const { stepsList } = this.activeProcessContainer; - // ==================== 工具调用渲染 ==================== + const step = document.createElement('div'); + step.className = `process-step tool-call${isTodoWrite ? ' todo-step' : ''}`; - /** - * 渲染工具调用 - */ - 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'; + let icon = 'wrench'; + let title = `调用工具: ${toolName}`; + let details = ''; - const header = document.createElement('div'); - header.className = isTodoWrite ? 'todo-write-header' : 'tool-call-header'; - header.innerHTML = isTodoWrite - ? '📋 任务列表' - : `⚙️ 调用工具: ${name}`; + if (isTodoWrite) { + icon = 'clipboard-list'; + title = '任务列表'; + const todoList = this.renderTodoList(args); + if (todoList) { + details = '
'; + } + } - div.appendChild(header); + step.innerHTML = ` +
+ +
+
+
${title}
+ ${isTodoWrite ? '' : `
${this.escapeHtml(ChatUtils.formatJson(args))}
`} + ${details} +
+ `; // 如果是 TodoWrite,渲染任务列表 if (isTodoWrite) { + const todoListContainer = step.querySelector('.step-todo-list'); const todoList = this.renderTodoList(args); - if (todoList) { - div.appendChild(todoList); + if (todoList && todoListContainer) { + todoListContainer.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); + stepsList.appendChild(step); + lucide.createIcons(); this.scrollToBottom(); - return div; + this.updateProcessStatus('calling-tool'); }, /** - * 渲染工具响应 + * 添加工具响应步骤 */ - renderToolResult(name, result, options = {}) { - const { isTodoWrite = false } = options; + addToolResponseStep(toolName, response, isTodoWrite = false) { + if (!this.activeProcessContainer) return; + + const { stepsList } = this.activeProcessContainer; + + const step = document.createElement('div'); + step.className = 'process-step tool-response'; if (isTodoWrite) { - return this.renderTodoProgress(result); + // 更新任务列表为进度视图 + step.className += ' todo-progress-step'; + const todoProgress = this.createTodoProgressElement(response); + step.appendChild(todoProgress); + } else { + let displayResponse = typeof response === 'string' ? response : ChatUtils.formatJson(response); + displayResponse = this.truncateText(displayResponse, 200); + + step.innerHTML = ` +
+ +
+
+
工具返回: ${toolName}
+
${this.escapeHtml(displayResponse)}
+
+ `; } - 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); + stepsList.appendChild(step); + lucide.createIcons(); this.scrollToBottom(); - return div; + this.updateProcessStatus('got-result'); + }, + + /** + * 设置最终回复内容 + */ + setFinalResponse(content) { + if (!this.activeProcessContainer) { + this.createAssistantMessageContainer(); + } + + const { finalResponse, detailsHeader } = this.activeProcessContainer; + + finalResponse.className = 'final-response'; + finalResponse.innerHTML = this.renderMarkdown(content); + this.addCodeCopyButtons(finalResponse); + + // 更新头部状态为完成 + const statusText = detailsHeader.querySelector('.status-text'); + const statusIcon = detailsHeader.querySelector('.process-status i'); + if (statusText) statusText.textContent = '已完成'; + if (statusIcon) { + statusIcon.setAttribute('data-lucide', 'check-circle'); + statusIcon.classList.remove('spinning'); + } + + lucide.createIcons(); + this.scrollToBottom(); + + // 重置活动容器 + this.activeProcessContainer = null; + }, + + /** + * 更新过程状态 + */ + updateProcessStatus(status) { + if (!this.activeProcessContainer) return; + + const { detailsHeader } = this.activeProcessContainer; + const statusText = detailsHeader.querySelector('.status-text'); + + const statusMap = { + 'thinking': '思考中...', + 'calling-tool': '调用工具...', + 'got-result': '处理结果...' + }; + + if (statusText && statusMap[status]) { + statusText.textContent = statusMap[status]; + } + }, + + // ==================== 旧接口兼容 ==================== + + /** + * 渲染 AI 消息(兼容旧接口) + */ + renderAssistantMessage(content, options = {}) { + if (options.isLoading) { + this.createAssistantMessageContainer(); + return this.activeProcessContainer.group; + } + + this.setFinalResponse(content); + return this.activeProcessContainer?.group; + }, + + /** + * 渲染工具调用(兼容旧接口,转发到新方法) + */ + renderToolCall(name, args, options = {}) { + this.addToolCallStep(name, args, options.isTodoWrite); + }, + + /** + * 渲染工具响应(兼容旧接口,转发到新方法) + */ + renderToolResult(name, result, options = {}) { + this.addToolResponseStep(name, result, options.isTodoWrite); }, // ==================== TodoWrite 渲染 ==================== @@ -193,10 +426,23 @@ const ChatUI = { if (!todos || todos.length === 0) return null; const listDiv = document.createElement('div'); - listDiv.className = 'todo-list'; + listDiv.className = 'todo-list-compact'; todos.forEach(todo => { - const item = this.createTodoItem(todo); + const item = document.createElement('div'); + item.className = `todo-item-compact ${todo.status}`; + + const icons = { + pending: '', + in_progress: '', + completed: '' + }; + + item.innerHTML = ` + ${icons[todo.status] || icons.pending} + ${this.escapeHtml(todo.content)} + `; + listDiv.appendChild(item); }); @@ -208,9 +454,9 @@ const ChatUI = { }, /** - * 渲染 TodoWrite 进度 + * 创建 TodoWrite 进度元素 */ - renderTodoProgress(response) { + createTodoProgressElement(response) { try { const data = typeof response === 'string' ? this.extractJsonFromString(response) @@ -218,82 +464,70 @@ const ChatUI = { const todos = this.extractTodos(data); if (!todos || todos.length === 0) { - return this.renderToolResult('TodoWrite', response); + return document.createTextNode('任务更新'); } - const div = document.createElement('div'); - div.className = 'todo-write-progress animate-in'; + const container = document.createElement('div'); + container.className = 'step-todo-progress'; // 计算进度 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 = 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); + container.innerHTML = ` +
+
+
+
+ ${completed}/${total} 完成 + ${percentage}% +
+ `; - // 任务列表 - const listDiv = document.createElement('div'); - listDiv.className = 'todo-list'; - todos.forEach(todo => { - listDiv.appendChild(this.createTodoItem(todo)); - }); + // 任务列表(只显示进行中或未完成的) + const activeTodos = todos.filter(t => t.status !== 'completed'); + if (activeTodos.length > 0) { + const listDiv = document.createElement('div'); + listDiv.className = 'todo-list-compact'; - div.appendChild(header); - div.appendChild(progressBar); - div.appendChild(listDiv); + activeTodos.slice(0, 3).forEach(todo => { + const item = document.createElement('div'); + item.className = `todo-item-compact ${todo.status}`; - this.elements.messagesContainer.appendChild(div); - this.scrollToBottom(); + const icons = { + pending: '', + in_progress: '', + completed: '' + }; - return div; + item.innerHTML = ` + ${icons[todo.status] || icons.pending} + ${this.escapeHtml(todo.content)} + `; + + listDiv.appendChild(item); + }); + + if (activeTodos.length > 3) { + const more = document.createElement('div'); + more.className = 'todo-more'; + more.textContent = `还有 ${activeTodos.length - 3} 个任务...`; + listDiv.appendChild(more); + } + + container.appendChild(listDiv); + } + + return container; } catch (e) { console.error('渲染任务进度失败:', e); - return this.renderToolResult('TodoWrite', response); + return document.createTextNode('任务更新'); } }, - /** - * 创建任务项 - */ - 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 */ @@ -319,6 +553,16 @@ const ChatUI = { // ==================== 辅助功能 ==================== + /** + * 隐藏欢迎消息 + */ + hideWelcomeMessage() { + const welcomeMessage = this.elements.messagesContainer.querySelector('.welcome-message'); + if (welcomeMessage) { + welcomeMessage.style.display = 'none'; + } + }, + /** * 渲染 Markdown */ @@ -335,25 +579,40 @@ const ChatUI = { hljs.highlightElement(block); const pre = block.parentElement; + + if (pre.querySelector('.copy-button')) return; + + // 确保 pre 有相对定位 + pre.style.position = 'relative'; + + // 检测语言并设置 data-language + const language = block.className.match(/language-(\w+)/); + if (language) { + pre.setAttribute('data-language', language[1]); + } + const copyBtn = document.createElement('button'); copyBtn.className = 'copy-button'; - copyBtn.textContent = '复制'; + copyBtn.innerHTML = ''; + copyBtn.title = '复制'; copyBtn.addEventListener('click', async () => { try { await navigator.clipboard.writeText(block.textContent); - copyBtn.textContent = '已复制!'; + copyBtn.innerHTML = ''; copyBtn.classList.add('copied'); + lucide.createIcons(); setTimeout(() => { - copyBtn.textContent = '复制'; + copyBtn.innerHTML = ''; copyBtn.classList.remove('copied'); + lucide.createIcons(); }, 2000); } catch (err) { - copyBtn.textContent = '复制失败'; + copyBtn.innerHTML = ''; + lucide.createIcons(); } }); - pre.style.position = 'relative'; pre.appendChild(copyBtn); }); }, @@ -363,15 +622,14 @@ const ChatUI = { */ showError(message, duration = 3000) { const errorDiv = document.createElement('div'); - errorDiv.className = 'error-message animate-in'; - errorDiv.textContent = '❌ ' + message; + errorDiv.className = 'error-message'; + errorDiv.textContent = message; this.elements.messagesContainer.appendChild(errorDiv); this.scrollToBottom(); setTimeout(() => { - errorDiv.classList.add('animate-out'); - setTimeout(() => errorDiv.remove(), 300); + errorDiv.remove(); }, duration); }, @@ -380,12 +638,17 @@ const ChatUI = { */ updateConnectionStatus(connected) { const status = this.elements.connectionStatus; - if (connected) { - status.textContent = '已连接'; - status.className = 'status-indicator connected'; - } else { - status.textContent = '未连接'; - status.className = 'status-indicator disconnected'; + const statusText = status.querySelector('.status-text'); + const statusDot = status.querySelector('.status-dot'); + + if (statusText && statusDot) { + if (connected) { + statusText.textContent = '处理中...'; + statusDot.style.background = 'var(--accent)'; + } else { + statusText.textContent = '已连接'; + statusDot.style.background = 'var(--secondary)'; + } } }, @@ -393,7 +656,230 @@ const ChatUI = { * 清空消息区域 */ clearMessages() { - this.elements.messagesContainer.innerHTML = ''; + this.activeProcessContainer = null; + this.elements.messagesContainer.innerHTML = ` +
+
+ +
+

有什么可以帮你的?

+

我可以帮你执行定价流程、管理任务、查询数据等

+ +
+ + + + +
+
+ `; + + this.bindSidebarEvents(); + lucide.createIcons(); + }, + + /** + * 处理新对话 + */ + async handleNewChat() { + // 通过 API 创建新会话 + try { + const conversation = await ChatAPI.createConversation('新对话'); + this.activeProcessContainer = null; + this.clearMessages(); + this.loadConversationList(); // 刷新列表 + + if (this.elements.sidebar) { + this.elements.sidebar.classList.remove('open'); + } + } catch (error) { + console.error('创建新会话失败:', error); + // 降级到本地生成 + const newId = ChatUtils.regenerateConversationId(); + ChatAPI.setConversationId(newId); + this.activeProcessContainer = null; + this.clearMessages(); + } + }, + + // ==================== 会话列表管理 ==================== + + /** + * 渲染会话列表 + */ + renderConversationList(conversations, currentId) { + const navList = document.getElementById('conversation-list'); + if (!navList) return; + + if (conversations.length === 0) { + navList.innerHTML = ''; + return; + } + + navList.innerHTML = conversations.map(conv => { + const isActive = conv.id === currentId; + const date = this.formatDate(conv.updatedAt); + return ` + + `; + }).join(''); + + // 绑定点击事件 + navList.querySelectorAll('.nav-item').forEach(item => { + item.addEventListener('click', (e) => { + // 如果点击的是删除按钮,不触发切换 + if (e.target.closest('.btn-delete-conv')) return; + + const convId = item.dataset.conversationId; + this.switchToConversation(convId); + }); + }); + + // 绑定删除事件 + navList.querySelectorAll('.btn-delete-conv').forEach(btn => { + btn.addEventListener('click', async (e) => { + e.stopPropagation(); + const item = btn.closest('.nav-item'); + const convId = item.dataset.conversationId; + await this.deleteConversation(convId); + }); + }); + + lucide.createIcons(); + }, + + /** + * 加载会话列表 + */ + async loadConversationList() { + try { + const conversations = await ChatAPI.listConversations(); + this.renderConversationList(conversations, ChatAPI.conversationId); + } catch (error) { + console.error('加载会话列表失败:', error); + } + }, + + /** + * 切换到指定会话 + */ + async switchToConversation(conversationId) { + try { + // 获取会话消息 + const messages = await ChatAPI.getMessages(conversationId); + + // 更新当前会话 ID + ChatAPI.setConversationId(conversationId); + + // 清空并重新渲染消息 + this.activeProcessContainer = null; + this.elements.messagesContainer.innerHTML = ''; + + // 渲染历史消息 + messages.forEach(msg => { + if (msg.role === 'user') { + this.renderUserMessage(msg.content); + } else if (msg.role === 'assistant') { + this.renderAssistantMessage(msg.content); + } + }); + + // 如果没有消息,显示欢迎界面 + if (messages.length === 0) { + this.clearMessages(); + } + + // 刷新会话列表(更新选中状态) + await this.loadConversationList(); + + // 关闭移动端侧边栏 + if (this.elements.sidebar) { + this.elements.sidebar.classList.remove('open'); + } + + // 滚动到底部 + this.scrollToBottom(); + } catch (error) { + console.error('切换会话失败:', error); + this.showError('加载会话失败'); + } + }, + + /** + * 删除会话 + */ + async deleteConversation(conversationId) { + if (!confirm('确定要删除这个会话吗?')) return; + + try { + await ChatAPI.deleteConversation(conversationId); + + // 重新加载会话列表 + const conversations = await ChatAPI.listConversations(); + + // 如果删除的是当前会话 + if (conversationId === ChatAPI.conversationId) { + // 如果还有其他会话,切换到最近的会话 + if (conversations.length > 0) { + const newestConv = conversations[0]; // 列表已按更新时间排序 + await this.switchToConversation(newestConv.id); + } else { + // 没有任何会话了,创建新会话 + await this.handleNewChat(); + } + } else { + // 删除的不是当前会话,只刷新列表 + this.renderConversationList(conversations, ChatAPI.conversationId); + } + } catch (error) { + console.error('删除会话失败:', error); + this.showError('删除会话失败'); + } + }, + + /** + * 格式化日期 + */ + formatDate(dateString) { + if (!dateString) return ''; + const date = new Date(dateString); + const now = new Date(); + const diff = now - date; + + // 小于 1 分钟 + if (diff < 60000) return '刚刚'; + // 小于 1 小时 + if (diff < 3600000) return `${Math.floor(diff / 60000)} 分钟前`; + // 小于 24 小时 + if (diff < 86400000) return `${Math.floor(diff / 3600000)} 小时前`; + // 小于 7 天 + if (diff < 604800000) return `${Math.floor(diff / 86400000)} 天前`; + + // 显示具体日期 + return date.toLocaleDateString('zh-CN', { + month: 'short', + day: 'numeric' + }); }, /** @@ -435,6 +921,23 @@ const ChatUI = { */ isToolEnabled() { return this.elements.toolToggle.checked; + }, + + /** + * HTML 转义 + */ + escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text; + return div.innerHTML; + }, + + /** + * 截断文本 + */ + truncateText(text, maxLength) { + if (!text || text.length <= maxLength) return text; + return text.substring(0, maxLength) + '...'; } };