diff --git a/internal/app/app.go b/internal/app/app.go
index 8dec42b5..4daaea53 100644
--- a/internal/app/app.go
+++ b/internal/app/app.go
@@ -98,8 +98,9 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
- // CORS中间件
+ // CORS 与 Gzip 压缩中间件
router.Use(corsMiddleware(cfg.Server.CORSAllowedOrigins))
+ router.Use(gzipMiddleware())
// 初始化数据库
dbPath := cfg.Database.Path
diff --git a/internal/app/gzip.go b/internal/app/gzip.go
new file mode 100644
index 00000000..166baf89
--- /dev/null
+++ b/internal/app/gzip.go
@@ -0,0 +1,187 @@
+package app
+
+import (
+ "bufio"
+ "compress/gzip"
+ "io"
+ "net"
+ "net/http"
+ "strings"
+ "sync"
+
+ "github.com/gin-gonic/gin"
+)
+
+var gzipWriterPool = sync.Pool{
+ New: func() any {
+ w, _ := gzip.NewWriterLevel(io.Discard, gzip.BestSpeed)
+ return w
+ },
+}
+
+// gzipMiddleware 对可压缩的 JSON/文本/静态资源响应启用 Gzip 压缩,
+// 自动跳过 SSE、WebSocket、二进制压缩格式及客户端未声明 gzip 的请求。
+func gzipMiddleware() gin.HandlerFunc {
+ return func(c *gin.Context) {
+ if !shouldTryGzipRequest(c.Request) {
+ c.Next()
+ return
+ }
+
+ origWriter := c.Writer
+ gw := &gzipResponseWriter{
+ ResponseWriter: origWriter,
+ }
+ c.Writer = gw
+ defer func() {
+ gw.close()
+ c.Writer = origWriter
+ }()
+
+ c.Next()
+ }
+}
+
+func shouldTryGzipRequest(r *http.Request) bool {
+ if r == nil || r.Method == http.MethodHead {
+ return false
+ }
+ if !strings.Contains(strings.ToLower(r.Header.Get("Accept-Encoding")), "gzip") {
+ return false
+ }
+ if r.Header.Get("Upgrade") != "" {
+ return false
+ }
+ if strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/event-stream") {
+ return false
+ }
+ path := strings.ToLower(r.URL.Path)
+ if strings.HasSuffix(path, "/stream") ||
+ strings.HasSuffix(path, "/task-events") ||
+ strings.HasSuffix(path, "/events") ||
+ strings.Contains(path, "/ws") ||
+ strings.Contains(path, "/terminal") {
+ return false
+ }
+ return true
+}
+
+func shouldCompressResponse(status int, header http.Header) bool {
+ if status == http.StatusNoContent || status == http.StatusNotModified || (status >= 100 && status < 200) {
+ return false
+ }
+ if header.Get("Content-Encoding") != "" {
+ return false
+ }
+ ct := strings.ToLower(header.Get("Content-Type"))
+ if strings.Contains(ct, "text/event-stream") {
+ return false
+ }
+ if strings.HasPrefix(ct, "image/") && !strings.Contains(ct, "svg") {
+ return false
+ }
+ if strings.HasPrefix(ct, "video/") ||
+ strings.HasPrefix(ct, "audio/") ||
+ strings.HasPrefix(ct, "font/") ||
+ strings.Contains(ct, "application/gzip") ||
+ strings.Contains(ct, "application/zip") ||
+ strings.Contains(ct, "application/octet-stream") {
+ return false
+ }
+ return true
+}
+
+type gzipResponseWriter struct {
+ gin.ResponseWriter
+ gz *gzip.Writer
+ decided bool
+ compressing bool
+ statusCode int
+}
+
+func (w *gzipResponseWriter) decide(status int) {
+ if w.decided {
+ return
+ }
+ w.decided = true
+ if status == 0 {
+ status = http.StatusOK
+ }
+ w.statusCode = status
+ if !shouldCompressResponse(status, w.Header()) {
+ return
+ }
+ w.compressing = true
+ h := w.Header()
+ h.Set("Content-Encoding", "gzip")
+ h.Del("Content-Length")
+ vary := h.Get("Vary")
+ if vary == "" {
+ h.Set("Vary", "Accept-Encoding")
+ } else if !strings.Contains(strings.ToLower(vary), "accept-encoding") {
+ h.Set("Vary", vary+", Accept-Encoding")
+ }
+ gz := gzipWriterPool.Get().(*gzip.Writer)
+ gz.Reset(w.ResponseWriter)
+ w.gz = gz
+}
+
+func (w *gzipResponseWriter) WriteHeader(code int) {
+ if w.Written() {
+ return
+ }
+ w.decide(code)
+ w.ResponseWriter.WriteHeader(code)
+}
+
+func (w *gzipResponseWriter) WriteHeaderNow() {
+ if !w.decided {
+ w.decide(w.Status())
+ }
+ w.ResponseWriter.WriteHeaderNow()
+}
+
+func (w *gzipResponseWriter) Write(data []byte) (int, error) {
+ if !w.decided {
+ if w.Header().Get("Content-Type") == "" && len(data) > 0 {
+ w.Header().Set("Content-Type", http.DetectContentType(data))
+ }
+ status := w.statusCode
+ if status == 0 {
+ status = w.ResponseWriter.Status()
+ }
+ if status == 0 {
+ status = http.StatusOK
+ }
+ w.decide(status)
+ }
+ if w.compressing && w.gz != nil {
+ return w.gz.Write(data)
+ }
+ return w.ResponseWriter.Write(data)
+}
+
+func (w *gzipResponseWriter) WriteString(s string) (int, error) {
+ return w.Write([]byte(s))
+}
+
+func (w *gzipResponseWriter) Flush() {
+ if w.compressing && w.gz != nil {
+ _ = w.gz.Flush()
+ }
+ w.ResponseWriter.Flush()
+}
+
+func (w *gzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ w.close()
+ return w.ResponseWriter.Hijack()
+}
+
+func (w *gzipResponseWriter) close() {
+ if w.gz != nil {
+ _ = w.gz.Close()
+ w.gz.Reset(io.Discard)
+ gzipWriterPool.Put(w.gz)
+ w.gz = nil
+ }
+}
diff --git a/internal/app/gzip_test.go b/internal/app/gzip_test.go
new file mode 100644
index 00000000..c039ba79
--- /dev/null
+++ b/internal/app/gzip_test.go
@@ -0,0 +1,87 @@
+package app
+
+import (
+ "compress/gzip"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestGzipMiddlewareCompressesJSONAndSkipsSSE(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ r := gin.New()
+ r.Use(gzipMiddleware())
+
+ payload := strings.Repeat(`{"toolName":"nmap","result":"open port 80/tcp http"}`, 200)
+ r.GET("/api/conversations/1", func(c *gin.Context) {
+ c.Data(http.StatusOK, "application/json; charset=utf-8", []byte(payload))
+ })
+ r.POST("/api/agent/stream", func(c *gin.Context) {
+ c.Header("Content-Type", "text/event-stream; charset=utf-8")
+ c.Writer.WriteHeader(http.StatusOK)
+ _, _ = c.Writer.Write([]byte("data: {\"type\":\"done\"}\n\n"))
+ c.Writer.Flush()
+ })
+ r.GET("/api/empty", func(c *gin.Context) {
+ c.Status(http.StatusNoContent)
+ })
+
+ // 1. JSON with Accept-Encoding: gzip should be compressed and round-trip cleanly.
+ req := httptest.NewRequest(http.MethodGet, "/api/conversations/1", nil)
+ req.Header.Set("Accept-Encoding", "gzip, deflate")
+ w := httptest.NewRecorder()
+ r.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if got := w.Header().Get("Content-Encoding"); got != "gzip" {
+ t.Fatalf("Content-Encoding = %q, want gzip", got)
+ }
+ if !strings.Contains(w.Header().Get("Vary"), "Accept-Encoding") {
+ t.Fatalf("Vary = %q, want Accept-Encoding", w.Header().Get("Vary"))
+ }
+ if w.Body.Len() >= len(payload)/4 {
+ t.Fatalf("compressed len = %d, expected much smaller than %d", w.Body.Len(), len(payload))
+ }
+ gr, err := gzip.NewReader(w.Body)
+ if err != nil {
+ t.Fatalf("gzip.NewReader: %v", err)
+ }
+ decoded, err := io.ReadAll(gr)
+ _ = gr.Close()
+ if err != nil {
+ t.Fatalf("read gzip body: %v", err)
+ }
+ if string(decoded) != payload {
+ t.Fatalf("decoded payload mismatch: len=%d want=%d", len(decoded), len(payload))
+ }
+
+ // 2. SSE stream endpoint must NOT be gzipped.
+ sseReq := httptest.NewRequest(http.MethodPost, "/api/agent/stream", nil)
+ sseReq.Header.Set("Accept-Encoding", "gzip")
+ sseW := httptest.NewRecorder()
+ r.ServeHTTP(sseW, sseReq)
+ if got := sseW.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("SSE Content-Encoding = %q, want empty", got)
+ }
+ if !strings.Contains(sseW.Body.String(), `"done"`) {
+ t.Fatalf("unexpected SSE body: %q", sseW.Body.String())
+ }
+
+ // 3. 204 No Content must NOT set Content-Encoding.
+ emptyReq := httptest.NewRequest(http.MethodGet, "/api/empty", nil)
+ emptyReq.Header.Set("Accept-Encoding", "gzip")
+ emptyW := httptest.NewRecorder()
+ r.ServeHTTP(emptyW, emptyReq)
+ if emptyW.Code != http.StatusNoContent {
+ t.Fatalf("204 status = %d", emptyW.Code)
+ }
+ if got := emptyW.Header().Get("Content-Encoding"); got != "" {
+ t.Fatalf("204 Content-Encoding = %q, want empty", got)
+ }
+}
diff --git a/internal/database/conversation.go b/internal/database/conversation.go
index e79756d3..3a990a91 100644
--- a/internal/database/conversation.go
+++ b/internal/database/conversation.go
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strings"
"time"
+ "unicode/utf8"
"github.com/google/uuid"
"go.uber.org/zap"
@@ -494,6 +495,302 @@ func (db *DB) GetConversationLite(id string) (*Conversation, error) {
return &conv, nil
}
+const (
+ summaryInlineToolArgsMaxBytes = 512
+ summaryInlineThinkingMaxRunes = 512
+ summaryInlineMessageMaxRunes = 4000
+ summaryInlineRawDataMaxBytes = 4096
+ summaryFallbackReasoningRunes = 20000
+)
+
+// GetConversationSummary 获取对话(摘要版):返回全部消息与裁剪后的过程详情摘要。
+// 跳过 progress 噪音事件,剥离大体积工具输出、大参数、长思考正文与重复 finalText,
+// 仅保留前端列表与状态标签所需的轻量元数据;完整单条载荷在用户展开时再按需拉取。
+func (db *DB) GetConversationSummary(id string) (*Conversation, error) {
+ var conv Conversation
+ var createdAt, updatedAt string
+ var pinned int
+
+ var projectID sql.NullString
+ var roleName sql.NullString
+ var agentMode sql.NullString
+ err := db.QueryRow(
+ "SELECT id, title, pinned, created_at, updated_at, project_id, role_name, agent_mode FROM conversations WHERE id = ?",
+ id,
+ ).Scan(&conv.ID, &conv.Title, &pinned, &createdAt, &updatedAt, &projectID, &roleName, &agentMode)
+ if err != nil {
+ if err == sql.ErrNoRows {
+ return nil, fmt.Errorf("对话不存在")
+ }
+ return nil, fmt.Errorf("查询对话失败: %w", err)
+ }
+ if projectID.Valid {
+ conv.ProjectID = strings.TrimSpace(projectID.String)
+ }
+ if roleName.Valid {
+ conv.RoleName = normalizeConversationRoleName(roleName.String)
+ }
+ if agentMode.Valid {
+ conv.AgentMode = normalizeConversationAgentMode(agentMode.String)
+ }
+
+ conv.CreatedAt = parseDBTime(createdAt)
+ conv.UpdatedAt = parseDBTime(updatedAt)
+ conv.Pinned = pinned != 0
+
+ messages, err := db.GetMessages(id)
+ if err != nil {
+ return nil, fmt.Errorf("加载消息失败: %w", err)
+ }
+ conv.Messages = messages
+
+ processDetailsMap, err := db.GetProcessDetailsByConversationForSummary(id)
+ if err != nil {
+ db.logger.Warn("加载过程详情摘要失败", zap.Error(err))
+ processDetailsMap = make(map[string][]ProcessDetail)
+ }
+
+ for i := range conv.Messages {
+ hasThinkingDetail := false
+ if details, ok := processDetailsMap[conv.Messages[i].ID]; ok {
+ details = DedupeConsecutiveProcessDetails(details)
+ detailsJSON := make([]map[string]interface{}, 0, len(details))
+ for _, detail := range details {
+ if detail.EventType == "thinking" || detail.EventType == "reasoning_chain" {
+ hasThinkingDetail = true
+ }
+ detailsJSON = append(detailsJSON, summarizeProcessDetailRow(detail, db.logger))
+ }
+ conv.Messages[i].ProcessDetails = detailsJSON
+ }
+ // 若过程详情中已包含思考记录,避免重复传输聚合后的 reasoningContent。
+ if hasThinkingDetail {
+ conv.Messages[i].ReasoningContent = ""
+ } else if conv.Messages[i].ReasoningContent != "" {
+ conv.Messages[i].ReasoningContent, _ = truncateRunes(conv.Messages[i].ReasoningContent, summaryFallbackReasoningRunes)
+ }
+ }
+
+ return &conv, nil
+}
+
+// GetProcessDetailsByConversationForSummary 获取对话的非 progress 过程详情(按消息分组)。
+func (db *DB) GetProcessDetailsByConversationForSummary(conversationID string) (map[string][]ProcessDetail, error) {
+ rows, err := db.Query(
+ "SELECT id, message_id, conversation_id, event_type, message, data, created_at FROM process_details WHERE conversation_id = ? AND event_type != 'progress' ORDER BY created_at ASC, rowid ASC",
+ conversationID,
+ )
+ if err != nil {
+ return nil, fmt.Errorf("查询过程详情失败: %w", err)
+ }
+ defer rows.Close()
+
+ detailsMap := make(map[string][]ProcessDetail)
+ for rows.Next() {
+ var detail ProcessDetail
+ var createdAt string
+
+ if err := rows.Scan(&detail.ID, &detail.MessageID, &detail.ConversationID, &detail.EventType, &detail.Message, &detail.Data, &createdAt); err != nil {
+ return nil, fmt.Errorf("扫描过程详情失败: %w", err)
+ }
+ detail.CreatedAt = parseDBTime(createdAt)
+ detailsMap[detail.MessageID] = append(detailsMap[detail.MessageID], detail)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, fmt.Errorf("遍历过程详情失败: %w", err)
+ }
+ return detailsMap, nil
+}
+
+func truncateRunes(s string, maxRunes int) (string, bool) {
+ if maxRunes <= 0 || len(s) <= maxRunes {
+ return s, false
+ }
+ count := 0
+ for idx := range s {
+ if count == maxRunes {
+ return s[:idx], true
+ }
+ count++
+ }
+ return s, false
+}
+
+func hasNonEmptyToolArgs(m map[string]interface{}) (hasArgs bool, inlineSize int) {
+ if m == nil {
+ return false, 0
+ }
+ if obj, ok := m["argumentsObj"].(map[string]interface{}); ok && len(obj) > 0 {
+ if b, err := json.Marshal(obj); err == nil {
+ return true, len(b)
+ }
+ return true, summaryInlineToolArgsMaxBytes + 1
+ }
+ if raw, ok := m["arguments"]; ok && raw != nil {
+ switch v := raw.(type) {
+ case string:
+ trimmed := strings.TrimSpace(v)
+ if trimmed == "" || trimmed == "{}" || trimmed == "null" {
+ return false, 0
+ }
+ return true, len(trimmed)
+ default:
+ if b, err := json.Marshal(v); err == nil {
+ trimmed := strings.TrimSpace(string(b))
+ if trimmed == "" || trimmed == "{}" || trimmed == "null" {
+ return false, 0
+ }
+ return true, len(trimmed)
+ }
+ return true, summaryInlineToolArgsMaxBytes + 1
+ }
+ }
+ return false, 0
+}
+
+func hasNonEmptyToolResult(d ProcessDetail, m map[string]interface{}) bool {
+ if strings.TrimSpace(d.Message) != "" {
+ return true
+ }
+ if m == nil {
+ return false
+ }
+ for _, key := range []string{"resultPreview", "result", "error", "output"} {
+ if v, ok := m[key]; ok && v != nil {
+ if s, ok := v.(string); ok {
+ if strings.TrimSpace(s) != "" {
+ return true
+ }
+ } else {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func summarizeProcessDetailRow(d ProcessDetail, logger *zap.Logger) map[string]interface{} {
+ var parsed interface{}
+ if d.Data != "" {
+ if err := json.Unmarshal([]byte(d.Data), &parsed); err != nil && logger != nil {
+ logger.Warn("解析过程详情数据失败", zap.Error(err))
+ }
+ }
+ m, _ := parsed.(map[string]interface{})
+ msg := d.Message
+ var outData interface{} = parsed
+
+ switch d.EventType {
+ case "tool_call":
+ msg = ""
+ out := make(map[string]interface{}, 12)
+ if m != nil {
+ for _, key := range []string{
+ "toolName", "toolCallId", "index", "total", "executionId",
+ "agentName", "agentRole", "agentScope", "orchestration", "agentFacing", "status",
+ } {
+ if v, ok := m[key]; ok && v != nil {
+ out[key] = v
+ }
+ }
+ hasArgs, argSize := hasNonEmptyToolArgs(m)
+ if hasArgs && argSize <= summaryInlineToolArgsMaxBytes {
+ if v, ok := m["argumentsObj"]; ok && v != nil {
+ out["argumentsObj"] = v
+ } else if v, ok := m["arguments"]; ok && v != nil {
+ out["arguments"] = v
+ }
+ out["_hasPayload"] = true
+ } else if hasArgs {
+ out["_payloadDeferred"] = true
+ out["_argsDeferred"] = true
+ out["_hasPayload"] = true
+ }
+ }
+ outData = out
+
+ case "tool_result":
+ hasResult := hasNonEmptyToolResult(d, m)
+ msg = ""
+ out := make(map[string]interface{}, 14)
+ if m != nil {
+ for _, key := range []string{
+ "toolName", "toolCallId", "index", "total", "executionId",
+ "agentName", "agentRole", "agentScope", "orchestration", "agentFacing",
+ "success", "isError", "status", "displayStatus", "blocked", "modelFacingIsError",
+ } {
+ if v, ok := m[key]; ok && v != nil {
+ out[key] = v
+ }
+ }
+ }
+ if hasResult {
+ out["_payloadDeferred"] = true
+ out["_hasPayload"] = true
+ }
+ outData = out
+
+ case "thinking", "reasoning_chain":
+ runeCount := utf8.RuneCountInString(msg)
+ if runeCount > summaryInlineThinkingMaxRunes {
+ msg = ""
+ out := map[string]interface{}{
+ "_payloadDeferred": true,
+ "_textLength": runeCount,
+ }
+ if m != nil {
+ if sid, ok := m["streamId"]; ok && sid != nil {
+ out["streamId"] = sid
+ }
+ }
+ outData = out
+ }
+
+ case "finalization_check":
+ msg, _ = truncateRunes(msg, summaryInlineMessageMaxRunes)
+ if m != nil {
+ out := make(map[string]interface{}, len(m))
+ for k, v := range m {
+ if k == "finalText" {
+ continue
+ }
+ out[k] = v
+ }
+ outData = out
+ }
+
+ default:
+ var truncated bool
+ msg, truncated = truncateRunes(msg, summaryInlineMessageMaxRunes)
+ if len(d.Data) > summaryInlineRawDataMaxBytes {
+ outData = map[string]interface{}{
+ "_payloadDeferred": true,
+ }
+ } else if truncated {
+ if m != nil {
+ out := make(map[string]interface{}, len(m)+1)
+ for k, v := range m {
+ out[k] = v
+ }
+ out["_payloadDeferred"] = true
+ outData = out
+ } else {
+ outData = map[string]interface{}{"_payloadDeferred": true}
+ }
+ }
+ }
+
+ return map[string]interface{}{
+ "id": d.ID,
+ "messageId": d.MessageID,
+ "conversationId": d.ConversationID,
+ "eventType": d.EventType,
+ "message": msg,
+ "data": outData,
+ "createdAt": d.CreatedAt,
+ }
+}
+
func normalizeConversationRoleName(roleName string) string {
roleName = strings.TrimSpace(roleName)
if roleName == "" {
diff --git a/internal/database/schemas/application.sql b/internal/database/schemas/application.sql
index 85267731..6e9dee00 100644
--- a/internal/database/schemas/application.sql
+++ b/internal/database/schemas/application.sql
@@ -862,6 +862,8 @@ CREATE INDEX idx_knowledge_retrieval_logs_message ON knowledge_retrieval_logs(me
CREATE INDEX idx_messages_conversation_id ON messages(conversation_id);
+CREATE INDEX idx_messages_conversation_created ON messages(conversation_id, created_at);
+
CREATE INDEX idx_model_token_usage_conversation ON model_token_usage(conversation_id);
CREATE INDEX idx_model_token_usage_created_at ON model_token_usage(created_at);
@@ -874,8 +876,12 @@ CREATE INDEX idx_notification_reads_user_read_at ON notification_reads_by_user(u
CREATE INDEX idx_process_details_conversation_id ON process_details(conversation_id);
+CREATE INDEX idx_process_details_conversation_created ON process_details(conversation_id, created_at);
+
CREATE INDEX idx_process_details_message_id ON process_details(message_id);
+CREATE INDEX idx_process_details_message_created ON process_details(message_id, created_at);
+
CREATE INDEX idx_project_fact_edges_project ON project_fact_edges(project_id);
CREATE INDEX idx_project_fact_edges_source ON project_fact_edges(project_id, source_fact_key);
diff --git a/internal/handler/conversation.go b/internal/handler/conversation.go
index 09fdce49..c296a5f3 100644
--- a/internal/handler/conversation.go
+++ b/internal/handler/conversation.go
@@ -251,17 +251,20 @@ func (h *ConversationHandler) GetConversation(c *gin.Context) {
id := c.Param("id")
// 默认轻量加载,只有用户需要展开详情时再按需拉取
+ // include_process_details=summary/compact 时返回裁剪后的过程详情摘要(不含工具大载荷/长思考正文)
// include_process_details=1/true 时返回全量 processDetails(兼容旧行为)
- includeStr := c.DefaultQuery("include_process_details", "0")
- include := includeStr == "1" || includeStr == "true" || includeStr == "yes"
+ includeStr := strings.ToLower(strings.TrimSpace(c.DefaultQuery("include_process_details", "0")))
var (
conv *database.Conversation
err error
)
- if include {
+ switch includeStr {
+ case "summary", "compact":
+ conv, err = h.db.GetConversationSummary(id)
+ case "1", "true", "yes":
conv, err = h.db.GetConversation(id)
- } else {
+ default:
conv, err = h.db.GetConversationLite(id)
}
if err != nil {
@@ -486,15 +489,19 @@ func processDetailsToJSON(logger *zap.Logger, db *database.DB, details []databas
if m, ok := data.(map[string]interface{}); ok {
enrichEmptyToolCallArgumentsFromExecution(logger, db, d, m)
}
+ msg := d.Message
if !includeToolPayload {
data = summarizeProcessDetailData(d.EventType, data)
+ if d.EventType == "tool_result" {
+ msg = ""
+ }
}
out = append(out, map[string]interface{}{
"id": d.ID,
"messageId": d.MessageID,
"conversationId": d.ConversationID,
"eventType": d.EventType,
- "message": d.Message,
+ "message": msg,
"data": data,
"createdAt": d.CreatedAt,
})
diff --git a/internal/handler/conversation_process_details_test.go b/internal/handler/conversation_process_details_test.go
index 66600b87..e1951b00 100644
--- a/internal/handler/conversation_process_details_test.go
+++ b/internal/handler/conversation_process_details_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"net/http/httptest"
"path/filepath"
+ "strings"
"testing"
"time"
@@ -262,3 +263,120 @@ func TestProcessDetailsPageBackfillsAgentFilesystemArgumentsFromPrefixedExecutio
t.Fatalf("arguments should be preserved in summarized page data: %#v", data)
}
}
+
+func TestGetConversationSummaryDefersLargePayloadsAndSkipsProgress(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ db, err := database.NewDB(filepath.Join(t.TempDir(), "conversation-summary.db"), zap.NewNop())
+ if err != nil {
+ t.Fatalf("NewDB: %v", err)
+ }
+ t.Cleanup(func() { _ = db.Close() })
+
+ conv, err := db.CreateConversation("heavy deepagent session", database.ConversationCreateMeta{})
+ if err != nil {
+ t.Fatalf("CreateConversation: %v", err)
+ }
+ msg, err := db.AddMessage(conv.ID, "assistant", "final report body", nil)
+ if err != nil {
+ t.Fatalf("AddMessage: %v", err)
+ }
+ if err := db.UpdateAssistantMessageFinalize(msg.ID, "final report body", nil, "duplicate reasoning fallback"); err != nil {
+ t.Fatalf("UpdateAssistantMessageFinalize: %v", err)
+ }
+
+ largeArgs := strings.Repeat("A", 4096)
+ largeOutput := strings.Repeat("open 80/tcp http\n", 1024)
+ largeThought := strings.Repeat("深入分析目标指纹与端口开放情况。", 120)
+
+ if err := db.AddProcessDetail(msg.ID, conv.ID, "progress", "heartbeat noise", nil); err != nil {
+ t.Fatalf("AddProcessDetail(progress): %v", err)
+ }
+ thoughtID, err := db.AddProcessDetailWithID(msg.ID, conv.ID, "thinking", largeThought, map[string]interface{}{"streamId": "s1"})
+ if err != nil {
+ t.Fatalf("AddProcessDetailWithID(thinking): %v", err)
+ }
+ callID, err := db.AddProcessDetailWithID(msg.ID, conv.ID, "tool_call", "calling write_file", map[string]interface{}{
+ "toolName": "write_file",
+ "toolCallId": "call-big",
+ "agentName": "main",
+ "argumentsObj": map[string]interface{}{"content": largeArgs},
+ })
+ if err != nil {
+ t.Fatalf("AddProcessDetailWithID(tool_call): %v", err)
+ }
+ resultID, err := db.AddProcessDetailWithID(msg.ID, conv.ID, "tool_result", largeOutput, map[string]interface{}{
+ "toolName": "write_file",
+ "toolCallId": "call-big",
+ "agentName": "main",
+ "result": largeOutput,
+ "success": true,
+ })
+ if err != nil {
+ t.Fatalf("AddProcessDetailWithID(tool_result): %v", err)
+ }
+ if err := db.AddProcessDetail(msg.ID, conv.ID, "finalization_check", "ok", map[string]interface{}{
+ "finalizable": true,
+ "finalText": strings.Repeat("report copy ", 500),
+ }); err != nil {
+ t.Fatalf("AddProcessDetail(finalization_check): %v", err)
+ }
+
+ h := NewConversationHandler(db, zap.NewNop())
+
+ // Summary mode should be tiny and omit large payloads + progress rows + duplicate reasoningContent.
+ w := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(w)
+ c.Request = httptest.NewRequest("GET", "/api/conversations/"+conv.ID+"?include_process_details=summary", nil)
+ c.Params = gin.Params{{Key: "id", Value: conv.ID}}
+ h.GetConversation(c)
+ if w.Code != 200 {
+ t.Fatalf("summary status = %d: %s", w.Code, w.Body.String())
+ }
+ bodyStr := w.Body.String()
+ if strings.Contains(bodyStr, largeArgs) || strings.Contains(bodyStr, largeOutput) || strings.Contains(bodyStr, largeThought) {
+ t.Fatalf("summary response leaked deferred payload (len=%d)", len(bodyStr))
+ }
+ if strings.Contains(bodyStr, "heartbeat noise") {
+ t.Fatalf("summary response should skip progress rows")
+ }
+ if strings.Contains(bodyStr, "report copy") {
+ t.Fatalf("summary response should strip finalization_check.finalText")
+ }
+ if strings.Contains(bodyStr, "duplicate reasoning fallback") {
+ t.Fatalf("summary response should omit duplicate reasoningContent when thinking detail exists")
+ }
+
+ var convResp struct {
+ Messages []struct {
+ ProcessDetails []map[string]interface{} `json:"processDetails"`
+ } `json:"messages"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &convResp); err != nil {
+ t.Fatalf("decode summary response: %v", err)
+ }
+ if len(convResp.Messages) != 1 || len(convResp.Messages[0].ProcessDetails) != 4 {
+ t.Fatalf("unexpected summary details count: %+v", convResp.Messages)
+ }
+
+ // Single-detail fetch still returns the full payloads on demand.
+ for _, tc := range []struct {
+ id string
+ wantSub string
+ }{
+ {thoughtID, "深入分析目标指纹与端口开放情况。"},
+ {callID, largeArgs[:64]},
+ {resultID, "open 80/tcp http"},
+ } {
+ dw := httptest.NewRecorder()
+ dc, _ := gin.CreateTestContext(dw)
+ dc.Request = httptest.NewRequest("GET", "/api/process-details/"+tc.id, nil)
+ dc.Params = gin.Params{{Key: "id", Value: tc.id}}
+ h.GetProcessDetail(dc)
+ if dw.Code != 200 {
+ t.Fatalf("GetProcessDetail(%s) status=%d: %s", tc.id, dw.Code, dw.Body.String())
+ }
+ if !strings.Contains(dw.Body.String(), tc.wantSub) {
+ t.Fatalf("GetProcessDetail(%s) missing full payload", tc.id)
+ }
+ }
+}
diff --git a/web/frontend/src/pages/chat/MessageList.jsx b/web/frontend/src/pages/chat/MessageList.jsx
index 42351860..16362c69 100644
--- a/web/frontend/src/pages/chat/MessageList.jsx
+++ b/web/frontend/src/pages/chat/MessageList.jsx
@@ -1,5 +1,5 @@
/** 消息区:运行中跟随输出,结束后定位到最终总结的开头。 */
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Avatar, Button, Empty, Spin, Tag, Tooltip, Typography } from '@douyinfe/semi-ui';
import { IconArrowDown, IconComment, IconDelete, IconRefresh, IconUser } from '@douyinfe/semi-icons';
import { CopyButton, ErrorBanner } from '../../components/ui';
@@ -10,6 +10,15 @@ import { LIVE_STATUS_META, buildHistoryBlocks } from './stream';
const { Paragraph, Text } = Typography;
+const INITIAL_VISIBLE_MESSAGES = 40;
+const LOAD_MORE_STEP = 40;
+
+function textFingerprint(value) {
+ const text = String(value || '');
+ if (text.length <= 128) return text;
+ return `${text.length}:${text.slice(0, 64)}:${text.slice(-64)}`;
+}
+
function ChatWelcome() {
const t = useT();
return (
@@ -42,7 +51,7 @@ function useElapsed(startedAt, endedAt, active) {
return `${minutes}m${seconds % 60}s`;
}
-function MessageRow({ message, canDelete, onDeleteTurn }) {
+const MessageRow = memo(function MessageRow({ message, canDelete, onDeleteTurn }) {
const t = useT();
const isUser = message.role === 'user';
const isSystem = message.role === 'system';
@@ -89,7 +98,7 @@ function MessageRow({ message, canDelete, onDeleteTurn }) {
);
-}
+});
function LiveRow({ live }) {
const t = useT();
@@ -138,13 +147,20 @@ export default function MessageList({
const stickRef = useRef(true);
const positionedSummaryRef = useRef('');
const [atBottom, setAtBottom] = useState(true);
+ const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE_MESSAGES);
const list = Array.isArray(messages) ? messages : [];
+ const hiddenCount = Math.max(0, list.length - visibleCount);
+ const visibleMessages = useMemo(
+ () => (hiddenCount > 0 ? list.slice(hiddenCount) : list),
+ [list, hiddenCount]
+ );
const lastMessage = list[list.length - 1];
- const historySignature = `${list.length}:${lastMessage?.id || ''}:${lastMessage?.content || ''}:${lastMessage?.processDetails?.length || 0}`;
+ const lastContentSig = textFingerprint(lastMessage?.content);
+ const historySignature = `${list.length}:${lastMessage?.id || ''}:${lastContentSig}:${lastMessage?.processDetails?.length || 0}`;
const summaryKey = live
- ? (live.status !== 'streaming' && live.text.trim() ? `live:${conversationId}:${live.messageId || live.id}:${live.text}` : '')
- : (!loading && lastMessage?.role === 'assistant' && String(lastMessage.content || '').trim() ? `history:${conversationId}:${lastMessage.id}:${lastMessage.content}` : '');
+ ? (live.status !== 'streaming' && live.text.trim() ? `live:${conversationId}:${live.messageId || live.id}:${textFingerprint(live.text)}` : '')
+ : (!loading && lastMessage?.role === 'assistant' && String(lastMessage.content || '').trim() ? `history:${conversationId}:${lastMessage.id}:${lastContentSig}` : '');
const signature = useMemo(() => {
if (!live) return historySignature;
const blockSig = live.blocks.map(block => `${block.kind}:${block.id}:${block.text ? block.text.length : 0}:${block.status || ''}`).join('|');
@@ -185,6 +201,7 @@ export default function MessageList({
stickRef.current = true;
positionedSummaryRef.current = '';
setAtBottom(true);
+ setVisibleCount(INITIAL_VISIBLE_MESSAGES);
const timer = setTimeout(() => scrollToLatest(false), 30);
return () => clearTimeout(timer);
}, [conversationId, scrollToLatest]);
@@ -222,7 +239,25 @@ export default function MessageList({
{!loading && !list.length && !live && (
{truncateText(text)}
+ {displayText}}
{argsText}
>
)}
- {resultText && (
+ {open && resultText && (
<>
{resultText}
@@ -128,7 +261,7 @@ function EventLog({ events }) {
);
}
-export default function TurnBody({
+const TurnBody = memo(function TurnBody({
text,
blocks,
events,
@@ -169,7 +302,7 @@ export default function TurnBody({
An error occurred:
`+V(n.message+``,!0)+``;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function W(e,t){return Xn.parse(e,t)}W.options=W.setOptions=function(e){return Xn.setOptions(e),W.defaults=Xn.defaults,Nt(W.defaults),W},W.getDefaults=jt,W.defaults=Mt,W.use=function(...e){return Xn.use(...e),W.defaults=Xn.defaults,Nt(W.defaults),W},W.walkTokens=function(e,t){return Xn.walkTokens(e,t)},W.parseInline=Xn.parseInline,W.Parser=U,W.parser=U.parse,W.Renderer=qn,W.TextRenderer=Jn,W.Lexer=H,W.lexer=H.lex,W.Tokenizer=Kn,W.Hooks=Yn,W.parse=W,W.options,W.setOptions,W.use,W.walkTokens,W.parseInline,U.parse,H.lex;function Zn(e,t){this.v=e,this.k=t}function Qn(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n