perf(chat): eliminate old conversation loading lag and polling livelock
- Add compact summary mode (include_process_details=summary) on GET /api/conversations/:id that skips progress noise, strips duplicated tool outputs/large arguments/long thinking bodies/finalText, and defers full payloads for on-demand GET /api/process-details/:id fetches - Prevent paginated GET /api/messages/:id/process-details from leaking full tool_result payloads through message when includeToolPayload is false - Add stdlib Gzip response compression middleware (skipping SSE, WebSocket, and already-compressed assets) - Add SQLite composite indexes on messages(conversation_id, created_at) and process_details(conversation_id/message_id, created_at) - Switch chat page to summary loading with on-demand ToolBlock/ReasoningBlock detail fetching, AbortController cancellation, and in-flight poll deduplication to fix backgroundRunning 4s polling livelock - Memoize MessageRow/TurnBody, defer prettyJson until panel expansion, and window long conversation histories (>40 messages) - Rebuild web/static/app bundle and add Go + Playwright regression tests
This commit is contained in:
parent
b5f4ab9071
commit
966836ef19
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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 == "" {
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 }) {
|
|||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
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 && (
|
||||
<ChatWelcome />
|
||||
)}
|
||||
{list.map(message => (
|
||||
{!loading && hiddenCount > 0 && (
|
||||
<div className="chat-history-more">
|
||||
<Button
|
||||
size="small"
|
||||
theme="light"
|
||||
onClick={() => setVisibleCount(count => count + LOAD_MORE_STEP)}
|
||||
>
|
||||
{t('chat.loadEarlierMessages', { count: Math.min(LOAD_MORE_STEP, hiddenCount) }, `显示更早的 ${Math.min(LOAD_MORE_STEP, hiddenCount)} 条消息`)}
|
||||
</Button>
|
||||
<Button
|
||||
size="small"
|
||||
theme="borderless"
|
||||
onClick={() => setVisibleCount(list.length)}
|
||||
>
|
||||
{t('chat.showAllMessages', { total: list.length }, `显示全部(共 ${list.length} 条)`)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{visibleMessages.map(message => (
|
||||
<MessageRow
|
||||
key={message.id}
|
||||
message={message}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,16 @@
|
|||
/** 单轮输出:执行过程与事件在前,助手最终正文在末尾独立展示。 */
|
||||
import { useState } from 'react';
|
||||
import { Collapse, Tag, Typography } from '@douyinfe/semi-ui';
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Collapse, Spin, Tag, Typography } from '@douyinfe/semi-ui';
|
||||
import { MarkdownView, JsonViewer } from '../../components/ui';
|
||||
import { api, errorMessage } from '../../lib/http';
|
||||
import { formatNumber } from '../../lib/format';
|
||||
import { useI18n } from '../../lib/i18n';
|
||||
import { prettyJson, truncateText } from './stream';
|
||||
import {
|
||||
extractProcessDetailArgs,
|
||||
extractProcessDetailResult,
|
||||
prettyJson,
|
||||
truncateText
|
||||
} from './stream';
|
||||
|
||||
const { Text } = Typography;
|
||||
|
||||
|
|
@ -16,14 +22,72 @@ const STATUS_TAG = {
|
|||
blocked: { color: 'orange', label: '已拦截' }
|
||||
};
|
||||
|
||||
function isPanelActive(activeKey) {
|
||||
return Array.isArray(activeKey) ? activeKey.includes('1') : activeKey === '1';
|
||||
}
|
||||
|
||||
function ReasoningBlock({ block, defaultOpen }) {
|
||||
const text = block.text || '';
|
||||
if (!text.trim()) return null;
|
||||
const [open, setOpen] = useState(Boolean(defaultOpen));
|
||||
const [loadedText, setLoadedText] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const abortRef = useRef(null);
|
||||
|
||||
const effectiveText = block.text || loadedText;
|
||||
const textLength = effectiveText ? effectiveText.length : (Number(block.textLength) || 0);
|
||||
const needsFetch = Boolean(block.payloadDeferred && block.detailId && !effectiveText);
|
||||
|
||||
const fetchDetail = useCallback(async () => {
|
||||
if (!block.detailId) return;
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setLoading(true);
|
||||
setLoadError('');
|
||||
try {
|
||||
const payload = await api.get(`/process-details/${encodeURIComponent(block.detailId)}`, null, { signal: controller.signal });
|
||||
if (controller.signal.aborted) return;
|
||||
const detail = payload?.processDetail;
|
||||
setLoadedText(String(detail?.message || ''));
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) setLoadError(errorMessage(error, '加载思考过程失败'));
|
||||
} finally {
|
||||
if (abortRef.current === controller) {
|
||||
abortRef.current = null;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [block.detailId]);
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && needsFetch && !loading && !loadError) {
|
||||
void fetchDetail();
|
||||
}
|
||||
}, [open, needsFetch, loading, loadError, fetchDetail]);
|
||||
|
||||
const displayText = useMemo(() => (open && effectiveText ? truncateText(effectiveText) : ''), [open, effectiveText]);
|
||||
|
||||
if (!effectiveText.trim() && !block.payloadDeferred) return null;
|
||||
const title = block.label === 'reasoning_chain' ? '🔗 推理过程' : '🤔 思考过程';
|
||||
return (
|
||||
<Collapse className="chat-block-collapse" defaultActiveKey={defaultOpen ? ['1'] : []}>
|
||||
<Collapse.Panel itemKey="1" header={<span className="chat-block-title">{title} · {text.length} 字符</span>}>
|
||||
<pre className="chat-pre">{truncateText(text)}</pre>
|
||||
<Collapse
|
||||
className="chat-block-collapse"
|
||||
activeKey={open ? ['1'] : []}
|
||||
onChange={activeKey => setOpen(isPanelActive(activeKey))}
|
||||
>
|
||||
<Collapse.Panel itemKey="1" header={<span className="chat-block-title">{title} · {textLength} 字符</span>}>
|
||||
{open && loading && (
|
||||
<div className="chat-tool-loading"><Spin size="small" /><span>正在加载思考过程…</span></div>
|
||||
)}
|
||||
{open && loadError && (
|
||||
<div className="chat-tool-error">
|
||||
<span>{loadError}</span>
|
||||
<button type="button" className="chat-link-btn" onClick={() => void fetchDetail()}>重试</button>
|
||||
</div>
|
||||
)}
|
||||
{open && displayText && <pre className="chat-pre">{displayText}</pre>}
|
||||
</Collapse.Panel>
|
||||
</Collapse>
|
||||
);
|
||||
|
|
@ -31,10 +95,66 @@ function ReasoningBlock({ block, defaultOpen }) {
|
|||
|
||||
function ToolBlock({ block, index, total }) {
|
||||
const { t } = useI18n();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [loadedArgs, setLoadedArgs] = useState(undefined);
|
||||
const [loadedResult, setLoadedResult] = useState(undefined);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState('');
|
||||
const abortRef = useRef(null);
|
||||
|
||||
const meta = STATUS_TAG[block.status] || STATUS_TAG.running;
|
||||
const argsText = prettyJson(block.args);
|
||||
const resultText = block.result || '';
|
||||
const hasBody = Boolean(argsText || resultText);
|
||||
const effectiveArgs = loadedArgs !== undefined ? loadedArgs : block.args;
|
||||
const effectiveResult = loadedResult !== undefined ? loadedResult : (block.result || '');
|
||||
const needArgs = Boolean(block.argsDeferred && block.callDetailId && loadedArgs === undefined);
|
||||
const needResult = Boolean(block.resultDeferred && block.resultDetailId && loadedResult === undefined);
|
||||
const hasInlineArgs = effectiveArgs !== null && effectiveArgs !== undefined && effectiveArgs !== '';
|
||||
const hasBody = Boolean(hasInlineArgs || effectiveResult || needArgs || needResult || block.hasDeferredPayload);
|
||||
|
||||
const fetchDeferredDetails = useCallback(async () => {
|
||||
const idsToFetch = [];
|
||||
if (needArgs && block.callDetailId) idsToFetch.push({ kind: 'args', id: block.callDetailId });
|
||||
if (needResult && block.resultDetailId) idsToFetch.push({ kind: 'result', id: block.resultDetailId });
|
||||
if (!idsToFetch.length) return;
|
||||
|
||||
abortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortRef.current = controller;
|
||||
setLoading(true);
|
||||
setLoadError('');
|
||||
try {
|
||||
const results = await Promise.all(idsToFetch.map(async item => {
|
||||
const payload = await api.get(`/process-details/${encodeURIComponent(item.id)}`, null, { signal: controller.signal });
|
||||
return { kind: item.kind, detail: payload?.processDetail || null };
|
||||
}));
|
||||
if (controller.signal.aborted) return;
|
||||
for (const item of results) {
|
||||
if (item.kind === 'args') {
|
||||
setLoadedArgs(extractProcessDetailArgs(item.detail));
|
||||
} else if (item.kind === 'result') {
|
||||
setLoadedResult(extractProcessDetailResult(item.detail));
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) setLoadError(errorMessage(error, '加载工具详情失败'));
|
||||
} finally {
|
||||
if (abortRef.current === controller) {
|
||||
abortRef.current = null;
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
}, [block.callDetailId, block.resultDetailId, needArgs, needResult]);
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), []);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && (needArgs || needResult) && !loading && !loadError) {
|
||||
void fetchDeferredDetails();
|
||||
}
|
||||
}, [open, needArgs, needResult, loading, loadError, fetchDeferredDetails]);
|
||||
|
||||
const argsText = useMemo(() => (open ? prettyJson(effectiveArgs) : ''), [open, effectiveArgs]);
|
||||
const resultText = open ? effectiveResult : '';
|
||||
|
||||
const name = block.toolName || t('chat.unknownTool', null, '未知工具');
|
||||
const header = (
|
||||
<span className="chat-tool-head">
|
||||
|
|
@ -50,15 +170,28 @@ function ToolBlock({ block, index, total }) {
|
|||
}
|
||||
return (
|
||||
<div className="chat-tool">
|
||||
<Collapse className="chat-block-collapse">
|
||||
<Collapse
|
||||
className="chat-block-collapse"
|
||||
activeKey={open ? ['1'] : []}
|
||||
onChange={activeKey => setOpen(isPanelActive(activeKey))}
|
||||
>
|
||||
<Collapse.Panel itemKey="1" header={header}>
|
||||
{argsText && (
|
||||
{open && loading && (
|
||||
<div className="chat-tool-loading"><Spin size="small" /><span>正在加载工具详情…</span></div>
|
||||
)}
|
||||
{open && loadError && (
|
||||
<div className="chat-tool-error">
|
||||
<span>{loadError}</span>
|
||||
<button type="button" className="chat-link-btn" onClick={() => void fetchDeferredDetails()}>重试</button>
|
||||
</div>
|
||||
)}
|
||||
{open && argsText && (
|
||||
<>
|
||||
<Text type="tertiary" size="small">参数</Text>
|
||||
<pre className="chat-pre">{argsText}</pre>
|
||||
</>
|
||||
)}
|
||||
{resultText && (
|
||||
{open && resultText && (
|
||||
<>
|
||||
<Text type="tertiary" size="small">结果</Text>
|
||||
<pre className="chat-pre">{resultText}</pre>
|
||||
|
|
@ -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({
|
|||
<EventLog events={events} />
|
||||
{body.trim() && (isAssistant && !streaming ? (
|
||||
<section className="chat-task-summary" aria-label={t('chat.taskSummary')} data-chat-summary>
|
||||
<details key={body} open>
|
||||
<details key={body.length} open>
|
||||
<summary className="chat-task-summary-title">{t('chat.taskSummary')}</summary>
|
||||
<div className="chat-task-summary-content"><MarkdownView content={body} /></div>
|
||||
</details>
|
||||
|
|
@ -180,4 +313,6 @@ export default function TurnBody({
|
|||
{!body.trim() && streaming && <div className="chat-stream-placeholder">正在生成…</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export default TurnBody;
|
||||
|
|
|
|||
|
|
@ -112,6 +112,8 @@ export default function Page() {
|
|||
const narrow = useMediaQuery('(max-width: 900px)');
|
||||
|
||||
const detailSeq = useRef(0);
|
||||
const detailAbortRef = useRef(null);
|
||||
const detailInFlightRef = useRef({ id: '', active: false });
|
||||
const hitlSeq = useRef(0);
|
||||
const planSeq = useRef(0);
|
||||
const activeTask = useResource(async () => {
|
||||
|
|
@ -182,16 +184,31 @@ export default function Page() {
|
|||
setPage(1);
|
||||
}, []);
|
||||
|
||||
const loadDetail = useCallback(async (id, { silent = false } = {}) => {
|
||||
const seq = ++detailSeq.current;
|
||||
const loadDetail = useCallback(async (id, { silent = false, force = false } = {}) => {
|
||||
if (!id) {
|
||||
detailAbortRef.current?.abort();
|
||||
detailAbortRef.current = null;
|
||||
detailInFlightRef.current = { id: '', active: false };
|
||||
setDetail(EMPTY_DETAIL);
|
||||
return null;
|
||||
}
|
||||
// 后台任务轮询期间,若同会话已有请求在途则跳过,避免慢网/大历史场景下 detailSeq 互相作废导致无限转圈。
|
||||
if (silent && !force && detailInFlightRef.current.active && detailInFlightRef.current.id === id) {
|
||||
return null;
|
||||
}
|
||||
detailAbortRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
detailAbortRef.current = controller;
|
||||
detailInFlightRef.current = { id, active: true };
|
||||
const seq = ++detailSeq.current;
|
||||
if (!silent) setDetail(prev => ({ ...prev, loading: true, error: null }));
|
||||
try {
|
||||
const payload = await api.get(`/conversations/${encodeURIComponent(id)}`, { include_process_details: 1 });
|
||||
if (seq !== detailSeq.current || conversationRef.current !== id) return null;
|
||||
const payload = await api.get(
|
||||
`/conversations/${encodeURIComponent(id)}`,
|
||||
{ include_process_details: 'summary' },
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
if (controller.signal.aborted || seq !== detailSeq.current || conversationRef.current !== id) return null;
|
||||
setDetail({
|
||||
conversation: payload || null,
|
||||
messages: Array.isArray(payload?.messages) ? payload.messages : [],
|
||||
|
|
@ -200,13 +217,25 @@ export default function Page() {
|
|||
});
|
||||
return payload;
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted) return null;
|
||||
if (seq === detailSeq.current && conversationRef.current === id) {
|
||||
setDetail(prev => ({ ...prev, loading: false, error }));
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
if (detailAbortRef.current === controller) {
|
||||
detailAbortRef.current = null;
|
||||
detailInFlightRef.current = { id: '', active: false };
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => () => {
|
||||
detailAbortRef.current?.abort();
|
||||
detailAbortRef.current = null;
|
||||
detailInFlightRef.current = { id: '', active: false };
|
||||
}, []);
|
||||
|
||||
const refreshHitl = useCallback(async () => {
|
||||
const id = conversationRef.current;
|
||||
const seq = ++hitlSeq.current;
|
||||
|
|
@ -279,6 +308,9 @@ export default function Page() {
|
|||
boundByRun.current = null;
|
||||
if (newlyBound || isStreaming(conversationId)) return;
|
||||
resetRun();
|
||||
detailAbortRef.current?.abort();
|
||||
detailAbortRef.current = null;
|
||||
detailInFlightRef.current = { id: '', active: false };
|
||||
detailSeq.current++;
|
||||
hitlSeq.current++;
|
||||
planSeq.current++;
|
||||
|
|
@ -305,7 +337,7 @@ export default function Page() {
|
|||
|
||||
useEffect(() => {
|
||||
if (lastActive.current === conversationId && !backgroundRunning) {
|
||||
loadDetail(conversationId, { silent: true });
|
||||
loadDetail(conversationId, { silent: true, force: true });
|
||||
reloadConversations.current?.({ silent: true });
|
||||
}
|
||||
lastActive.current = backgroundRunning ? conversationId : null;
|
||||
|
|
@ -630,6 +662,10 @@ export default function Page() {
|
|||
/>
|
||||
);
|
||||
|
||||
const retryDetail = useCallback(() => (
|
||||
conversationId ? loadDetail(conversationId, { force: true }) : null
|
||||
), [conversationId, loadDetail]);
|
||||
|
||||
return (
|
||||
<div className="chat-page">
|
||||
{!narrow && <aside className="chat-sidebar">{sidebar}</aside>}
|
||||
|
|
@ -655,7 +691,7 @@ export default function Page() {
|
|||
live={live}
|
||||
loading={detail.loading || Boolean(conversationId && !detail.conversation && !detail.error)}
|
||||
error={detail.error}
|
||||
onRetry={() => (conversationId ? loadDetail(conversationId) : null)}
|
||||
onRetry={retryDetail}
|
||||
canDelete={canDelete}
|
||||
onDeleteTurn={deleteTurn}
|
||||
/>
|
||||
|
|
|
|||
|
|
@ -527,6 +527,25 @@
|
|||
}
|
||||
.chat-plan-strip-bar { flex: 1 1 auto; margin: 0; min-width: 80px; }
|
||||
|
||||
.chat-tool-loading,
|
||||
.chat-tool-error {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 0;
|
||||
font-size: 12px;
|
||||
color: var(--semi-color-text-2);
|
||||
}
|
||||
.chat-tool-error { color: var(--semi-color-danger); }
|
||||
|
||||
.chat-history-more {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
padding: 4px 0 8px;
|
||||
}
|
||||
|
||||
/* ---------- 窄屏与输入方式 ---------- */
|
||||
|
||||
@container chat-workspace (max-width: 560px) {
|
||||
|
|
|
|||
|
|
@ -118,6 +118,17 @@ function toolArgumentsFromData(data) {
|
|||
}
|
||||
}
|
||||
|
||||
export function extractProcessDetailArgs(detail) {
|
||||
const data = asObject(detail?.data) || {};
|
||||
return toolArgumentsFromData(data);
|
||||
}
|
||||
|
||||
export function extractProcessDetailResult(detail) {
|
||||
const data = asObject(detail?.data) || {};
|
||||
const raw = data.resultPreview ?? data.result ?? data.error ?? detail?.message;
|
||||
return prettyJson(raw, 8000);
|
||||
}
|
||||
|
||||
function matchToolResult({ blocks, toolsByCallId }, { toolCallId, toolName, agentName }) {
|
||||
const sameAgent = block => !agentName || !block.agentName || block.agentName === agentName;
|
||||
const matches = toolsByCallId.get(toolCallId)?.filter(sameAgent);
|
||||
|
|
@ -147,6 +158,7 @@ function addToolEvent(timeline, type, data, message, key, processDetailId) {
|
|||
};
|
||||
const args = toolArgumentsFromData(data);
|
||||
const isResult = type === 'tool_result';
|
||||
const detailId = str(processDetailId);
|
||||
let tool = isResult ? matchToolResult(timeline, identity) : null;
|
||||
if (!tool) {
|
||||
tool = {
|
||||
|
|
@ -158,10 +170,17 @@ function addToolEvent(timeline, type, data, message, key, processDetailId) {
|
|||
args,
|
||||
result: '',
|
||||
status: 'running',
|
||||
processDetailId: str(processDetailId),
|
||||
processDetailId: detailId,
|
||||
callDetailId: isResult ? '' : detailId,
|
||||
resultDetailId: isResult ? detailId : '',
|
||||
argsDeferred: Boolean(!isResult && data._argsDeferred && detailId),
|
||||
resultDeferred: false,
|
||||
hasDeferredPayload: Boolean(data._hasPayload || data._argsDeferred),
|
||||
hasResult: false
|
||||
};
|
||||
timeline.blocks.push(tool);
|
||||
} else if (!isResult && detailId && !tool.callDetailId) {
|
||||
tool.callDetailId = detailId;
|
||||
}
|
||||
if (identity.toolCallId && !tool.toolCallId) {
|
||||
tool.toolCallId = identity.toolCallId;
|
||||
|
|
@ -169,16 +188,31 @@ function addToolEvent(timeline, type, data, message, key, processDetailId) {
|
|||
if (matches) matches.push(tool);
|
||||
else timeline.toolsByCallId.set(tool.toolCallId, [tool]);
|
||||
}
|
||||
if (!isResult) return;
|
||||
if (!isResult) {
|
||||
if (data._argsDeferred && detailId) {
|
||||
tool.argsDeferred = true;
|
||||
tool.hasDeferredPayload = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
tool.hasResult = true;
|
||||
tool.toolName ||= identity.toolName;
|
||||
tool.agentName ||= identity.agentName;
|
||||
if (detailId) tool.resultDetailId = detailId;
|
||||
tool.status = toolStatusFromData(data);
|
||||
if (args !== null && (tool.args === null || (asObject(tool.args) && !Object.keys(tool.args).length))) {
|
||||
tool.args = args;
|
||||
tool.argsDeferred = false;
|
||||
}
|
||||
const rawResult = data.resultPreview ?? data.result ?? data.error ?? (str(message).trim() ? message : undefined);
|
||||
if (rawResult !== undefined && rawResult !== null && str(rawResult) !== '') {
|
||||
tool.result = prettyJson(rawResult, 8000);
|
||||
tool.resultDeferred = false;
|
||||
} else if (data._payloadDeferred && data._hasPayload !== false && detailId) {
|
||||
tool.resultDeferred = true;
|
||||
tool.hasDeferredPayload = true;
|
||||
}
|
||||
tool.result = prettyJson(data.resultPreview ?? data.result ?? data.error ?? message, 8000);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -409,14 +443,18 @@ export function buildHistoryBlocks(message) {
|
|||
}
|
||||
case 'thinking':
|
||||
case 'reasoning_chain': {
|
||||
if (!text.trim()) break;
|
||||
const deferred = Boolean(data._payloadDeferred && detail?.id && !text.trim());
|
||||
if (!text.trim() && !deferred) break;
|
||||
blocks.push({
|
||||
kind: 'reasoning',
|
||||
id: key('reason'),
|
||||
detailId: str(detail?.id),
|
||||
key: str(data.streamId) || key('reasonkey'),
|
||||
stream: str(data.streamId),
|
||||
label: eventType,
|
||||
text: truncateText(text)
|
||||
text: deferred ? '' : truncateText(text),
|
||||
textLength: deferred ? (Number(data._textLength) || 0) : text.length,
|
||||
payloadDeferred: deferred
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,159 @@
|
|||
import { test, expect, ready, CONVERSATION } from './fixtures.mjs';
|
||||
|
||||
test('loads conversation history in summary mode and fetches deferred tool/thinking details on demand', async ({ page, mockApi }) => {
|
||||
const requestedQueries = [];
|
||||
const detailFetches = [];
|
||||
|
||||
const summaryConversation = {
|
||||
...CONVERSATION,
|
||||
messages: [
|
||||
{ id: 'u1', role: 'user', content: '扫描目标端口' },
|
||||
{
|
||||
id: 'a1',
|
||||
role: 'assistant',
|
||||
content: '扫描完成,发现 80 端口开放。',
|
||||
processDetails: [
|
||||
{
|
||||
id: 'pd-think-1',
|
||||
eventType: 'thinking',
|
||||
message: '',
|
||||
data: { streamId: 's1', _payloadDeferred: true, _textLength: 1024 }
|
||||
},
|
||||
{
|
||||
id: 'pd-call-1',
|
||||
eventType: 'tool_call',
|
||||
message: '',
|
||||
data: {
|
||||
toolName: 'nmap_scan',
|
||||
toolCallId: 'tc-1',
|
||||
agentName: 'main',
|
||||
_payloadDeferred: true,
|
||||
_argsDeferred: true,
|
||||
_hasPayload: true
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'pd-res-1',
|
||||
eventType: 'tool_result',
|
||||
message: '',
|
||||
data: {
|
||||
toolName: 'nmap_scan',
|
||||
toolCallId: 'tc-1',
|
||||
agentName: 'main',
|
||||
success: true,
|
||||
_payloadDeferred: true,
|
||||
_hasPayload: true
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
mockApi.respond('GET', `/api/conversations/${CONVERSATION.id}`, entry => {
|
||||
requestedQueries.push(entry.query);
|
||||
return { json: summaryConversation };
|
||||
});
|
||||
mockApi.respond('GET', '/api/process-details/pd-think-1', () => {
|
||||
detailFetches.push('pd-think-1');
|
||||
return {
|
||||
json: {
|
||||
processDetail: {
|
||||
id: 'pd-think-1',
|
||||
eventType: 'thinking',
|
||||
message: '这是按需拉取的完整思考内容。',
|
||||
data: { streamId: 's1' }
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
mockApi.respond('GET', '/api/process-details/pd-call-1', () => {
|
||||
detailFetches.push('pd-call-1');
|
||||
return {
|
||||
json: {
|
||||
processDetail: {
|
||||
id: 'pd-call-1',
|
||||
eventType: 'tool_call',
|
||||
message: '',
|
||||
data: { toolName: 'nmap_scan', toolCallId: 'tc-1', argumentsObj: { target: '10.0.0.1', ports: '1-65535' } }
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
mockApi.respond('GET', '/api/process-details/pd-res-1', () => {
|
||||
detailFetches.push('pd-res-1');
|
||||
return {
|
||||
json: {
|
||||
processDetail: {
|
||||
id: 'pd-res-1',
|
||||
eventType: 'tool_result',
|
||||
message: '80/tcp open http',
|
||||
data: { toolName: 'nmap_scan', toolCallId: 'tc-1', result: '80/tcp open http', success: true }
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
await page.goto(`/static/app/#/chat?conversation=${CONVERSATION.id}`);
|
||||
const main = await ready(page);
|
||||
|
||||
expect(requestedQueries.some(query => query.includes('include_process_details=summary'))).toBe(true);
|
||||
// Nothing deferred should be fetched before user expands the panel.
|
||||
expect(detailFetches).toEqual([]);
|
||||
|
||||
await expect(main.getByText('扫描完成,发现 80 端口开放。')).toBeVisible();
|
||||
await expect(main.locator('.chat-tool')).toContainText('nmap_scan (1/1)');
|
||||
await expect(main.locator('.chat-tool')).toContainText('完成');
|
||||
|
||||
// Expand tool card -> fetches both deferred call args and tool result on demand.
|
||||
await main.locator('.chat-tool .semi-collapse-header').click();
|
||||
await expect(main.locator('.chat-tool pre').nth(0)).toContainText('"target": "10.0.0.1"');
|
||||
await expect(main.locator('.chat-tool pre').nth(1)).toContainText('80/tcp open http');
|
||||
expect(detailFetches).toContain('pd-call-1');
|
||||
expect(detailFetches).toContain('pd-res-1');
|
||||
|
||||
// Expand deferred thinking block -> fetches full thought text on demand.
|
||||
await main.locator('.chat-block-title', { hasText: '1024 字符' }).click();
|
||||
await expect(main.getByText('这是按需拉取的完整思考内容。')).toBeVisible();
|
||||
expect(detailFetches).toContain('pd-think-1');
|
||||
});
|
||||
|
||||
test('background polling does not livelock slow conversation detail loading', async ({ page, mockApi }) => {
|
||||
let detailRequestCount = 0;
|
||||
let releaseDetail;
|
||||
const detailGate = new Promise(resolve => { releaseDetail = resolve; });
|
||||
|
||||
mockApi.respond('GET', '/api/agent-loop/tasks', {
|
||||
json: { tasks: [{ conversationId: CONVERSATION.id, status: 'running' }] }
|
||||
});
|
||||
mockApi.respond('GET', `/api/conversations/${CONVERSATION.id}/plan-tasks`, {
|
||||
json: {
|
||||
running: true,
|
||||
total: 5,
|
||||
completed: 0,
|
||||
activeStep: 1,
|
||||
tasks: [{ id: '1', subject: '步骤一', status: 'in_progress' }]
|
||||
}
|
||||
});
|
||||
mockApi.respond('GET', `/api/conversations/${CONVERSATION.id}`, async () => {
|
||||
detailRequestCount += 1;
|
||||
await detailGate;
|
||||
return { json: CONVERSATION };
|
||||
});
|
||||
|
||||
await page.goto(`/static/app/#/chat?conversation=${CONVERSATION.id}`);
|
||||
const main = page.locator('#main-content');
|
||||
await expect(main.getByText('0/5 · 第 1 步')).toBeVisible();
|
||||
const countAfterMount = detailRequestCount;
|
||||
expect(countAfterMount).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Wait past the 4s polling interval while the initial detail request is still in flight.
|
||||
// Silent background polls must NOT fire competing requests that invalidate detailSeq.
|
||||
await page.waitForTimeout(4500);
|
||||
expect(detailRequestCount).toBe(countAfterMount);
|
||||
|
||||
releaseDetail();
|
||||
await ready(page);
|
||||
await expect(main.getByText(CONVERSATION.title).first()).toBeVisible();
|
||||
await expect(main.getByText(CONVERSATION.messages[1].content)).toBeVisible();
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-SJWmtITN.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-L6htuljo.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-SJWmtITN.js";import"./c2-shared-B1qG-Fhd.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-L6htuljo.js";import"./c2-shared-sB4ii0L_.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
|
|
@ -1 +1 @@
|
|||
import{I as e,L as t}from"./index-SJWmtITN.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
import{I as e,L as t}from"./index-L6htuljo.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-SJWmtITN.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-L6htuljo.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(a,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(o,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-SJWmtITN.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-L6htuljo.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1,4 +1,4 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{$t as a,A as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,c as h,f as g,h as _,kt as v,m as y,ot as b,p as x,s as S,st as ee,u as C,v as w,x as T,z as E}from"./semi-CHxO7u8f.js";import{A as te,D,E as O,F as ne,I as k,L as A,M as j,N as M,P as re,R as N,S as P,T as F,_ as ie,a as I,b as L,d as R,j as ae,l as z,m as B,n as V,o as H,p as U,s as W,u as G,x as oe,y as se}from"./index-SJWmtITN.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var K=e(t(),1),q=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function me(e){return JSON.stringify(String(e))}function he(e){let t=String(e);return pe(t)?t:me(t)}function ge(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):me(String(e));let t=String(e);return pe(t)?t:me(t)}function _e(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ve(e,t,n,r){let i=` `.repeat(n),a=he(e);if(_e(t))r.push(`${i}${a}: ${ge(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),xe(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ye(t,n+2,r)):r.push(`${i}${a}: {}`)}function ye(e,t,n){for(let[r,i]of Object.entries(e))ve(r,i,t,n)}function be(e,t,n){let r=` `.repeat(t);if(_e(e)){n.push(`${r}- ${ge(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),xe(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);_e(o)?n.push(`${r}- ${he(a)}: ${ge(o)}`):(n.push(`${r}-`),ve(a,o,t+2,n));for(let[e,r]of s)ve(e,r,t+2,n)}function xe(e,t,n){for(let r of e)be(r,t,n)}function Se(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{$t as a,A as o,F as s,H as c,I as l,L as u,M as d,O as f,W as p,Z as m,c as h,f as g,h as _,kt as v,m as y,ot as b,p as x,s as S,st as ee,u as C,v as w,x as T,z as E}from"./semi-CHxO7u8f.js";import{A as te,D,E as O,F as ne,I as k,L as A,M as j,N as M,P as re,R as N,S as P,T as F,_ as ie,a as I,b as L,d as R,j as ae,l as z,m as B,n as V,o as H,p as U,s as W,u as G,x as oe,y as se}from"./index-L6htuljo.js";import{n as ce,r as le,t as ue}from"./model-channel-mQ6lfvSO.js";var K=e(t(),1),q=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},de=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,fe=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function pe(e){let t=String(e);return!(t===``||fe.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||de.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function me(e){return JSON.stringify(String(e))}function he(e){let t=String(e);return pe(t)?t:me(t)}function ge(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):me(String(e));let t=String(e);return pe(t)?t:me(t)}function _e(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ve(e,t,n,r){let i=` `.repeat(n),a=he(e);if(_e(t))r.push(`${i}${a}: ${ge(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),xe(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),ye(t,n+2,r)):r.push(`${i}${a}: {}`)}function ye(e,t,n){for(let[r,i]of Object.entries(e))ve(r,i,t,n)}function be(e,t,n){let r=` `.repeat(t);if(_e(e)){n.push(`${r}- ${ge(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),xe(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);_e(o)?n.push(`${r}- ${he(a)}: ${ge(o)}`):(n.push(`${r}-`),ve(a,o,t+2,n));for(let[e,r]of s)ve(e,r,t+2,n)}function xe(e,t,n){for(let r of e)be(r,t,n)}function Se(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
`).split(`
|
||||
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return _e(e)?(n.push(ge(e)),`${n.join(`
|
||||
`)}\n`):Array.isArray(e)?(e.length?xe(e,0,n):n.push(`[]`),`${n.join(`
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-SJWmtITN.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-L6htuljo.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -18,7 +18,7 @@
|
|||
} catch (error) { /* first paint fallback */ }
|
||||
})();
|
||||
</script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-SJWmtITN.js"></script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-L6htuljo.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-CHxO7u8f.js">
|
||||
|
|
|
|||
Loading…
Reference in New Issue