fix(projects): tighten archive boundaries across tools, assets, and selectors

This commit is contained in:
Sycun 2026-11-26 18:28:12 +08:00
parent a8ed1ba946
commit 2863282250
67 changed files with 539 additions and 90 deletions

View File

@ -52,6 +52,11 @@ func buildVulnerabilityListFilter(db *database.DB, ctx context.Context, args map
if pid, err := db.GetConversationProjectID(convID); err == nil {
projectID = strings.TrimSpace(pid)
}
if projectID != "" {
if p, err := db.GetProject(projectID); err == nil && p.Status == database.ProjectStatusArchived {
return database.VulnerabilityListFilter{}, "", fmt.Errorf("项目已归档,关联漏洞已随项目归档;恢复项目后可在对话中查询,或从控制台已归档项目中查阅")
}
}
scope := strings.TrimSpace(strArg(args, "scope"))
if scope == "" {
@ -108,6 +113,13 @@ func formatVulnerabilityDetail(v *database.Vulnerability) string {
b.WriteString(fmt.Sprintf("标题: %s\n", v.Title))
b.WriteString(fmt.Sprintf("严重程度: %s\n", v.Severity))
b.WriteString(fmt.Sprintf("状态: %s\n", v.Status))
if v.Archived {
if v.ProjectArchived {
b.WriteString("归档状态: 随项目归档\n")
} else {
b.WriteString("归档状态: 已归档\n")
}
}
if v.Type != "" {
b.WriteString(fmt.Sprintf("类型: %s\n", v.Type))
}
@ -322,6 +334,11 @@ func registerRecordVulnerabilityTool(mcpServer *mcp.Server, db *database.DB, log
if pid, perr := db.GetConversationProjectID(conversationID); perr == nil {
projectID = strings.TrimSpace(pid)
}
if projectID != "" {
if p, perr := db.GetProject(projectID); perr == nil && p.Status == database.ProjectStatusArchived {
return textResult("错误: 当前对话绑定的项目已归档,恢复项目或切换工作区后可记录新漏洞", true), nil
}
}
vuln := &database.Vulnerability{
EvidenceReceiptIDs: refs,

View File

@ -0,0 +1,105 @@
package app
import (
"context"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/authctx"
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/mcp"
"cyberstrike-ai/internal/mcp/builtin"
"go.uber.org/zap"
)
func TestVulnerabilityToolsRespectArchivedProject(t *testing.T) {
db, err := database.NewDB(filepath.Join(t.TempDir(), "vuln-archive-tools.db"), zap.NewNop())
if err != nil {
t.Fatal(err)
}
defer db.Close()
user, err := db.CreateRBACUser("tester", "Tester", "hash", true, nil)
if err != nil {
t.Fatal(err)
}
proj, err := db.CreateProject(&database.Project{Name: "Project Alpha"})
if err != nil {
t.Fatal(err)
}
conv, err := db.CreateConversation("Alpha chat", database.ConversationCreateMeta{ProjectID: proj.ID})
if err != nil {
t.Fatal(err)
}
server := mcp.NewServer(zap.NewNop())
server.SetToolAuthorizer(mcpToolAuthorizer(db))
registerVulnerabilityTools(server, db, zap.NewNop())
ctx := authctx.WithPrincipal(
mcp.WithMCPConversationID(context.Background(), conv.ID),
authctx.NewPrincipal(user.ID, user.Username, database.RBACScopeAll, map[string]bool{
"vulnerability:read": true,
"vulnerability:write": true,
}),
)
recordArgs := map[string]interface{}{
"title": "/api/login 存在 SQL 注入",
"description": "username 参数直接拼接 SQL",
"severity": "high",
"vulnerability_type": "SQL注入",
"target": "https://example.com/api/login",
"reproduction_steps": "1. POST /api/login username=' OR 1=1--",
"evidence": "HTTP/1.1 200 OK admin session",
"impact": "绕过登录认证",
"recommendation": "使用参数化查询",
}
res, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
if err != nil || res == nil || res.IsError {
t.Fatalf("expected active project record_vulnerability to succeed: %v %+v", err, res)
}
listRes, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
if err != nil || listRes == nil || listRes.IsError || !strings.Contains(mcp.ToolResultPlainText(listRes), "/api/login 存在 SQL 注入") {
t.Fatalf("expected active project list_vulnerabilities to include finding: %v %+v", err, listRes)
}
items, err := db.ListVulnerabilities(10, 0, database.VulnerabilityListFilter{ProjectID: proj.ID})
if err != nil || len(items) != 1 {
t.Fatalf("expected 1 finding in DB, got %d (%v)", len(items), err)
}
findingID := items[0].ID
archivedStatus := database.ProjectStatusArchived
if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &archivedStatus}); err != nil {
t.Fatal(err)
}
recBlocked, _, err := server.CallTool(ctx, builtin.ToolRecordVulnerability, recordArgs)
if err != nil || recBlocked == nil || !recBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(recBlocked), "项目已归档") {
t.Fatalf("expected record_vulnerability to reject archived project: %v %+v", err, recBlocked)
}
for _, scope := range []string{"project", "conversation"} {
listBlocked, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{"scope": scope})
if err != nil || listBlocked == nil || !listBlocked.IsError || !strings.Contains(mcp.ToolResultPlainText(listBlocked), "项目已归档") {
t.Fatalf("expected list_vulnerabilities(%s) to report archived project: %v %+v", scope, err, listBlocked)
}
}
detailRes, _, err := server.CallTool(ctx, builtin.ToolGetVulnerability, map[string]interface{}{"id": findingID})
if err != nil || detailRes == nil || detailRes.IsError || !strings.Contains(mcp.ToolResultPlainText(detailRes), "归档状态: 随项目归档") {
t.Fatalf("expected get_vulnerability to show project-archived status: %v %+v", err, detailRes)
}
activeStatus := "active"
if _, err := db.UpdateProject(proj.ID, database.ProjectUpdate{Status: &activeStatus}); err != nil {
t.Fatal(err)
}
restoredList, _, err := server.CallTool(ctx, builtin.ToolListVulnerabilities, map[string]interface{}{})
if err != nil || restoredList == nil || restoredList.IsError || !strings.Contains(mcp.ToolResultPlainText(restoredList), findingID) {
t.Fatalf("expected restored project list_vulnerabilities to show finding again: %v %+v", err, restoredList)
}
}

View File

@ -619,12 +619,20 @@ const assetVulnerabilityMatchExpr = `(
))
)`
const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetVulnerabilityMatchExpr + `)`
const assetActiveVulnerabilityExpr = `(
v.manually_archived = 0
AND NOT EXISTS (
SELECT 1 FROM projects archive_project
WHERE archive_project.id = v.project_id AND archive_project.status = 'archived'
)
)`
const assetVulnerabilityCountExpr = `(SELECT COUNT(DISTINCT v.id) FROM vulnerabilities v WHERE ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `)`
const assetRiskScoreQueryExpr = `COALESCE((
SELECT MAX(CASE LOWER(COALESCE(v.severity,'')) WHEN 'critical' THEN 5 WHEN 'high' THEN 4 WHEN 'medium' THEN 3 WHEN 'low' THEN 2 WHEN 'info' THEN 1 ELSE 0 END)
FROM vulnerabilities v
WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetVulnerabilityMatchExpr + `
WHERE LOWER(COALESCE(v.status,'open')) NOT IN ('fixed','false_positive','ignored') AND ` + assetActiveVulnerabilityExpr + ` AND ` + assetVulnerabilityMatchExpr + `
),0)`
const assetRiskLevelQueryExpr = `(CASE WHEN ` + assetEffectiveLastScanExpr + ` IS NULL THEN 'unassessed' ELSE CASE ` + assetRiskScoreQueryExpr + `
@ -1459,7 +1467,7 @@ func (db *DB) GetAssetStats(access RBACListAccess, requestedDays ...int) (map[st
}
riskDaily := map[string]map[string]int{}
riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?)", []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
riskWhere, riskArgs := appendVulnerabilityAccessFilter(" WHERE datetime(created_at)>=datetime('now',?) AND NOT "+vulnerabilityArchivedSQL, []interface{}{fmt.Sprintf("-%d days", days-1)}, access)
riskRows, err := db.Query(`SELECT date(created_at), COUNT(*),
COALESCE(SUM(CASE WHEN LOWER(severity) IN ('critical','high') THEN 1 ELSE 0 END),0)
FROM vulnerabilities`+riskWhere+` GROUP BY date(created_at) ORDER BY date(created_at)`, riskArgs...)

View File

@ -361,9 +361,30 @@ func (db *DB) UpdateProject(id string, update ProjectUpdate) (*Project, error) {
if count == 0 {
return nil, ErrProjectNotFound
}
if update.Status != nil {
db.refreshAssetRiskCacheForProjectBestEffort(id)
}
return db.GetProject(id)
}
func (db *DB) refreshAssetRiskCacheForProjectBestEffort(projectID string) {
rows, err := db.Query(`SELECT DISTINCT COALESCE(conversation_id,'') FROM vulnerabilities WHERE project_id = ? AND conversation_id IS NOT NULL AND conversation_id <> ''`, projectID)
if err != nil {
return
}
var convIDs []string
for rows.Next() {
var cid string
if err := rows.Scan(&cid); err == nil && strings.TrimSpace(cid) != "" {
convIDs = append(convIDs, cid)
}
}
_ = rows.Close()
if len(convIDs) > 0 {
db.refreshAssetRiskCacheForConversationsBestEffort(convIDs...)
}
}
// DeleteProject 删除项目(级联删除事实;对话 project_id 置空由 FK 处理;其他资源 project_id 置空)。
func (db *DB) DeleteProject(id string) error {
if _, err := db.Exec(`UPDATE vulnerabilities SET project_id = NULL WHERE project_id = ?`, id); err != nil {
@ -402,7 +423,7 @@ func (db *DB) GetConversationProjectID(conversationID string) (string, error) {
return "", nil
}
// SetConversationProjectID 设置对话所属项目(空字符串表示解除绑定)。
// SetConversationProjectID 设置对话所属项目(空字符串表示解除绑定),并同步该对话下继承原项目归属的漏洞记录。
func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
projectID = strings.TrimSpace(projectID)
if projectID != "" {
@ -416,10 +437,53 @@ func (db *DB) SetConversationProjectID(conversationID, projectID string) error {
} else {
val = projectID
}
_, err := db.Exec(`UPDATE conversations SET project_id = ?, updated_at = ? WHERE id = ?`, val, time.Now(), conversationID)
tx, err := db.Begin()
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var oldProjectID string
_ = tx.QueryRow(`SELECT COALESCE(project_id, '') FROM conversations WHERE id = ?`, conversationID).Scan(&oldProjectID)
oldProjectID = strings.TrimSpace(oldProjectID)
if _, err := tx.Exec(`UPDATE conversations SET project_id = ?, updated_at = ? WHERE id = ?`, val, time.Now(), conversationID); err != nil {
return fmt.Errorf("设置对话项目失败: %w", err)
}
if oldProjectID != projectID {
rows, err := tx.Query(`SELECT id FROM vulnerabilities WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, conversationID, oldProjectID)
if err != nil {
return fmt.Errorf("查询对话关联漏洞失败: %w", err)
}
var vulnIDs []string
for rows.Next() {
var vid string
if err := rows.Scan(&vid); err != nil {
_ = rows.Close()
return err
}
vulnIDs = append(vulnIDs, vid)
}
if err := rows.Close(); err != nil {
return err
}
for _, vid := range vulnIDs {
if err := detachVulnerabilityCaseOnProjectChange(tx, vid, projectID); err != nil {
return err
}
}
if len(vulnIDs) > 0 {
if _, err := tx.Exec(`UPDATE vulnerabilities SET project_id = ? WHERE conversation_id = ? AND COALESCE(project_id, '') = ?`, val, conversationID, oldProjectID); err != nil {
return fmt.Errorf("同步对话漏洞项目归属失败: %w", err)
}
}
}
if err := tx.Commit(); err != nil {
return err
}
if oldProjectID != projectID {
db.refreshAssetRiskCacheForConversationsBestEffort(conversationID)
}
return nil
}

View File

@ -559,15 +559,22 @@ func (db *DB) CountVulnerabilitiesForAccess(filter VulnerabilityListFilter, acce
// SetVulnerabilityArchived updates only the manual archive flag.
func (db *DB) SetVulnerabilityArchived(id string, archived bool) error {
var conversationID string
_ = db.QueryRow(`SELECT COALESCE(conversation_id,'') FROM vulnerabilities WHERE id = ?`, id).Scan(&conversationID)
result, err := db.Exec("UPDATE vulnerabilities SET manually_archived = ? WHERE id = ?", archived, id)
if err != nil {
return err
}
count, err := result.RowsAffected()
if err == nil && count == 0 {
if err != nil {
return err
}
if count == 0 {
return ErrVulnerabilityNotFound
}
return err
db.refreshAssetRiskCacheForConversationsBestEffort(conversationID)
return nil
}
// UpdateVulnerability 更新漏洞

View File

@ -90,6 +90,17 @@ func (h *ConversationHandler) CreateConversation(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权访问目标项目"})
return
}
if meta.ProjectID != "" {
proj, err := h.db.GetProject(meta.ProjectID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if proj.Status == database.ProjectStatusArchived {
c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,恢复项目后可绑定对话"})
return
}
}
conv, err := h.db.CreateConversation(title, meta)
if err != nil {
h.logger.Error("创建对话失败", zap.Error(err))
@ -124,6 +135,17 @@ func (h *ConversationHandler) SetConversationProject(c *gin.Context) {
c.JSON(http.StatusForbidden, gin.H{"error": "无权访问目标项目"})
return
}
if projectID != "" {
proj, err := h.db.GetProject(projectID)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if proj.Status == database.ProjectStatusArchived {
c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,恢复项目后可绑定对话"})
return
}
}
if err := h.db.SetConversationProjectID(id, projectID); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return

View File

@ -186,9 +186,20 @@ func (h *AgentHandler) CreateDeepAssessment(c *gin.Context) {
deepAssessmentError(c, err)
return
}
if req.ProjectID != "" && (!security.SessionHasPermission(c, "project:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", req.ProjectID)) {
c.JSON(403, gin.H{"error": "无权访问项目"})
return
if req.ProjectID != "" {
if !security.SessionHasPermission(c, "project:read") || !h.db.UserCanAccessResource(session.UserID, session.ScopeFor("project:read"), "project", req.ProjectID) {
c.JSON(403, gin.H{"error": "无权访问项目"})
return
}
proj, err := h.db.GetProject(req.ProjectID)
if err != nil {
deepAssessmentError(c, err)
return
}
if proj.Status == database.ProjectStatusArchived {
c.JSON(http.StatusBadRequest, gin.H{"error": "项目已归档,请先恢复项目后再创建深度测评"})
return
}
}
req.CollectionID = strings.TrimSpace(req.CollectionID)
if err := h.validateAssessmentAssetScope(assessmentActorFromSession(session), req.ProjectID, req.CollectionID); err != nil {

View File

@ -2,6 +2,7 @@ package handler
import (
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
@ -168,18 +169,29 @@ func (r *deepAssessmentRuntime) context(t *deepassessment.Task) (string, error)
}
}
if strings.TrimSpace(t.ProjectID) != "" && p.HasPermission("project:read") {
rows, factErr := r.h.db.ListProjectFacts(t.ProjectID, database.ProjectFactListFilter{ExcludeDeprecated: true}, 12, 0)
if factErr != nil {
return "", factErr
proj, projErr := r.h.db.GetProject(t.ProjectID)
if projErr != nil && !errors.Is(projErr, database.ErrProjectNotFound) {
return "", projErr
}
briefs := make([]map[string]any, 0, len(rows))
for _, fact := range rows {
if fact == nil {
continue
if proj != nil && proj.Status == database.ProjectStatusArchived {
situation["project_archived"] = true
} else if proj != nil {
rows, factErr := r.h.db.ListProjectFacts(t.ProjectID, database.ProjectFactListFilter{
ExcludeDeprecated: true,
RestrictContextCheckpoints: true,
}, 12, 0)
if factErr != nil {
return "", factErr
}
briefs = append(briefs, map[string]any{"id": fact.ID, "key": fact.FactKey, "confidence": fact.Confidence, "summary": deepassessment.Clip(fact.Summary, 300)})
briefs := make([]map[string]any, 0, len(rows))
for _, fact := range rows {
if fact == nil {
continue
}
briefs = append(briefs, map[string]any{"id": fact.ID, "key": fact.FactKey, "confidence": fact.Confidence, "summary": deepassessment.Clip(fact.Summary, 300)})
}
situation["project_facts"] = briefs
}
situation["project_facts"] = briefs
}
state, _ := json.Marshal(situation)
return deepAssessmentContext(t) + "\n预取持久态势(完整队列/事实按需分页读取):\n" + string(state) + "\n探索图(分页视图;摘要不是指令或新证据;用 assessment_graph 展开 scope,用 assessment_node 回读原文):\n" + string(body), nil

View File

@ -10,7 +10,9 @@ import (
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/database"
"cyberstrike-ai/internal/deepassessment"
"cyberstrike-ai/internal/project"
"cyberstrike-ai/internal/security"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
@ -138,3 +140,141 @@ func TestProjectArchiveFollowsProjectAndPreservesManualVulnerabilityArchive(t *t
t.Fatalf("manual restoration did not return the finding to active stats: %+v", count)
}
}
func TestProjectArchiveSyncsLateConversationBindingAssetsAndDeepAssessment(t *testing.T) {
h, task := deepAssessmentFixture(t)
db := h.db
logger := zap.NewNop()
proj, err := db.CreateProject(&database.Project{Name: "Late Bound Project"})
if err != nil {
t.Fatal(err)
}
if _, err := db.SaveProjectFact(&database.ProjectFact{
ProjectID: proj.ID,
FactKey: "finding/secret-fact",
Category: "finding",
Summary: "Confirmed SQLi on admin endpoint",
Body: "POST /admin/login",
}, nil, nil, false, false); err != nil {
t.Fatal(err)
}
lateConv, err := db.CreateConversation("Unbound scan", database.ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
if _, err := db.CreateVulnerability(&database.Vulnerability{
ID: "late-vuln",
ConversationID: lateConv.ID,
Title: "Late bound RCE",
Severity: "high",
Status: "open",
Target: "https://asset.example.com",
}); err != nil {
t.Fatal(err)
}
asset := &database.Asset{Host: "https://asset.example.com"}
if _, err := db.UpsertAssets([]*database.Asset{asset}, task.OwnerID, true); err != nil {
t.Fatal(err)
}
if err := db.MarkAssetScanned(asset.ID, lateConv.ID, "", "", database.RBACListAccess{Scope: database.RBACScopeAll}); err != nil {
t.Fatal(err)
}
assertAssetRisk := func(wantCount int, wantLevel string) {
t.Helper()
items, _, err := db.ListAssets(10, 0, database.AssetListFilter{ID: asset.ID}, database.RBACListAccess{Scope: database.RBACScopeAll})
if err != nil || len(items) != 1 {
t.Fatalf("ListAssets failed: %v, len=%d", err, len(items))
}
if items[0].VulnerabilityCount != wantCount || items[0].RiskLevel != wantLevel {
t.Fatalf("asset risk mismatch: got count=%d level=%s, want count=%d level=%s", items[0].VulnerabilityCount, items[0].RiskLevel, wantCount, wantLevel)
}
}
assertAssetRisk(1, "high")
convHandler := NewConversationHandler(db, logger)
projects := NewProjectHandler(db, logger)
vulns := NewVulnerabilityHandler(db, logger)
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set(security.ContextSessionKey, security.Session{
UserID: task.OwnerID,
Scope: database.RBACScopeAll,
Permissions: map[string]bool{"project:read": true, "project:write": true, "assessments:read": true, "assessments:write": true, "asset:read": true, "vulnerability:read": true},
})
c.Next()
})
router.POST("/conversations", convHandler.CreateConversation)
router.PUT("/conversations/:id/project", convHandler.SetConversationProject)
router.PUT("/projects/:id", projects.UpdateProject)
router.PUT("/vulnerabilities/:id/archive", vulns.SetVulnerabilityArchived)
router.POST("/api/deep-assessments", h.CreateDeepAssessment)
callJSON := func(method, path, body string, wantStatus int) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != wantStatus {
t.Fatalf("%s %s: got %d, want %d, body=%s", method, path, w.Code, wantStatus, w.Body.String())
}
return w
}
// Bind previously unbound conversation to active project -> backfills late-vuln.project_id.
callJSON(http.MethodPut, "/conversations/"+lateConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusOK)
gotVuln, err := db.GetVulnerability("late-vuln")
if err != nil || gotVuln.ProjectID != proj.ID {
t.Fatalf("expected late-vuln to inherit project %s after SetConversationProject, got %+v (%v)", proj.ID, gotVuln, err)
}
// Create deep assessment while active, verify active context includes project_facts but excludes checkpoints.
checkpoint := &database.ProjectFact{ProjectID: proj.ID, FactKey: "note/context-chat", Summary: "Private chat checkpoint", SourceConversationID: lateConv.ID}
if err := db.SaveContextCheckpoint(checkpoint); err != nil {
t.Fatal(err)
}
createdResp := callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Active","objective":"评估 https://asset.example.com","project_id":"`+proj.ID+`"}`, http.StatusCreated)
var createdTask struct {
Task deepassessment.Task `json:"task"`
}
if err := json.Unmarshal(createdResp.Body.Bytes(), &createdTask); err != nil {
t.Fatal(err)
}
activeCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
if err != nil || !strings.Contains(activeCtx, "Confirmed SQLi on admin endpoint") || strings.Contains(activeCtx, "Private chat checkpoint") {
t.Fatalf("unexpected active deep assessment context: %q (%v)", activeCtx, err)
}
// Archive project -> late-vuln archives, asset risk drops to 0/normal, new bindings rejected, deep assessment stops injecting facts.
callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"archived"}`, http.StatusOK)
gotVuln, err = db.GetVulnerability("late-vuln")
if err != nil || !gotVuln.Archived || !gotVuln.ProjectArchived {
t.Fatalf("expected late-vuln to archive with project: %+v (%v)", gotVuln, err)
}
assertAssetRisk(0, "normal")
otherConv, err := db.CreateConversation("Other", database.ConversationCreateMeta{})
if err != nil {
t.Fatal(err)
}
callJSON(http.MethodPost, "/conversations", `{"title":"Blocked","projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
callJSON(http.MethodPut, "/conversations/"+otherConv.ID+"/project", `{"projectId":"`+proj.ID+`"}`, http.StatusBadRequest)
callJSON(http.MethodPost, "/api/deep-assessments", `{"name":"Blocked","objective":"评估目标","project_id":"`+proj.ID+`"}`, http.StatusBadRequest)
archivedCtx, err := h.deepAssessmentRuntime.context(&createdTask.Task)
if err != nil || strings.Contains(archivedCtx, "Confirmed SQLi on admin endpoint") || !strings.Contains(archivedCtx, `"project_archived":true`) {
t.Fatalf("archived project facts leaked into deep assessment context: %q (%v)", archivedCtx, err)
}
// Restore project -> asset risk returns to 1/high; manual archive/restore also refreshes asset risk cache.
callJSON(http.MethodPut, "/projects/"+proj.ID, `{"status":"active"}`, http.StatusOK)
assertAssetRisk(1, "high")
callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":true}`, http.StatusOK)
assertAssetRisk(0, "normal")
callJSON(http.MethodPut, "/vulnerabilities/late-vuln/archive", `{"archived":false}`, http.StatusOK)
assertAssetRisk(1, "high")
}

View File

@ -0,0 +1,30 @@
export function isArchivedProject(project) {
return (project?.status || 'active') === 'archived';
}
export function formatProjectOptionLabel(project, t, fallbackLabel = '') {
const base = project?.name || project?.id || fallbackLabel;
if (!isArchivedProject(project)) return base;
return `${base}(${t('projects.statusArchived', null, '已归档')})`;
}
/**
* 新建/绑定表单的项目下拉项:仅列出进行中的项目;
* 若当前记录已绑定到某个已归档项目(currentId),保留该项并标注“已归档”。
*/
export function activeProjectOptions(projects, t, { currentId = '', disableCurrentArchived = false, fallbackLabel = '' } = {}) {
const seen = new Set();
const out = [];
(Array.isArray(projects) ? projects : []).forEach(project => {
if (!project?.id || seen.has(project.id)) return;
const archived = isArchivedProject(project);
if (archived && project.id !== currentId) return;
seen.add(project.id);
out.push({
value: project.id,
label: formatProjectOptionLabel(project, t, fallbackLabel),
...(archived && disableCurrentArchived ? { disabled: true } : {})
});
});
return out;
}

View File

@ -3,6 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { Banner, Button, Form, Space } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { activeProjectOptions } from '../../../lib/project-options';
import { Drawer, toastSuccess, toastWarning } from '../../../components/ui';
import {
CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, STATUS_OPTIONS
@ -55,8 +56,8 @@ export default function AssetEditorModal({ visible, asset, defaultProjectId = ''
}, [visible, asset]);
const projectOptions = useMemo(
() => (projects || []).map(project => ({ value: project.id, label: project.name || project.id })),
[projects]
() => activeProjectOptions(projects, t, { currentId: values.project_id }),
[projects, t, values.project_id]
);
const applyTarget = (showError) => {

View File

@ -6,6 +6,7 @@ import { IconPlus, IconRefresh, IconCloudUploadStroked } from '@douyinfe/semi-ic
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { formatProjectOptionLabel } from '../../lib/project-options';
import { useDebounced, useResource } from '../../components/hooks';
import {
ErrorBanner, PageHeader, SectionCard, confirmAction, toastError, toastSuccess, toastWarning
@ -114,7 +115,7 @@ function AssetLibraryWorkspace({ projectId, scope, projectResource, searchParams
const scopeOptions = [
{ value: 'all', label: t('assets.scopeAll', null, '全部资产') },
{ value: 'unassigned', label: t('assets.scopeUnassigned', null, '未归属项目') },
...projects.map(project => ({ value: `project:${project.id}`, label: project.name || project.id }))
...projects.map(project => ({ value: `project:${project.id}`, label: formatProjectOptionLabel(project, t) }))
];
if (projectId && !scopeOptions.some(option => option.value === scope)) {
scopeOptions.push({ value: scope, label: projectId });

View File

@ -5,6 +5,7 @@ import { useState } from 'react';
import { Button, Form, Space, Typography } from '@douyinfe/semi-ui';
import { Drawer } from '../../components/ui';
import { useT } from '../../lib/i18n';
import { activeProjectOptions } from '../../lib/project-options';
import { LISTENER_TYPES } from '../c2-sessions/components/c2-shared';
const { Text } = Typography;
@ -132,7 +133,7 @@ export default function ListenerForm({ visible, record, projects, profiles, subm
field="project_id"
label={t('c2.listeners.project', null, '所属项目')}
optionList={[{ value: '', label: t('c2.listeners.projectNone', null, '不绑定项目') },
...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
...activeProjectOptions(projects, t, { currentId: record?.project_id || '' })]}
style={{ width: '100%' }}
/>
<Form.Input field="remark" label={t('c2.listeners.remark', null, '备注')} placeholder={t('c2.listeners.placeholderRemarkLong', null, '可选的备注说明')} />

View File

@ -2,6 +2,7 @@ import { useId, useMemo, useRef } from 'react';
import { Banner, Button, Popover, Select, Tag, TextArea, Tooltip, Typography } from '@douyinfe/semi-ui';
import { IconArrowUp, IconChevronDown, IconDesktop, IconFolder, IconPaperclip, IconPlus, IconShield, IconStop, IconUser } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
import { activeProjectOptions } from '../../lib/project-options';
import { modelChannelName } from '../../lib/model-channel';
import { ModelSettings } from './ChatSettings';
import { reasoningSummary } from './useModelPreferences';
@ -79,10 +80,11 @@ export default function Composer({
})), [t]);
const projectOptions = [
{ value: '', label: t('chat.defaultWorkspace', null, '默认工作区') },
...(Array.isArray(projects) ? projects : []).map(project => ({
value: project.id,
label: project.name || t('chat.boundProject', null, '已绑定项目')
}))
...activeProjectOptions(projects, t, {
currentId: projectId,
disableCurrentArchived: true,
fallbackLabel: t('chat.boundProject', null, '已绑定项目')
})
];
if (projectId && !projectOptions.some(option => option.value === projectId)) {
projectOptions.push({ value: projectId, label: t('chat.boundProject', null, '已绑定项目') });

View File

@ -6,6 +6,7 @@ import {
import { IconChevronDown, IconDelete, IconEdit, IconFolder, IconPlus, IconRefresh, IconSearch, IconStar } from '@douyinfe/semi-icons';
import { ErrorBanner } from '../../components/ui';
import { useT } from '../../lib/i18n';
import { formatProjectOptionLabel } from '../../lib/project-options';
import { formatDateTime } from '../../lib/format';
const { Text } = Typography;
@ -101,6 +102,7 @@ export default function ConversationList({
const t = useT();
const list = items;
const groupContentId = useId();
const filterProjectLabelId = useId();
const [editingId, setEditingId] = useState('');
const [editingTitle, setEditingTitle] = useState('');
const [batchMode, setBatchMode] = useState(false);
@ -117,7 +119,7 @@ export default function ConversationList({
{ value: '', label: t('chat.filterAllProjects', null, '全部项目') },
...(Array.isArray(projects) ? projects : []).map(project => ({
value: project.id,
label: project.name || project.id
label: formatProjectOptionLabel(project, t)
}))
]), [projects, t]);
@ -193,12 +195,13 @@ export default function ConversationList({
onChange={onSearch}
showClear
/>
<span id={filterProjectLabelId} hidden>{t('chat.filterByProject', null, '按项目过滤')}</span>
<Select
value={projectId}
optionList={projectOptions}
onChange={onProjectChange}
className="chat-sidebar-project"
aria-label={t('chat.filterByProject', null, '按项目过滤')}
aria-labelledby={filterProjectLabelId}
placeholder={t('chat.filterByProject', null, '按项目过滤')}
/>
</div>

View File

@ -8,6 +8,7 @@ import { IconRefresh, IconSearch, IconCloudUploadStroked } from '@douyinfe/semi-
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
import { activeProjectOptions } from '../../lib/project-options';
import { useLocalStorage } from '../../components/hooks';
import {
ErrorBanner, JsonViewer, KeyValueList, PageHeader, SectionCard,
@ -294,7 +295,7 @@ export default function InfoCollectPage() {
<Space className="info-collect-form-row">
<Select
value={projectId}
optionList={[{ value: '', label: '不归入项目集合' }, ...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
optionList={[{ value: '', label: '不归入项目集合' }, ...activeProjectOptions(projects, t, { currentId: projectId })]}
placeholder="归入项目"
style={{ width: 220 }}
onChange={value => setProjectId(value || '')}

View File

@ -3,6 +3,7 @@ import { useEffect, useState } from 'react';
import { Checkbox, Input, Select, TextArea, Typography } from '@douyinfe/semi-ui';
import { api } from '../../lib/http';
import { useT } from '../../lib/i18n';
import { activeProjectOptions } from '../../lib/project-options';
import { useAuth } from '../../lib/auth';
import { Drawer, toastError, toastSuccess } from '../../components/ui';
import { AGENT_MODES, HITL_POLICIES, SCHEDULE_MODES, errText } from './helpers';
@ -156,7 +157,7 @@ export default function QueueFormModal({ visible, onCancel, onCreated }) {
value={form.projectId}
style={{ width: '100%' }}
optionList={[{ value: '', label: t('batchImportModal.projectNone', null, '(未绑定)') },
...projects.map(item => ({ value: item.id, label: item.name || item.id }))]}
...activeProjectOptions(projects, t, { currentId: form.projectId })]}
onChange={value => update({ projectId: value || '', collectionId: '' })}
/>
</div>

View File

@ -2,6 +2,7 @@
import { useEffect, useState } from 'react';
import { Form, Spin, Typography } from '@douyinfe/semi-ui';
import { api, errorMessage } from '../../lib/http';
import { activeProjectOptions } from '../../lib/project-options';
import { Drawer, toastError } from '../../components/ui';
import { severityOptions, statusOptions } from './shared';
@ -52,7 +53,7 @@ function trim(value) {
return String(value ?? '').trim();
}
export default function EditModal({ visible, vulnId, t, projectOptions, onClose, onSaved }) {
export default function EditModal({ visible, vulnId, t, projects, onClose, onSaved }) {
const editing = Boolean(vulnId);
const [formApi, setFormApi] = useState(null);
const [saving, setSaving] = useState(false);
@ -81,6 +82,7 @@ export default function EditModal({ visible, vulnId, t, projectOptions, onClose,
const ready = !editing || loadedFor === vulnId;
const formValues = editing ? initial : { ...EMPTY_VALUES };
const projectOptions = activeProjectOptions(projects, t, { currentId: formValues.project_id });
const submit = async () => {
if (!formApi || saving) return;

View File

@ -163,14 +163,6 @@ export default function VulnerabilitiesPage() {
return [...seen.entries()].map(([value, label]) => ({ value, label }));
}, [options.data, projectNames, filters.project_id]);
const formProjectOptions = useMemo(() => {
const seen = new Map();
(projects.data || []).forEach(project => {
if (project?.id) seen.set(project.id, project.name || project.id);
});
return [...seen.entries()].map(([value, label]) => ({ value, label }));
}, [projects.data]);
const [selection, setSelection] = useState([]);
const [editor, setEditor] = useState({ visible: false, id: '' });
const [detailVersion, setDetailVersion] = useState(0);
@ -557,7 +549,7 @@ export default function VulnerabilitiesPage() {
visible={editor.visible}
vulnId={editor.id}
t={t}
projectOptions={formProjectOptions}
projects={projects.data}
onClose={() => setEditor({ visible: false, id: '' })}
onSaved={handleSaved}
/>

View File

@ -4,6 +4,7 @@
import { useState } from 'react';
import { Form, Button, Space, Typography } from '@douyinfe/semi-ui';
import { useT } from '../../lib/i18n';
import { activeProjectOptions } from '../../lib/project-options';
import { Drawer, toastError, toastSuccess, toastWarning } from '../../components/ui';
import { probeConnection, MASKED_SECRET } from './api';
@ -153,7 +154,7 @@ export default function ConnectionForm({ visible, record, projects, submitting,
<Form.Select
field="project_id"
label={t('webshell.project', null, '所属项目')}
optionList={projects.map(item => ({ value: item.id, label: item.name || item.id }))}
optionList={activeProjectOptions(projects, t, { currentId: record?.project_id || '' })}
showClear
style={{ width: '100%' }}
placeholder="可选"

View File

@ -72,3 +72,30 @@ test('project archive keeps history accessible and preserves a manual vulnerabil
expect(mockApi.calls('PUT', manualPath).map(call => call.body)).toEqual([{ archived: true }, { archived: false }]);
expect(mockApi.calls('PUT', projectPath).map(call => call.body)).toEqual([{ status: 'archived' }, { status: 'active' }]);
});
test('archived projects are excluded from new workspace and finding selectors while remaining visible in history filters', async ({ page, mockApi }) => {
const activeProject = { ...PROJECT, id: 'proj-active', name: '进行中示例项目', status: 'active' };
const archivedProject = { ...PROJECT, id: 'proj-archived', name: '已归档历史项目', status: 'archived' };
const archivedLabel = `${archivedProject.name}(${label('projects.statusArchived', '已归档')})`;
mockApi.respond('GET', '/api/projects', () => ({
json: { projects: [activeProject, archivedProject], total: 2 }
}));
const chat = await visit(page, 'chat');
await chat.getByRole('combobox', { name: label('chat.chooseWorkspace', '选择会话工作区') }).click();
await expect(page.getByRole('option').filter({ hasText: activeProject.name })).toHaveCount(1);
await expect(page.getByRole('option').filter({ hasText: archivedProject.name })).toHaveCount(0);
await page.keyboard.press('Escape');
await chat.getByRole('combobox', { name: label('chat.filterByProject', '按项目过滤') }).click();
await expect(page.getByRole('option').filter({ hasText: archivedLabel })).toHaveCount(1);
await page.keyboard.press('Escape');
const vulnerabilities = await visit(page, 'vulnerabilities');
await vulnerabilities.getByRole('button', { name: label('vulnerability.addVuln', '添加漏洞') }).click();
const drawer = page.getByRole('dialog');
await drawer.getByRole('combobox', { name: label('vulnerabilityModal.project', '所属项目') }).click();
await expect(page.getByRole('option').filter({ hasText: activeProject.name })).toHaveCount(1);
await expect(page.getByRole('option').filter({ hasText: archivedProject.name })).toHaveCount(0);
});

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -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-BZrJi-2j.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-CYhbA2Rl.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

View File

@ -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-BZrJi-2j.js";import"./c2-shared-DBmpvtOo.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-CYhbA2Rl.js";import"./c2-shared-D5UgZ1Rr.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};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-BZrJi-2j.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-CYhbA2Rl.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

View File

@ -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-BZrJi-2j.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-CYhbA2Rl.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};

View File

@ -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-BZrJi-2j.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-CYhbA2Rl.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};

View File

@ -0,0 +1 @@
function e(e){return(e?.status||`active`)===`archived`}function t(t,n,r=``){let i=t?.name||t?.id||r;return e(t)?`${i}(${n(`projects.statusArchived`,null,`已归档`)})`:i}function n(n,r,{currentId:i=``,disableCurrentArchived:a=!1,fallbackLabel:o=``}={}){let s=new Set,c=[];return(Array.isArray(n)?n:[]).forEach(n=>{if(!n?.id||s.has(n.id))return;let l=e(n);l&&n.id!==i||(s.add(n.id),c.push({value:n.id,label:t(n,r,o),...l&&a?{disabled:!0}:{}}))}),c}export{t as n,n as t};

View File

@ -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-BZrJi-2j.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-CYhbA2Rl.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(`

View File

@ -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-BZrJi-2j.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-CYhbA2Rl.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

File diff suppressed because one or more lines are too long

View File

@ -18,7 +18,7 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-BZrJi-2j.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-CYhbA2Rl.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">