fix: Phase 6联调 — 插件管理器端口修正 + 多模型配置系统整合 + 历史消息刷新修复
## 调试日志
### 1. 插件管理器启动失败
- **症状**: DevTools 显示插件管理器一直"已停止",手动启动正常
- **排查**: 对比 process-manager.js 传入的环境变量 vs plugin-manager config.go 读取的变量
- **根因**: config.js 传入 PLUGIN_MANAGER_PORT=8094,但 config.go 读取 os.Getenv("PORT"),env 名不匹配。且 process.env 中 PORT 泄露时被误读为 9090,与 DevTools 端口冲突
- **修复**: config.js 将 PLUGIN_MANAGER_PORT → PORT,使 env 名与代码一致 (c3055f4)
### 2. 历史消息刷新后消失
- **症状**: 浏览器刷新后聊天历史清空
- **排查**: WebSocket history_response handler 中 if (msg.messages) 对空数组 [] 为 truthy
- **根因**: 后端返回空的 history_response (缓存为空) 时,空数组覆盖了 HTTP 已加载的消息
- **修复**: useWebSocket.ts 改为 if (msg.messages && msg.messages.length > 0),空数组走 else-if 分支仅打日志,不覆盖已有消息
### 3. Phase 6 多模型配置系统
- Gateway: ModelsConfigStore (JSON文件持久化) + Admin CRUD API (providers/models/routing)
- ai-core: ModelSelector 支持按 purpose 选择 + fallback_chain,无配置时回退 .env
- DevTools: 模型配置管理面板 (Providers/Models/Routing 三Tab)、在线模型查询代理、路由表单 checkbox 多选、关键词搜索过滤
- .gitignore: models.json + platform_configs.json
### 4. 多端客户端追踪
- Hub 新增 knownClients 映射 (clientID → KnownClient),在线/离线状态追踪
- 客户端备注持久化到 PostgreSQL
- DevTools 客户端管理面板
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -7,8 +7,8 @@ import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"github.com/yourname/cyrene-ai/pkg/logger"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -50,6 +50,9 @@ func (h *ChatHandler) HandleWebSocket(c *gin.Context) {
|
||||
// 从query参数获取token和session_id
|
||||
token := c.Query("token")
|
||||
sessionID := c.Query("session_id")
|
||||
clientID := c.Query("client_id")
|
||||
deviceName := c.Query("device_name")
|
||||
userAgent := c.Request.UserAgent()
|
||||
|
||||
if token == "" {
|
||||
// 也尝试从Authorization头读取
|
||||
@@ -93,7 +96,7 @@ func (h *ChatHandler) HandleWebSocket(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 创建客户端
|
||||
client := ws.NewClient(h.hub, conn, userID, sessionID)
|
||||
client := ws.NewClient(h.hub, conn, userID, sessionID, clientID, deviceName, userAgent)
|
||||
|
||||
// 注册到Hub
|
||||
h.hub.Register(client)
|
||||
@@ -128,7 +131,7 @@ func (h *ChatHandler) handleChatMessage(client *ws.Client, msg ws.ClientMessage)
|
||||
|
||||
// 持久化用户消息到数据库(在 WebSocket 发送之前)
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, "user", "chat", msg.Content); err != nil {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, "user", "chat", msg.Content, client.ClientID); err != nil {
|
||||
logger.Printf("[chat] 持久化用户消息失败: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -168,6 +171,10 @@ func (h *ChatHandler) handleChatMessage(client *ws.Client, msg ws.ClientMessage)
|
||||
Role: "user",
|
||||
Content: msg.Content,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
ClientInfo: &ws.ClientInfo{
|
||||
ClientID: client.ClientID,
|
||||
DeviceName: client.DeviceName,
|
||||
},
|
||||
}
|
||||
if len(msg.Attachments) > 0 {
|
||||
userMsg.Attachments = msg.Attachments
|
||||
@@ -229,13 +236,13 @@ func (h *ChatHandler) streamResponse(client *ws.Client, mode string, reqBody []b
|
||||
// 增大 scanner buffer 以处理大块 SSE 数据
|
||||
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
|
||||
|
||||
// 通知前端 AI 开始生成回复
|
||||
client.SendMessage(ws.ServerMessage{
|
||||
Type: "stream_start",
|
||||
MessageID: "msg_" + generateID(),
|
||||
SessionID: client.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
// 通知前端 AI 开始生成回复
|
||||
client.SendMessage(ws.ServerMessage{
|
||||
Type: "stream_start",
|
||||
MessageID: "msg_" + generateID(),
|
||||
SessionID: client.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
|
||||
var fullText string
|
||||
var msgID string
|
||||
@@ -312,24 +319,30 @@ func (h *ChatHandler) streamResponse(client *ws.Client, mode string, reqBody []b
|
||||
reviewMsgID := fmt.Sprintf("%s_r%d", msgID, i)
|
||||
// 持久化每条审查消息
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, role, msgType, rm.Content); err != nil {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, role, msgType, rm.Content, client.ClientID); err != nil {
|
||||
logger.Printf("[chat] 持久化审查消息失败: %v", err)
|
||||
}
|
||||
}
|
||||
clientInfo := &ws.ClientInfo{
|
||||
ClientID: client.ClientID,
|
||||
DeviceName: client.DeviceName,
|
||||
}
|
||||
h.hub.CacheMessage(client.UserID, client.SessionID, ws.Message{
|
||||
ID: reviewMsgID,
|
||||
Role: role,
|
||||
Content: rm.Content,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
ID: reviewMsgID,
|
||||
Role: role,
|
||||
Content: rm.Content,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
ClientInfo: clientInfo,
|
||||
})
|
||||
client.SendMessage(ws.ServerMessage{
|
||||
Type: "response",
|
||||
MessageID: reviewMsgID,
|
||||
Content: rm.Content,
|
||||
Role: role,
|
||||
MsgType: msgType,
|
||||
SessionID: client.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Type: "response",
|
||||
MessageID: reviewMsgID,
|
||||
Content: rm.Content,
|
||||
Role: role,
|
||||
MsgType: msgType,
|
||||
SessionID: client.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
ClientInfo: clientInfo,
|
||||
})
|
||||
// 使用 MessageScheduler 计算的 per-message 延迟
|
||||
if rm.DelayMs > 0 {
|
||||
@@ -416,7 +429,7 @@ func (h *ChatHandler) streamResponse(client *ws.Client, mode string, reqBody []b
|
||||
// 如果有审查消息,每条已单独持久化,跳过 fullText 以避免重复
|
||||
if !hasReview && fullText != "" {
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, "assistant", "chat", fullText); err != nil {
|
||||
if err := h.sessionStore.AddMessage(client.SessionID, "assistant", "chat", fullText, client.ClientID); err != nil {
|
||||
logger.Printf("[chat] 持久化 AI 回复失败: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -426,6 +439,10 @@ func (h *ChatHandler) streamResponse(client *ws.Client, mode string, reqBody []b
|
||||
Role: "assistant",
|
||||
Content: fullText,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
ClientInfo: &ws.ClientInfo{
|
||||
ClientID: client.ClientID,
|
||||
DeviceName: client.DeviceName,
|
||||
},
|
||||
})
|
||||
}
|
||||
// RecordMessage 使用不带 [review] 标记的文本
|
||||
@@ -451,7 +468,6 @@ func (h *ChatHandler) handleVoiceInput(client *ws.Client, msg ws.ClientMessage)
|
||||
client.SendMessage(response)
|
||||
}
|
||||
|
||||
|
||||
// handleHistoryRequest 处理历史消息请求
|
||||
func (h *ChatHandler) handleHistoryRequest(client *ws.Client, msg ws.ClientMessage) {
|
||||
// 优先使用请求中的 session_id,否则使用客户端的 session_id
|
||||
@@ -469,19 +485,28 @@ func (h *ChatHandler) handleHistoryRequest(client *ws.Client, msg ws.ClientMessa
|
||||
logger.Printf("[history] 从数据库恢复会话历史: session=%s, %d 条消息", sessionID, len(dbMessages))
|
||||
// 恢复到内存缓存
|
||||
for _, dbMsg := range dbMessages {
|
||||
var ci *ws.ClientInfo
|
||||
if dbMsg.ClientID != "" {
|
||||
ci = h.hub.ClientInfo(dbMsg.ClientID)
|
||||
if ci == nil {
|
||||
ci = &ws.ClientInfo{ClientID: dbMsg.ClientID}
|
||||
}
|
||||
}
|
||||
messages = append(messages, ws.Message{
|
||||
ID: fmt.Sprintf("db_%d", dbMsg.ID),
|
||||
Role: dbMsg.Role,
|
||||
MsgType: dbMsg.MsgType,
|
||||
Content: dbMsg.Content,
|
||||
Timestamp: dbMsg.CreatedAt.UnixMilli(),
|
||||
ID: fmt.Sprintf("db_%d", dbMsg.ID),
|
||||
Role: dbMsg.Role,
|
||||
MsgType: dbMsg.MsgType,
|
||||
Content: dbMsg.Content,
|
||||
Timestamp: dbMsg.CreatedAt.UnixMilli(),
|
||||
ClientInfo: ci,
|
||||
})
|
||||
h.hub.CacheMessage(client.UserID, sessionID, ws.Message{
|
||||
ID: fmt.Sprintf("db_%d", dbMsg.ID),
|
||||
Role: dbMsg.Role,
|
||||
MsgType: dbMsg.MsgType,
|
||||
Content: dbMsg.Content,
|
||||
Timestamp: dbMsg.CreatedAt.UnixMilli(),
|
||||
ID: fmt.Sprintf("db_%d", dbMsg.ID),
|
||||
Role: dbMsg.Role,
|
||||
MsgType: dbMsg.MsgType,
|
||||
Content: dbMsg.Content,
|
||||
Timestamp: dbMsg.CreatedAt.UnixMilli(),
|
||||
ClientInfo: ci,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -534,72 +559,216 @@ func (h *ChatHandler) HandleProactiveMessage(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户是否在线
|
||||
// Parse content to split (action) from chat text.
|
||||
segments := parseProactiveContent(req.Content)
|
||||
|
||||
// Check online status.
|
||||
onlineCount := h.hub.UserClientCount(req.UserID)
|
||||
if onlineCount == 0 {
|
||||
// Phase 2: 离线时排队,等待用户重连后推送
|
||||
data, _ := json.Marshal(ws.ServerMessage{
|
||||
Type: "response",
|
||||
MessageID: "proactive_" + generateID(),
|
||||
Content: req.Content,
|
||||
Role: "assistant",
|
||||
MsgType: "proactive",
|
||||
SessionID: req.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
h.hub.QueueProactiveMessage(req.UserID, data)
|
||||
logger.Printf("[proactive] 用户离线,消息已排队: user=%s", req.UserID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"reason": "queued",
|
||||
"message": "用户离线,消息已排队等待重连后推送",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 构建主动消息
|
||||
msgID := "proactive_" + generateID()
|
||||
msg := ws.ServerMessage{
|
||||
Type: "response",
|
||||
MessageID: msgID,
|
||||
Content: req.Content,
|
||||
Role: "assistant",
|
||||
MsgType: "proactive",
|
||||
SessionID: req.SessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
logger.Printf("[proactive] 序列化消息失败: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "内部错误"})
|
||||
return
|
||||
}
|
||||
|
||||
h.hub.SendToUser(req.UserID, data)
|
||||
|
||||
// 同时缓存到对话历史(使用 admin 的主 session)
|
||||
sessionID := req.SessionID
|
||||
if sessionID == "" {
|
||||
sessionID = "session_admin_main"
|
||||
}
|
||||
h.hub.CacheMessage(req.UserID, sessionID, ws.Message{
|
||||
ID: msgID,
|
||||
Role: "assistant",
|
||||
Content: req.Content,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
})
|
||||
h.hub.RecordMessage(sessionID, "assistant", req.Content)
|
||||
|
||||
logger.Printf("[proactive] 主动消息已推送: user=%s, online=%d, content_len=%d", req.UserID, onlineCount, len(req.Content))
|
||||
timestamp := time.Now().UnixMilli()
|
||||
|
||||
for i, seg := range segments {
|
||||
msgID := fmt.Sprintf("proactive_%s_%d", generateID(), i)
|
||||
msgType := "chat"
|
||||
role := "assistant"
|
||||
if seg.msgType == "action" {
|
||||
msgType = "action"
|
||||
role = "action"
|
||||
}
|
||||
|
||||
msg := ws.ServerMessage{
|
||||
Type: "response",
|
||||
MessageID: msgID,
|
||||
Content: seg.content,
|
||||
Role: role,
|
||||
MsgType: msgType,
|
||||
SessionID: sessionID,
|
||||
Timestamp: timestamp + int64(i),
|
||||
}
|
||||
|
||||
data, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
logger.Printf("[proactive] 序列化消息失败: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
if onlineCount == 0 {
|
||||
h.hub.QueueProactiveMessage(req.UserID, data)
|
||||
} else {
|
||||
h.hub.SendToUser(req.UserID, data)
|
||||
if i < len(segments)-1 {
|
||||
delay := 200 + int(time.Now().UnixNano()%200)
|
||||
time.Sleep(time.Duration(delay) * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// Persist to database so proactive messages survive restarts.
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
if err := h.sessionStore.AddMessage(sessionID, role, msgType, seg.content, ""); err != nil {
|
||||
logger.Printf("[proactive] 持久化消息失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Cache each segment to conversation history.
|
||||
h.hub.CacheMessage(req.UserID, sessionID, ws.Message{
|
||||
ID: msgID,
|
||||
Role: role,
|
||||
MsgType: msgType,
|
||||
Content: seg.content,
|
||||
Timestamp: timestamp,
|
||||
})
|
||||
h.hub.RecordMessage(sessionID, role, seg.content)
|
||||
}
|
||||
|
||||
logger.Printf("[proactive] 主动消息已推送: user=%s, online=%d, segments=%d", req.UserID, onlineCount, len(segments))
|
||||
|
||||
reason := "delivered"
|
||||
if onlineCount == 0 {
|
||||
reason = "queued"
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "消息已推送",
|
||||
"segments": len(segments),
|
||||
"delivered": onlineCount,
|
||||
"reason": reason,
|
||||
})
|
||||
}
|
||||
|
||||
// proactiveSegment holds a parsed piece of a proactive message.
|
||||
type proactiveSegment struct {
|
||||
msgType string // "chat" or "action"
|
||||
content string
|
||||
}
|
||||
|
||||
// parseProactiveContent splits text by (parenthesized actions).
|
||||
// "(笑) 你好呀 (调暗灯光) 今天过得如何" →
|
||||
// [action: "笑", chat: "你好呀", action: "调暗灯光", chat: "今天过得如何"]
|
||||
func parseProactiveContent(text string) []proactiveSegment {
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
var segments []proactiveSegment
|
||||
remaining := []rune(text)
|
||||
|
||||
for len(remaining) > 0 {
|
||||
actionStart := -1 // index in remaining
|
||||
actionEnd := -1 // index after closing paren
|
||||
var actionContent string
|
||||
|
||||
for i, r := range remaining {
|
||||
if r == '(' || r == '(' {
|
||||
actionStart = i
|
||||
closeRune := ')'
|
||||
if r == '(' {
|
||||
closeRune = ')'
|
||||
}
|
||||
for j := i + 1; j < len(remaining); j++ {
|
||||
if remaining[j] == closeRune {
|
||||
actionEnd = j + 1
|
||||
actionContent = string(remaining[i+1 : j])
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if actionStart >= 0 {
|
||||
if actionStart > 0 {
|
||||
prefix := strings.TrimSpace(string(remaining[:actionStart]))
|
||||
if prefix != "" {
|
||||
segments = append(segments, proactiveSegment{msgType: "chat", content: prefix})
|
||||
}
|
||||
}
|
||||
content := strings.TrimSpace(actionContent)
|
||||
if content != "" {
|
||||
segments = append(segments, proactiveSegment{msgType: "action", content: content})
|
||||
}
|
||||
remaining = remaining[actionEnd:]
|
||||
} else {
|
||||
text := strings.TrimSpace(string(remaining))
|
||||
if text != "" {
|
||||
segments = append(segments, proactiveSegment{msgType: "chat", content: text})
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(segments) == 0 && text != "" {
|
||||
segments = append(segments, proactiveSegment{msgType: "chat", content: strings.TrimSpace(text)})
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
// ========== 多端客户端管理 API ==========
|
||||
|
||||
// HandleListClients returns all known clients for the authenticated user.
|
||||
// GET /api/v1/admin/clients
|
||||
func (h *ChatHandler) HandleListClients(c *gin.Context) {
|
||||
userID := c.Query("user_id")
|
||||
if userID == "" {
|
||||
userID = "admin"
|
||||
}
|
||||
clients := h.hub.GetKnownClients(userID)
|
||||
|
||||
// Merge with persisted notes from DB
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
dbClients, err := h.sessionStore.GetClients(userID)
|
||||
if err == nil {
|
||||
noteByID := make(map[string]string)
|
||||
for _, dc := range dbClients {
|
||||
noteByID[dc.ClientID] = dc.Note
|
||||
}
|
||||
for i := range clients {
|
||||
if note, ok := noteByID[clients[i].ClientID]; ok && note != "" {
|
||||
clients[i].Note = note
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"clients": clients,
|
||||
"total": len(clients),
|
||||
})
|
||||
}
|
||||
|
||||
// HandleUpdateClientNote sets a label/note on a client.
|
||||
// PUT /api/v1/admin/clients/:id/note
|
||||
func (h *ChatHandler) HandleUpdateClientNote(c *gin.Context) {
|
||||
clientID := c.Param("id")
|
||||
var req struct {
|
||||
Note string `json:"note"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求参数无效"})
|
||||
return
|
||||
}
|
||||
|
||||
// Update in-memory
|
||||
if !h.hub.UpdateClientNote(clientID, req.Note) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "客户端未找到"})
|
||||
return
|
||||
}
|
||||
|
||||
// Persist to DB
|
||||
if h.sessionStore != nil && h.sessionStore.IsAvailable() {
|
||||
if err := h.sessionStore.UpdateClientNote(clientID, req.Note); err != nil {
|
||||
logger.Printf("[clients] 持久化备注失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok", "client_id": clientID, "note": req.Note})
|
||||
}
|
||||
|
||||
func generateID() string {
|
||||
return time.Now().Format("20060102150405") + randomStr(6)
|
||||
}
|
||||
@@ -609,7 +778,7 @@ func randomStr(n int) string {
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
// fallback: deterministic but hard to predict
|
||||
for i := range b {
|
||||
b[i] = byte(time.Now().UnixNano()%256)
|
||||
b[i] = byte(time.Now().UnixNano() % 256)
|
||||
}
|
||||
}
|
||||
return hex.EncodeToString(b)[:n]
|
||||
@@ -637,4 +806,3 @@ func parseMultiMessage(text string) []string {
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user