feat: 实现会话管理和 AI 回复保存功能
## 新增功能 - 实现会话持久化存储(JSON 文件) - 支持会话列表显示、切换、创建、删除 - 自动保存用户消息和 AI 回复 - 优化 Markdown 渲染样式(标题、列表、代码块、表格等) - 添加过程数据可视化(思考步骤、工具调用、响应) ## 技术改进 - 新增 ConversationMessage、ConversationMetadata 模型 - 新增 ConversationStorageService 服务(JSON 文件存储) - 在 ChatService 中添加流式响应完成后保存 AI 回复的逻辑 - 优化删除会话逻辑:删除当前会话后切换到现有会话,而非自动创建新会话 - 优化应用初始化:优先使用现有会话,仅在没有会话时才创建新会话 ## 依赖更新 - 添加 jackson-datatype-jsr310 支持 Java 8 DateTime Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1ffd256c9d
commit
fd09a55614
11 files changed
+2697
-993
No files matched your search
@@ -33,4 +33,7 @@ target/
|
||||
# Claude Code local settings
|
||||
.claude/
|
||||
|
||||
# Conversation storage
|
||||
conversations/
|
||||
|
||||
spring-ai-agent-util-examples/
|
||||
@@ -80,6 +80,12 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-actuator</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Jackson JSR310 for Java 8 DateTime support -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<dependencyManagement>
|
||||
|
||||
@@ -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<String> clear(@RequestParam String conversationId) {
|
||||
chatService.clear(conversationId);
|
||||
storageService.deleteConversation(conversationId);
|
||||
return ResponseEntity.ok("Conversation cleared: " + conversationId);
|
||||
}
|
||||
|
||||
// ==================== 会话管理 API ====================
|
||||
|
||||
/**
|
||||
* 获取所有会话列表
|
||||
*/
|
||||
@GetMapping("/conversations")
|
||||
public ResponseEntity<List<org.springaicommunity.skills.model.ConversationMetadata>> listConversations() {
|
||||
return ResponseEntity.ok(storageService.listConversations());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建新会话
|
||||
*/
|
||||
@PostMapping("/conversations")
|
||||
public ResponseEntity<org.springaicommunity.skills.model.ConversationMetadata> createConversation(
|
||||
@RequestBody Map<String, String> 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<List<org.springaicommunity.skills.model.ConversationMessage>> getMessages(
|
||||
@PathVariable String conversationId) {
|
||||
return ResponseEntity.ok(storageService.loadMessages(conversationId));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取会话元数据
|
||||
*/
|
||||
@GetMapping("/conversations/{conversationId}")
|
||||
public ResponseEntity<org.springaicommunity.skills.model.ConversationMetadata> 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<Void> updateConversation(
|
||||
@PathVariable String conversationId,
|
||||
@RequestBody Map<String, String> request) {
|
||||
String title = request.get("title");
|
||||
if (title != null) {
|
||||
storageService.updateTitle(conversationId, title);
|
||||
}
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除会话
|
||||
*/
|
||||
@DeleteMapping("/conversations/{conversationId}")
|
||||
public ResponseEntity<Void> 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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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();
|
||||
|
||||
|
||||
@@ -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<ConversationMessage> 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<ConversationMessage> 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<ConversationMessage> 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<ConversationMetadata> listConversations() {
|
||||
try (Stream<Path> 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"));
|
||||
}
|
||||
}
|
||||
+1376
-786
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -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 = '<i data-lucide="user" class="icon-sm"></i>';
|
||||
|
||||
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 = '<i data-lucide="bot" class="icon-sm"></i>';
|
||||
|
||||
// 消息主体
|
||||
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 = `
|
||||
<span class="process-status">
|
||||
<i data-lucide="loader-2" class="icon-xs spinning"></i>
|
||||
<span class="status-text">思考中...</span>
|
||||
</span>
|
||||
<span class="process-toggle">
|
||||
<i data-lucide="chevron-down" class="icon-sm"></i>
|
||||
</span>
|
||||
`;
|
||||
|
||||
// 步骤列表
|
||||
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 = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
|
||||
|
||||
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 = `
|
||||
<div class="step-icon">
|
||||
<i data-lucide="brain" class="icon-xs"></i>
|
||||
</div>
|
||||
<div class="step-content">${this.escapeHtml(content)}</div>
|
||||
`;
|
||||
|
||||
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 '<div class="typing-indicator"><span></span><span></span><span></span></div>';
|
||||
},
|
||||
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 class="step-todo-list"></div>';
|
||||
}
|
||||
}
|
||||
|
||||
div.appendChild(header);
|
||||
step.innerHTML = `
|
||||
<div class="step-icon">
|
||||
<i data-lucide="${icon}" class="icon-xs"></i>
|
||||
</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">${title}</div>
|
||||
${isTodoWrite ? '' : `<div class="step-args"><code>${this.escapeHtml(ChatUtils.formatJson(args))}</code></div>`}
|
||||
${details}
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 如果是 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 = `
|
||||
<div class="step-icon">
|
||||
<i data-lucide="check-circle" class="icon-xs"></i>
|
||||
</div>
|
||||
<div class="step-content">
|
||||
<div class="step-title">工具返回: ${toolName}</div>
|
||||
<div class="step-result">${this.escapeHtml(displayResponse)}</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
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: '<i data-lucide="circle" class="icon-xs"></i>',
|
||||
in_progress: '<i data-lucide="loader-2" class="icon-xs spinning"></i>',
|
||||
completed: '<i data-lucide="check-circle" class="icon-xs"></i>'
|
||||
};
|
||||
|
||||
item.innerHTML = `
|
||||
<span class="todo-icon">${icons[todo.status] || icons.pending}</span>
|
||||
<span class="todo-text">${this.escapeHtml(todo.content)}</span>
|
||||
`;
|
||||
|
||||
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 = `
|
||||
<div class="step-progress-bar">
|
||||
<div class="step-progress-fill" style="width: ${percentage}%"></div>
|
||||
</div>
|
||||
<div class="step-progress-info">
|
||||
<span>${completed}/${total} 完成</span>
|
||||
<span>${percentage}%</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 任务列表
|
||||
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: '<i data-lucide="circle" class="icon-xs"></i>',
|
||||
in_progress: '<i data-lucide="loader-2" class="icon-xs spinning"></i>',
|
||||
completed: '<i data-lucide="check-circle" class="icon-xs"></i>'
|
||||
};
|
||||
|
||||
return div;
|
||||
item.innerHTML = `
|
||||
<span class="todo-icon">${icons[todo.status] || icons.pending}</span>
|
||||
<span class="todo-text">${this.escapeHtml(todo.content)}</span>
|
||||
`;
|
||||
|
||||
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 = `
|
||||
<span class="todo-status">${icons[todo.status] || '[ ]'}</span>
|
||||
<span class="todo-content">${todo.content}</span>
|
||||
`;
|
||||
|
||||
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 = '<i data-lucide="copy" class="icon-xs"></i>';
|
||||
copyBtn.title = '复制';
|
||||
|
||||
copyBtn.addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(block.textContent);
|
||||
copyBtn.textContent = '已复制!';
|
||||
copyBtn.innerHTML = '<i data-lucide="check" class="icon-xs"></i>';
|
||||
copyBtn.classList.add('copied');
|
||||
lucide.createIcons();
|
||||
setTimeout(() => {
|
||||
copyBtn.textContent = '复制';
|
||||
copyBtn.innerHTML = '<i data-lucide="copy" class="icon-xs"></i>';
|
||||
copyBtn.classList.remove('copied');
|
||||
lucide.createIcons();
|
||||
}, 2000);
|
||||
} catch (err) {
|
||||
copyBtn.textContent = '复制失败';
|
||||
copyBtn.innerHTML = '<i data-lucide="x" class="icon-xs"></i>';
|
||||
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 = `
|
||||
<div class="welcome-message">
|
||||
<div class="welcome-icon">
|
||||
<i data-lucide="sparkles" class="icon-xl"></i>
|
||||
</div>
|
||||
<h2 class="welcome-title">有什么可以帮你的?</h2>
|
||||
<p class="welcome-subtitle">我可以帮你执行定价流程、管理任务、查询数据等</p>
|
||||
|
||||
<div class="quick-actions">
|
||||
<button class="quick-action-btn" data-prompt="请帮我为"深圳某某科技有限公司"执行完整的定价流程">
|
||||
<i data-lucide="calculator" class="icon-sm"></i>
|
||||
<span>执行定价流程</span>
|
||||
</button>
|
||||
<button class="quick-action-btn" data-prompt="分析最近3个月的定价数据,找出异常客户">
|
||||
<i data-lucide="bar-chart-3" class="icon-sm"></i>
|
||||
<span>数据分析</span>
|
||||
</button>
|
||||
<button class="quick-action-btn" data-prompt="获取"测试企业"的风险成本率">
|
||||
<i data-lucide="search" class="icon-sm"></i>
|
||||
<span>查询风险成本</span>
|
||||
</button>
|
||||
<button class="quick-action-btn" data-prompt="请解释历史行为定价法的适用场景">
|
||||
<i data-lucide="book-open" class="icon-sm"></i>
|
||||
<span>定价方法说明</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
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 = '<li class="nav-item-empty">暂无历史对话</li>';
|
||||
return;
|
||||
}
|
||||
|
||||
navList.innerHTML = conversations.map(conv => {
|
||||
const isActive = conv.id === currentId;
|
||||
const date = this.formatDate(conv.updatedAt);
|
||||
return `
|
||||
<li class="nav-item ${isActive ? 'active' : ''}" data-conversation-id="${conv.id}">
|
||||
<i data-lucide="message-square" class="icon-sm"></i>
|
||||
<span class="nav-item-text" title="${this.escapeHtml(conv.title)}">
|
||||
${this.escapeHtml(conv.title)}
|
||||
</span>
|
||||
<button class="btn-delete-conv" title="删除">
|
||||
<i data-lucide="x" class="icon-xs"></i>
|
||||
</button>
|
||||
</li>
|
||||
`;
|
||||
}).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) + '...';
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user