Compare commits

..
Author SHA1 Message Date
ji ruo ea49ba0a3a fix(intercept): avoid full-history polling and full-table counts
- Add partial covering index on intercept_pending(task_id, created_at DESC) INCLUDE (agent_name) WHERE status = 'pending'.
- Add GET /api/intercept/pending/summary (global count or per-task count + agent_names) and ?task_id= filtering on GET /api/intercept/pending.
- Cap unpaginated GET /api/intercept/task/{taskID} at 200 rows and remove unused tasks JOIN from non-search approval queries.
- Replace unbounded SELECT COUNT(*) in paginated approval queries with end-of-list shortcut, pg_class/pg_stat catalog estimate for large unfiltered tables, and bounded counting (10,000 cap) for large filtered sets.
- Deduplicate task detail and sessions-tab polling via single pending summary poll, switch sidebar badge to summary count, and guard approval polling against background tabs, overlapping requests, and deep-page/search churn.

Fixes #186
2026-11-26 00:54:26 +08:00
30 changed files with 720 additions and 1135 deletions

No files matched your search

-3
View File
@@ -80,9 +80,6 @@ func normalizeArchivedFindingVersions(raw json.RawMessage) (json.RawMessage, err
row[key] = 0
}
}
if row["remark"] == nil {
row["remark"] = ""
}
}
return json.Marshal(rows)
}
+7 -52
View File
@@ -10,7 +10,6 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"
)
// DBFinding is a row in the standalone findings table. It persists across task
@@ -35,7 +34,6 @@ type DBFinding struct {
Worker string
AssetIDs []int64
Status string
Remark string // 人工备注
Report string // 详细报告(Markdown);仅 GetFinding 填充,列表查询不带
ReportConversationID *int64 `json:"report_conversation_id,omitempty"`
CreatedAt time.Time
@@ -82,9 +80,6 @@ func ValidSeverity(s string) bool {
return false
}
// MaxFindingRemarkRunes is the maximum rune count allowed for a finding remark.
const MaxFindingRemarkRunes = 2000
// AddFinding inserts a finding into the standalone findings table. taskID and
// nodeID may be 0 (stored as NULL). name may be "" (frontend falls back to
// vulnclass). Returns the new finding id.
@@ -112,7 +107,7 @@ func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary
// findingSelectCols is the column list (with task_description join) every finding
// list query selects, so scanFinding stays in sync across callers.
const findingSelectCols = `f.id, f.task_id, f.node_id, f.vulnclass, COALESCE(f.name, ''), f.severity, f.summary,
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), COALESCE(f.remark, ''), f.created_at,
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), f.created_at,
COALESCE(t.description, '') AS task_description, f.evidence_version, f.report_evidence_version,
(SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=f.id)`
@@ -127,7 +122,7 @@ func scanFindings(rows interface {
f := &DBFinding{}
var aidsJSON string
if err := rows.Scan(&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt, &f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount); err != nil {
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt, &f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount); err != nil {
return nil, err
}
_ = json.Unmarshal([]byte(aidsJSON), &f.AssetIDs)
@@ -254,9 +249,8 @@ func (f FindingFilter) where() (string, []any) {
f.vulnclass ILIKE %s ESCAPE '\' OR
f.summary ILIKE %s ESCAPE '\' OR
f.evidence ILIKE %s ESCAPE '\' OR
COALESCE(f.remark, '') ILIKE %s ESCAPE '\' OR
COALESCE(f.report, '') ILIKE %s ESCAPE '\'
)`, placeholder, placeholder, placeholder, placeholder, placeholder, placeholder))
)`, placeholder, placeholder, placeholder, placeholder, placeholder))
}
if len(conds) == 0 {
return "", args
@@ -544,7 +538,7 @@ func (d *DB) ListFindingsForExport(f FindingFilter, ids []int64) ([]*DBFinding,
f := &DBFinding{}
var aidsJSON string
if err := rows.Scan(&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt,
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report); err != nil {
return nil, err
}
@@ -711,7 +705,7 @@ func (d *DB) GetFinding(id int64) (*DBFinding, error) {
LEFT JOIN tasks t ON f.task_id = t.id
WHERE f.id = $1`, id).Scan(
&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt,
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt,
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report, &reportConv)
if err == sql.ErrNoRows {
return nil, nil
@@ -993,43 +987,6 @@ func (d *DB) SetFindingVulnClass(id int64, vulnclass string) (int64, error) {
return d.setFindingCol(id, "vulnclass", "vulnclass", vulnclass)
}
// SetFindingSummary updates one finding's summary (+ node payload sync).
func (d *DB) SetFindingSummary(id int64, summary string) (int64, error) {
return d.setFindingCol(id, "summary", "summary", summary)
}
// SetFindingEvidence updates one finding's evidence text on the standalone findings row.
func (d *DB) SetFindingEvidence(id int64, evidence string) (int64, error) {
res, err := d.Exec(`UPDATE findings SET evidence=$1 WHERE id=$2`, evidence, id)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// SetFindingReport updates one finding's Markdown report and aligns report_evidence_version
// with the current evidence_version so manual edits clear any stale-report warning.
func (d *DB) SetFindingReport(id int64, report string) (int64, error) {
res, err := d.Exec(`UPDATE findings SET report=$1, report_evidence_version=evidence_version WHERE id=$2`, report, id)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// SetFindingRemark updates one finding's manual remark. Returns rows affected.
func (d *DB) SetFindingRemark(id int64, remark string) (int64, error) {
remark = strings.TrimSpace(remark)
if utf8.RuneCountInString(remark) > MaxFindingRemarkRunes {
return 0, fmt.Errorf("备注最多 %d 个字符", MaxFindingRemarkRunes)
}
res, err := d.Exec(`UPDATE findings SET remark=$1 WHERE id=$2`, remark, id)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// FindingMeta is the standalone-row data (id, triage state, anchored assets) the
// per-task view grafts onto its exploration-node findings.
type FindingMeta struct {
@@ -1037,8 +994,6 @@ type FindingMeta struct {
ID int64
Status string
Remark string
Evidence string
AssetIDs []int64
}
@@ -1057,7 +1012,7 @@ func (d *DB) FindingMetaByNodeID(taskID int64) (map[int64]FindingMeta, error) {
if taskID <= 0 {
return out, nil
}
rows, err := d.Query(`SELECT node_id, id, COALESCE(status,'pending'), COALESCE(remark,''), COALESCE(evidence,''), asset_ids, (SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=findings.id) FROM findings
rows, err := d.Query(`SELECT node_id, id, COALESCE(status,'pending'), asset_ids, (SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=findings.id) FROM findings
WHERE task_id=$1 AND node_id IS NOT NULL`, taskID)
if err != nil {
return out, err
@@ -1067,7 +1022,7 @@ func (d *DB) FindingMetaByNodeID(taskID int64) (map[int64]FindingMeta, error) {
var nid int64
var m FindingMeta
var aidsJSON string
if err := rows.Scan(&nid, &m.ID, &m.Status, &m.Remark, &m.Evidence, &aidsJSON, &m.TrafficCount); err != nil {
if err := rows.Scan(&nid, &m.ID, &m.Status, &aidsJSON, &m.TrafficCount); err != nil {
return out, err
}
_ = json.Unmarshal([]byte(aidsJSON), &m.AssetIDs)
-94
View File
@@ -644,97 +644,3 @@ func TestDeleteFindings(t *testing.T) {
t.Fatal(err)
}
}
func TestFindingRemarkAndManualEdit(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
defer d.Close()
vc := fmt.Sprintf("__test_finding_remark_%d__", time.Now().UnixNano())
tk, err := d.CreateTask("remark test", "goal", nil, 0, 0)
if err != nil {
t.Fatalf("CreateTask: %v", err)
}
t.Cleanup(func() {
_, _ = d.Exec(`DELETE FROM findings WHERE vulnclass=$1`, vc)
_ = d.DeleteTask(tk.ID)
})
es := d.Exploration(tk.ExplorationID)
nodeID, err := es.AddNode(KindFinding, map[string]any{
"vulnclass": vc,
"name": "old title",
"severity": SeverityMedium,
"summary": "old summary",
"evidence": "old proof",
}, 5, "confirmed", "tester", nil)
if err != nil {
t.Fatalf("AddNode: %v", err)
}
fid, err := d.AddFinding(tk.ID, nodeID, vc, "old title", SeverityMedium, "old summary", "old proof", "tester", nil)
if err != nil {
t.Fatalf("AddFinding: %v", err)
}
if n, err := d.SetFindingRemark(fid, " 已人工复核,需要内网 Cookie "); err != nil || n != 1 {
t.Fatalf("SetFindingRemark: n=%d err=%v", n, err)
}
if n, err := d.SetFindingSummary(fid, "updated summary"); err != nil || n != 1 {
t.Fatalf("SetFindingSummary: n=%d err=%v", n, err)
}
if n, err := d.SetFindingEvidence(fid, "GET /admin HTTP/1.1"); err != nil || n != 1 {
t.Fatalf("SetFindingEvidence: n=%d err=%v", n, err)
}
if n, err := d.SetFindingReport(fid, "## 手工报告\n已确认"); err != nil || n != 1 {
t.Fatalf("SetFindingReport: n=%d err=%v", n, err)
}
got, err := d.GetFinding(fid)
if err != nil || got == nil {
t.Fatalf("GetFinding: got=%+v err=%v", got, err)
}
if got.Remark != "已人工复核,需要内网 Cookie" || got.Summary != "updated summary" || got.Evidence != "GET /admin HTTP/1.1" || got.Report != "## 手工报告\n已确认" {
t.Fatalf("unexpected updated finding: %+v", got)
}
// Search must match remark.
matches, total, err := d.ListFindingsPage(FindingFilter{VulnClass: vc, Query: "内网 Cookie"}, 1, 20)
if err != nil || total != 1 || len(matches) != 1 || matches[0].ID != fid || matches[0].Remark != got.Remark {
t.Fatalf("search by remark failed: matches=%+v total=%d err=%v", matches, total, err)
}
// Per-task metadata must expose remark and updated evidence.
meta, err := d.FindingMetaByNodeID(tk.ID)
if err != nil {
t.Fatalf("FindingMetaByNodeID: %v", err)
}
if m := meta[nodeID]; m.Remark != got.Remark || m.Evidence != "GET /admin HTTP/1.1" {
t.Fatalf("FindingMetaByNodeID mismatch: %+v", m)
}
// Over-limit remark must be rejected without modifying stored value.
tooLong := strings.Repeat("备", MaxFindingRemarkRunes+1)
if _, err := d.SetFindingRemark(fid, tooLong); err == nil {
t.Fatal("expected over-limit remark to fail")
}
afterErr, _ := d.GetFinding(fid)
if afterErr.Remark != got.Remark {
t.Fatalf("remark mutated on error: %q", afterErr.Remark)
}
// Clearing remark to empty string must succeed.
if n, err := d.SetFindingRemark(fid, " "); err != nil || n != 1 {
t.Fatalf("clear remark: n=%d err=%v", n, err)
}
cleared, _ := d.GetFinding(fid)
if cleared.Remark != "" {
t.Fatalf("expected empty remark, got %q", cleared.Remark)
}
// Unknown IDs return 0 affected rows.
if n, err := d.SetFindingRemark(-1, "x"); err != nil || n != 0 {
t.Fatalf("SetFindingRemark(-1): n=%d err=%v", n, err)
}
}
+201 -21
View File
@@ -197,6 +197,64 @@ func (d *DB) ListPendingIntercepts() ([]InterceptPending, error) {
return out, rows.Err()
}
// ListPendingInterceptsByTask returns unresolved approval requests for one task,
// newest first.
func (d *DB) ListPendingInterceptsByTask(taskID string) ([]InterceptPending, error) {
rows, err := d.Query(`SELECT `+interceptPendingCols+` FROM intercept_pending WHERE status='pending' AND task_id=$1 ORDER BY created_at DESC`, taskID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []InterceptPending
for rows.Next() {
var p InterceptPending
if err := scanInterceptPending(rows, &p); err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// InterceptPendingSummary is a lightweight snapshot of unresolved approval
// requests without loading tool_input JSONB or historical rows.
type InterceptPendingSummary struct {
Count int `json:"count"`
AgentNames []string `json:"agent_names,omitempty"`
}
// CountPendingIntercepts returns the number of unresolved approval requests.
func (d *DB) CountPendingIntercepts() (int, error) {
var count int
if err := d.QueryRow(`SELECT COUNT(*) FROM intercept_pending WHERE status='pending'`).Scan(&count); err != nil {
return 0, err
}
return count, nil
}
// TaskPendingInterceptSummary returns the pending count and distinct agent names
// awaiting approval for one task.
func (d *DB) TaskPendingInterceptSummary(taskID string) (InterceptPendingSummary, error) {
rows, err := d.Query(`SELECT agent_name, COUNT(*) FROM intercept_pending WHERE status='pending' AND task_id=$1 GROUP BY agent_name ORDER BY agent_name`, taskID)
if err != nil {
return InterceptPendingSummary{}, err
}
defer rows.Close()
out := InterceptPendingSummary{AgentNames: []string{}}
for rows.Next() {
var agent string
var n int
if err := rows.Scan(&agent, &n); err != nil {
return InterceptPendingSummary{}, err
}
out.Count += n
if agent != "" {
out.AgentNames = append(out.AgentNames, agent)
}
}
return out, rows.Err()
}
// GetInterceptPending returns one pending record (nil if absent).
func (d *DB) GetInterceptPending(id int64) (*InterceptPending, error) {
var p InterceptPending
@@ -243,10 +301,13 @@ const approvalRowColumns = `ip.id, ip.rule_id, ip.conversation_id, ip.task_id, i
const approvalRowJoins = `
FROM intercept_pending ip
LEFT JOIN conversations c ON c.id = ip.conversation_id
LEFT JOIN tasks t ON t.id::text = ip.task_id
LEFT JOIN intercept_rules ir ON ir.id = ip.rule_id`
const approvalRowSearchJoins = approvalRowJoins + `
LEFT JOIN tasks t ON t.id::text = ip.task_id`
const approvalRowSelect = `SELECT ` + approvalRowColumns + approvalRowJoins
const approvalRowSearchSelect = `SELECT ` + approvalRowColumns + approvalRowSearchJoins
const approvalRowSelectWithAudit = `SELECT ` + approvalRowColumns + `, ip.audit` + approvalRowJoins
func interceptSource(ruleID int64, reason string) string {
@@ -299,14 +360,42 @@ type InterceptApprovalFilter struct {
CreatedTo string // inclusive UTC calendar date, YYYY-MM-DD
}
// ListAllInterceptsPage returns one 1-based page and the total matching count.
func (d *DB) ListAllInterceptsPage(page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
// InterceptApprovalPage is one 1-based page of approval history.
// When TotalApproximate is true, Total is either a PostgreSQL table-size
// estimate (unfiltered large table) or a lower bound (TotalCapped == true)
// rather than an exact full-table count.
type InterceptApprovalPage struct {
Items []InterceptApprovalRow
Total int
TotalApproximate bool
TotalCapped bool
HasMore bool
}
// interceptExactCountCap bounds exact COUNT(*) scans so large tables never
// trigger unbounded full scans on every poll. Tests may override it.
var interceptExactCountCap = 10000
// ListAllInterceptsPage returns one 1-based page and matching count metadata.
func (d *DB) ListAllInterceptsPage(page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
return d.listInterceptsPage("", page, size, filter)
}
// ListTaskIntercepts returns all intercept_pending rows for a specific task (newest first).
func (d *DB) ListTaskIntercepts(taskID string) ([]InterceptApprovalRow, error) {
rows, err := d.Query(approvalRowSelect+` WHERE ip.task_id=$1 ORDER BY ip.created_at DESC`, taskID)
return d.ListTaskInterceptsLimit(taskID, 0)
}
// ListTaskInterceptsLimit returns up to limit intercept_pending rows for a
// specific task (newest first). limit <= 0 returns all rows.
func (d *DB) ListTaskInterceptsLimit(taskID string, limit int) ([]InterceptApprovalRow, error) {
q := approvalRowSelect + ` WHERE ip.task_id=$1 ORDER BY ip.created_at DESC, ip.id DESC`
args := []any{taskID}
if limit > 0 {
q += ` LIMIT $2`
args = append(args, limit)
}
rows, err := d.Query(q, args...)
if err != nil {
return nil, err
}
@@ -323,11 +412,37 @@ func (d *DB) ListTaskIntercepts(taskID string) ([]InterceptApprovalRow, error) {
}
// ListTaskInterceptsPage is the paginated variant of ListTaskIntercepts.
func (d *DB) ListTaskInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
func (d *DB) ListTaskInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
return d.listInterceptsPage(taskID, page, size, filter)
}
func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) ([]InterceptApprovalRow, int, error) {
// estimateInterceptTableRows reads PostgreSQL's live row estimate for
// intercept_pending without scanning the table.
func (d *DB) estimateInterceptTableRows() (int64, error) {
var relTuples, liveTuples, deadTuples int64
err := d.QueryRow(`
SELECT
CASE WHEN c.reltuples >= 0 THEN c.reltuples::bigint ELSE -1 END,
pg_stat_get_live_tuples(c.oid),
pg_stat_get_dead_tuples(c.oid)
FROM pg_class c
WHERE c.oid = 'intercept_pending'::regclass`).Scan(&relTuples, &liveTuples, &deadTuples)
if err != nil {
return 0, err
}
if liveTuples > 0 {
return liveTuples, nil
}
if liveTuples == 0 && deadTuples > 0 {
return 0, nil
}
if relTuples > 0 {
return relTuples, nil
}
return 0, nil
}
func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptApprovalFilter) (InterceptApprovalPage, error) {
if page < 1 {
page = 1
}
@@ -359,13 +474,15 @@ func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptA
conditions = append(conditions, "ip.created_at < ($"+fmt.Sprint(len(args))+"::date + INTERVAL '1 day')")
}
search := strings.TrimSpace(filter.Search)
hasTextSearch := false
if strings.HasPrefix(search, "#") {
id, err := strconv.ParseInt(strings.TrimPrefix(search, "#"), 10, 64)
if err != nil || id <= 0 {
return nil, 0, fmt.Errorf("审批编号必须为 # 后接正整数")
return InterceptApprovalPage{}, fmt.Errorf("审批编号必须为 # 后接正整数")
}
add("ip.id", strconv.FormatInt(id, 10))
} else if search != "" {
hasTextSearch = true
// Treat SQL LIKE metacharacters literally, including URL percent escapes.
pattern := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(search)
args = append(args, "%"+pattern+"%")
@@ -391,33 +508,96 @@ func (d *DB) listInterceptsPage(taskID string, page, size int, filter InterceptA
if len(conditions) > 0 {
where = " WHERE " + strings.Join(conditions, " AND ")
}
var total int
countFrom := "FROM intercept_pending ip"
if search != "" && !strings.HasPrefix(search, "#") {
countFrom = approvalRowJoins
}
if err := d.QueryRow("SELECT COUNT(*) "+countFrom+where, args...).Scan(&total); err != nil {
return nil, 0, err
}
selectClause := approvalRowSelect
if hasTextSearch {
selectClause = approvalRowSearchSelect
}
limitArg := len(args) + 1
offsetArg := limitArg + 1
dataQ := approvalRowSelect + where +
dataQ := selectClause + where +
" ORDER BY ip.created_at DESC, ip.id DESC LIMIT $" + fmt.Sprint(limitArg) +
" OFFSET $" + fmt.Sprint(offsetArg)
args = append(args, size, offset)
rows, err := d.Query(dataQ, args...)
dataArgs := make([]any, 0, len(args)+2)
dataArgs = append(dataArgs, args...)
dataArgs = append(dataArgs, size+1, offset)
rows, err := d.Query(dataQ, dataArgs...)
if err != nil {
return nil, 0, err
return InterceptApprovalPage{}, err
}
defer rows.Close()
out := []InterceptApprovalRow{}
for rows.Next() {
var r InterceptApprovalRow
if err := scanInterceptApprovalRow(rows, &r); err != nil {
return nil, 0, err
return InterceptApprovalPage{}, err
}
out = append(out, r)
}
return out, total, rows.Err()
if err := rows.Err(); err != nil {
return InterceptApprovalPage{}, err
}
hasMore := len(out) > size
if hasMore {
out = out[:size]
}
// Fast path: when we already hit the end of the result set on a non-empty
// page (or page 1), the exact total is known without a separate COUNT query.
if !hasMore && (len(out) > 0 || offset == 0) {
return InterceptApprovalPage{
Items: out,
Total: offset + len(out),
HasMore: false,
}, nil
}
capLimit := interceptExactCountCap
if capLimit < offset+size {
capLimit = offset + size
}
// For large unfiltered global queries, use PostgreSQL's catalog estimate
// instead of scanning the entire intercept_pending table.
if len(conditions) == 0 {
if est, estErr := d.estimateInterceptTableRows(); estErr == nil && est > int64(capLimit) {
total := int(est)
if hasMore && total <= offset+len(out) {
total = offset + len(out) + 1
}
return InterceptApprovalPage{
Items: out,
Total: total,
TotalApproximate: true,
HasMore: hasMore,
}, nil
}
}
countFrom := "FROM intercept_pending ip"
if hasTextSearch {
countFrom = approvalRowSearchJoins
}
capArg := len(args) + 1
countArgs := make([]any, 0, len(args)+1)
countArgs = append(countArgs, args...)
countArgs = append(countArgs, capLimit+1)
var counted int
countQ := "SELECT COUNT(*) FROM (SELECT 1 " + countFrom + where + " LIMIT $" + fmt.Sprint(capArg) + ") s"
if err := d.QueryRow(countQ, countArgs...).Scan(&counted); err != nil {
return InterceptApprovalPage{}, err
}
if counted > capLimit {
return InterceptApprovalPage{
Items: out,
Total: capLimit,
TotalApproximate: true,
TotalCapped: true,
HasMore: hasMore,
}, nil
}
return InterceptApprovalPage{
Items: out,
Total: counted,
HasMore: hasMore,
}, nil
}
+114 -34
View File
@@ -21,10 +21,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
}
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_rules WHERE id=$1`, rule.ID) })
filter := InterceptApprovalFilter{Status: "denied", DecisionSource: "model"}
_, baseline, err := d.ListAllInterceptsPage(1, 20, filter)
basePage, err := d.ListAllInterceptsPage(1, 20, filter)
if err != nil {
t.Fatal(err)
}
baseline := basePage.Total
expected := []int64{}
for _, task := range []string{scope, scope + "-other"} {
copies := 3
@@ -85,11 +86,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rows, total, err := d.ListTaskInterceptsPage(scope, 1, 100, tc.filter)
if err != nil || total != tc.want || len(rows) != tc.want {
t.Fatalf("count=%d rows=%d err=%v", total, len(rows), err)
res, err := d.ListTaskInterceptsPage(scope, 1, 100, tc.filter)
if err != nil || res.Total != tc.want || len(res.Items) != tc.want {
t.Fatalf("count=%d rows=%d err=%v", res.Total, len(res.Items), err)
}
for _, r := range rows {
for _, r := range res.Items {
if r.TaskID == nil || *r.TaskID != scope || tc.filter.Status != "" && r.Status != tc.filter.Status || tc.filter.DecisionSource != "" && r.DecisionSource != tc.filter.DecisionSource {
t.Fatalf("nonmatching row: %+v", r)
}
@@ -99,29 +100,32 @@ func TestInterceptApprovalFilters(t *testing.T) {
slices.Reverse(expected)
var seen []int64
for page := 1; page <= 2; page++ {
rows, total, err := d.ListTaskInterceptsPage(scope, page, 2, filter)
if err != nil || total != 3 {
t.Fatalf("page %d total=%d err=%v", page, total, err)
res, err := d.ListTaskInterceptsPage(scope, page, 2, filter)
if err != nil || res.Total != 3 {
t.Fatalf("page %d total=%d err=%v", page, res.Total, err)
}
for _, r := range rows {
if wantMore := page == 1; res.HasMore != wantMore {
t.Fatalf("page %d hasMore=%v want=%v", page, res.HasMore, wantMore)
}
for _, r := range res.Items {
seen = append(seen, r.ID)
}
}
if !slices.Equal(seen, expected) {
t.Fatalf("unstable combined-filter pagination: got %v want %v", seen, expected)
}
rows, total, err := d.ListTaskInterceptsPage(scope, 3, 2, filter)
if err != nil || len(rows) != 0 || total != 3 {
t.Fatalf("empty page count=%d rows=%d err=%v", total, len(rows), err)
res, err := d.ListTaskInterceptsPage(scope, 3, 2, filter)
if err != nil || len(res.Items) != 0 || res.Total != 3 || res.HasMore {
t.Fatalf("empty page count=%d rows=%d hasMore=%v err=%v", res.Total, len(res.Items), res.HasMore, err)
}
_, total, err = d.ListAllInterceptsPage(1, 100, filter)
if err != nil || total != baseline+4 {
t.Fatalf("global filter count=%d want=%d err=%v", total, baseline+4, err)
globalRes, err := d.ListAllInterceptsPage(1, 100, filter)
if err != nil || globalRes.Total != baseline+4 {
t.Fatalf("global filter count=%d want=%d err=%v", globalRes.Total, baseline+4, err)
}
// Values must remain SQL parameters even for direct store callers.
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Status: "denied' OR 1=1 --"})
if err != nil || total != 0 || len(rows) != 0 {
t.Fatalf("invalid value escaped filter: %d %v", total, err)
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Status: "denied' OR 1=1 --"})
if err != nil || res.Total != 0 || len(res.Items) != 0 {
t.Fatalf("invalid value escaped filter: %d %v", res.Total, err)
}
// A rule's persisted source survives deletion of its associated rule.
_, err = d.Exec(`UPDATE intercept_pending SET decision_source='rule' WHERE task_id=$1 AND rule_id=$2`, scope, rule.ID)
@@ -131,11 +135,11 @@ func TestInterceptApprovalFilters(t *testing.T) {
if err = d.DeleteInterceptRule(rule.ID); err != nil {
t.Fatal(err)
}
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 100, InterceptApprovalFilter{DecisionSource: "rule"})
if err != nil || total != 12 {
t.Fatalf("deleted-rule source count=%d err=%v", total, err)
res, err = d.ListTaskInterceptsPage(scope, 1, 100, InterceptApprovalFilter{DecisionSource: "rule"})
if err != nil || res.Total != 12 {
t.Fatalf("deleted-rule source count=%d err=%v", res.Total, err)
}
for _, r := range rows {
for _, r := range res.Items {
if r.RuleID != nil || r.DecisionSource != "rule" {
t.Fatal("deleted rule lost its source")
}
@@ -146,22 +150,98 @@ func TestInterceptApprovalFilters(t *testing.T) {
if err != nil {
t.Fatal(err)
}
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "example.test"})
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
t.Fatalf("snapshot search total=%d rows=%d err=%v", total, len(rows), err)
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "example.test"})
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
t.Fatalf("snapshot search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
}
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "100%"})
if err != nil || total != 1 || len(rows) != 1 {
t.Fatalf("literal percent search total=%d rows=%d err=%v", total, len(rows), err)
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "100%"})
if err != nil || res.Total != 1 || len(res.Items) != 1 {
t.Fatalf("literal percent search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
}
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "#" + strconv.FormatInt(searchID, 10)})
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
t.Fatalf("id search total=%d rows=%d err=%v", total, len(rows), err)
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{Search: "#" + strconv.FormatInt(searchID, 10)})
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
t.Fatalf("id search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
}
rows, total, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{
res, err = d.ListTaskInterceptsPage(scope, 1, 20, InterceptApprovalFilter{
Search: "example.test", CreatedFrom: "2099-01-01", CreatedTo: "2099-01-01",
})
if err != nil || total != 1 || len(rows) != 1 || rows[0].ID != searchID {
t.Fatalf("date search total=%d rows=%d err=%v", total, len(rows), err)
if err != nil || res.Total != 1 || len(res.Items) != 1 || res.Items[0].ID != searchID {
t.Fatalf("date search total=%d rows=%d err=%v", res.Total, len(res.Items), err)
}
}
func TestInterceptPendingSummaryAndBoundedCount(t *testing.T) {
d, err := Open(testDSN(t))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = d.Close() })
scope := "approval-summary-" + t.Name()
other := scope + "-other"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id IN ($1,$2)`, scope, other) })
baseCount, err := d.CountPendingIntercepts()
if err != nil {
t.Fatal(err)
}
for _, agent := range []string{"mainagent", "work#1 · #101", "work#1 · #101", "planner"} {
if _, err := d.CreateInterceptPending(0, 0, scope, agent, "Bash", []byte(`{"command":"id"}`), "ask"); err != nil {
t.Fatal(err)
}
}
if _, err := d.CreateInterceptPending(0, 0, other, "mainagent", "Bash", []byte(`{"command":"id"}`), "ask"); err != nil {
t.Fatal(err)
}
for range 8 {
if _, err := d.CreateDecidedIntercept(0, 0, scope, "work#2 · #202", "Bash", []byte(`{"command":"ls"}`), "allowed", "ok"); err != nil {
t.Fatal(err)
}
}
globalCount, err := d.CountPendingIntercepts()
if err != nil || globalCount != baseCount+5 {
t.Fatalf("CountPendingIntercepts=%d want=%d err=%v", globalCount, baseCount+5, err)
}
summary, err := d.TaskPendingInterceptSummary(scope)
if err != nil {
t.Fatal(err)
}
wantAgents := []string{"mainagent", "planner", "work#1 · #101"}
if summary.Count != 4 || !slices.Equal(summary.AgentNames, wantAgents) {
t.Fatalf("TaskPendingInterceptSummary=%+v want count=4 agents=%v", summary, wantAgents)
}
taskPending, err := d.ListPendingInterceptsByTask(scope)
if err != nil || len(taskPending) != 4 {
t.Fatalf("ListPendingInterceptsByTask len=%d err=%v", len(taskPending), err)
}
limited, err := d.ListTaskInterceptsLimit(scope, 5)
if err != nil || len(limited) != 5 {
t.Fatalf("ListTaskInterceptsLimit len=%d err=%v", len(limited), err)
}
// Exercise bounded count cap and unfiltered approximate estimate without
// inserting tens of thousands of rows.
prevCap := interceptExactCountCap
interceptExactCountCap = 5
t.Cleanup(func() { interceptExactCountCap = prevCap })
capped, err := d.ListTaskInterceptsPage(scope, 1, 3, InterceptApprovalFilter{})
if err != nil {
t.Fatal(err)
}
if len(capped.Items) != 3 || !capped.HasMore || !capped.TotalApproximate || !capped.TotalCapped || capped.Total != 5 {
t.Fatalf("capped task page=%+v", capped)
}
if _, err := d.Exec(`ANALYZE intercept_pending`); err != nil {
t.Fatal(err)
}
approx, err := d.ListAllInterceptsPage(1, 3, InterceptApprovalFilter{})
if err != nil {
t.Fatal(err)
}
if len(approx.Items) != 3 || !approx.HasMore || !approx.TotalApproximate || approx.TotalCapped || approx.Total < 13 {
t.Fatalf("unfiltered approximate page=%+v", approx)
}
}
+4 -3
View File
@@ -1146,6 +1146,10 @@ CREATE TABLE IF NOT EXISTS intercept_pending (
CREATE INDEX IF NOT EXISTS idx_intercept_pending_status ON intercept_pending(status, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_intercept_pending_task ON intercept_pending(task_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_intercept_pending_created ON intercept_pending(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_intercept_pending_pending_task
ON intercept_pending(task_id, created_at DESC)
INCLUDE (agent_name)
WHERE status = 'pending';
-- 补旧库:reason 列(已发版,加列要带 IF NOT EXISTS)。
ALTER TABLE intercept_pending ADD COLUMN IF NOT EXISTS reason TEXT NOT NULL DEFAULT '';
-- Detail payloads are lazy-loaded; NULL preserves the meaning of legacy history.
@@ -1181,15 +1185,12 @@ CREATE TABLE IF NOT EXISTS findings (
-- 漏洞详细报告(Markdown);默认空,仅详情页读取/展示,不进列表接口以免 payload 膨胀。
report TEXT NOT NULL DEFAULT '',
report_conversation_id BIGINT REFERENCES conversations(id) ON DELETE SET NULL,
-- 人工备注;默认空,供漏洞详情页与列表记录复核/排查备忘。
remark TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
ALTER TABLE findings ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'pending';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT '';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report TEXT NOT NULL DEFAULT '';
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report_conversation_id BIGINT REFERENCES conversations(id) ON DELETE SET NULL;
ALTER TABLE findings ADD COLUMN IF NOT EXISTS remark TEXT NOT NULL DEFAULT '';
CREATE INDEX IF NOT EXISTS idx_findings_task ON findings(task_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_findings_time ON findings(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_findings_status ON findings(status, created_at DESC);
+1 -8
View File
@@ -79,9 +79,6 @@ func FindingsMarkdown(fs []*db.DBFinding, generatedAt time.Time) string {
if s := strings.TrimSpace(f.Summary); s != "" {
fmt.Fprintf(&b, "%s\n\n", s)
}
if rm := strings.TrimSpace(f.Remark); rm != "" {
fmt.Fprintf(&b, "**备注:**\n\n%s\n\n", rm)
}
if e := strings.TrimSpace(f.Evidence); e != "" {
fmt.Fprintf(&b, "**证据:**\n\n```\n%s\n```\n\n", e)
}
@@ -113,9 +110,6 @@ func SingleFindingMarkdown(f *db.DBFinding, generatedAt time.Time) string {
if s := strings.TrimSpace(f.Summary); s != "" {
fmt.Fprintf(&b, "## 概述\n\n%s\n\n", s)
}
if rm := strings.TrimSpace(f.Remark); rm != "" {
fmt.Fprintf(&b, "## 备注\n\n%s\n\n", rm)
}
if e := strings.TrimSpace(f.Evidence); e != "" {
fmt.Fprintf(&b, "## 证据\n\n```\n%s\n```\n\n", e)
}
@@ -161,7 +155,7 @@ func FindingsCSV(fs []*db.DBFinding) []byte {
var buf bytes.Buffer
buf.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
w := csv.NewWriter(&buf)
_ = w.Write([]string{"ID", "名称", "类别", "严重等级", "状态", "所属任务", "发现时间", "概述", "备注", "流量证据数量", "流量证据ID"})
_ = w.Write([]string{"ID", "名称", "类别", "严重等级", "状态", "所属任务", "发现时间", "概述", "流量证据数量", "流量证据ID"})
for _, f := range items {
id := fmt.Sprintf("%d", f.ID)
if f.ExportCaseID > 0 {
@@ -176,7 +170,6 @@ func FindingsCSV(fs []*db.DBFinding) []byte {
f.TaskDescription,
f.CreatedAt.Format("2006-01-02 15:04:05"),
strings.TrimSpace(f.Summary),
strings.TrimSpace(f.Remark),
fmt.Sprint(len(f.TrafficBindings)), findingTrafficIDs(f),
})
}
-4
View File
@@ -364,7 +364,6 @@ type FindingDTO struct {
Status string `json:"status"` // pending | in_progress | confirmed | resolved | fixed | false_positive | ignored | duplicate | risk_accepted
Summary string `json:"summary"`
Evidence string `json:"evidence"`
Remark string `json:"remark,omitempty"` // 人工备注
Report string `json:"report,omitempty"` // 详细报告(Markdown);仅详情接口返回,列表为空
ReportConversationID *int64 `json:"report_conversation_id,omitempty"`
@@ -465,8 +464,6 @@ func findingDTOsForOwner(taskID, description string, in []*db.Node, meta map[int
if m, ok := meta[n.ID]; ok {
d.FindingID = i64s(m.ID)
d.Status = m.Status
d.Remark = m.Remark
d.Evidence = m.Evidence
d.TrafficCount = m.TrafficCount
d.Assets = findingAssetDTOs(m.AssetIDs, assets)
}
@@ -505,7 +502,6 @@ func findingFromDB(f *db.DBFinding, assets map[int64]*db.Asset) FindingDTO {
Status: status,
Summary: f.Summary,
Evidence: f.Evidence,
Remark: f.Remark,
Report: f.Report,
ReportConversationID: f.ReportConversationID,
TS: rfc3339(f.CreatedAt),
-134
View File
@@ -1,134 +0,0 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/report"
)
func TestReportExportsIncludeFindingRemark(t *testing.T) {
now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
f := &db.DBFinding{
ID: 42,
Name: "后台越权导出",
VulnClass: "IDOR",
Severity: db.SeverityHigh,
Status: db.FindingConfirmed,
Summary: "普通用户可导出管理员报表",
Remark: "已与业务确认,本周五前修复",
Evidence: "GET /api/export?id=1 HTTP/1.1",
CreatedAt: now,
}
combined := report.FindingsMarkdown([]*db.DBFinding{f}, now)
if !strings.Contains(combined, "**备注:**\n\n已与业务确认,本周五前修复") {
t.Fatalf("combined markdown missing remark:\n%s", combined)
}
single := report.SingleFindingMarkdown(f, now)
if !strings.Contains(single, "## 备注\n\n已与业务确认,本周五前修复") {
t.Fatalf("single markdown missing remark:\n%s", single)
}
csvOut := string(report.FindingsCSV([]*db.DBFinding{f}))
if !strings.Contains(csvOut, "备注") || !strings.Contains(csvOut, "已与业务确认,本周五前修复") {
t.Fatalf("csv missing remark:\n%s", csvOut)
}
}
func TestPatchFindingManualEditAndRemark(t *testing.T) {
dsn, _, err := db.DSN()
if err != nil {
t.Skip("test postgres not configured")
}
pg, err := db.Open(dsn)
if err != nil {
t.Skipf("postgres unavailable (%v) — skipping", err)
}
t.Cleanup(func() { pg.Close() })
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
s := &Server{
ctx: ctx,
m: &Manager{pg: pg, dir: t.TempDir(), tasks: map[string]*Task{}},
}
vc := fmt.Sprintf("__test_patch_finding_%d__", time.Now().UnixNano())
fid, err := pg.AddFinding(0, 0, vc, "原始标题", db.SeverityMedium, "原始摘要", "原始证据", "worker", nil)
if err != nil {
t.Fatalf("AddFinding: %v", err)
}
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM findings WHERE id=$1`, fid) })
patch := func(id string, payload string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPatch, "/api/exploration/findings/"+id, bytes.NewBufferString(payload))
req.SetPathValue("id", id)
rec := httptest.NewRecorder()
s.patchFinding(rec, req)
return rec
}
idStr := fmt.Sprintf("%d", fid)
// Empty payload must return 400.
if w := patch(idStr, `{}`); w.Code != http.StatusBadRequest {
t.Fatalf("empty patch: want 400 got %d %s", w.Code, w.Body.String())
}
// Over-limit remark must return 400 and must NOT partially mutate name.
tooLong := strings.Repeat("注", db.MaxFindingRemarkRunes+1)
badBody, _ := json.Marshal(map[string]string{"name": "不应生效", "remark": tooLong})
if w := patch(idStr, string(badBody)); w.Code != http.StatusBadRequest {
t.Fatalf("over-limit remark: want 400 got %d %s", w.Code, w.Body.String())
}
before, _ := pg.GetFinding(fid)
if before.Name != "原始标题" || before.Remark != "" {
t.Fatalf("validation failure mutated row: %+v", before)
}
// Edit all fields at once.
fullBody, _ := json.Marshal(map[string]string{
"name": "手工修改后的标题",
"vulnclass": vc + "_edited",
"severity": db.SeverityCritical,
"status": db.FindingConfirmed,
"summary": "手工修改后的摘要",
"evidence": " indented evidence line\nline 2",
"report": "## 手工报告\n\n细节说明",
"remark": " 需要复核支付接口权限 ",
})
w := patch(idStr, string(fullBody))
if w.Code != http.StatusOK {
t.Fatalf("full patch: want 200 got %d %s", w.Code, w.Body.String())
}
var dto FindingDTO
if err := json.Unmarshal(w.Body.Bytes(), &dto); err != nil {
t.Fatalf("decode dto: %v", err)
}
if dto.Name != "手工修改后的标题" || dto.VulnClass != vc+"_edited" || dto.Severity != db.SeverityCritical ||
dto.Status != db.FindingConfirmed || dto.Summary != "手工修改后的摘要" ||
dto.Evidence != " indented evidence line\nline 2" || dto.Report != "## 手工报告\n\n细节说明" ||
dto.Remark != "需要复核支付接口权限" {
t.Fatalf("unexpected patched dto: %+v", dto)
}
// Clearing remark to empty string persists cleanly.
w = patch(idStr, `{"remark":" "}`)
if w.Code != http.StatusOK {
t.Fatalf("clear remark: want 200 got %d %s", w.Code, w.Body.String())
}
var cleared FindingDTO
if err := json.Unmarshal(w.Body.Bytes(), &cleared); err != nil {
t.Fatalf("decode cleared dto: %v", err)
}
if cleared.Remark != "" || cleared.Name != "手工修改后的标题" {
t.Fatalf("unexpected cleared dto: %+v", cleared)
}
}
+59 -9
View File
@@ -258,7 +258,16 @@ func (s *Server) interceptListPending(w http.ResponseWriter, r *http.Request) {
if pg == nil {
return
}
pending, err := pg.ListPendingIntercepts()
taskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
var (
pending []db.InterceptPending
err error
)
if taskID != "" {
pending, err = pg.ListPendingInterceptsByTask(taskID)
} else {
pending, err = pg.ListPendingIntercepts()
}
if err != nil {
writeErr(w, 500, err.Error())
return
@@ -269,6 +278,32 @@ func (s *Server) interceptListPending(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"pending": pending})
}
func (s *Server) interceptPendingSummary(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
return
}
taskID := strings.TrimSpace(r.URL.Query().Get("task_id"))
if taskID == "" {
count, err := pg.CountPendingIntercepts()
if err != nil {
writeErr(w, 500, err.Error())
return
}
writeJSON(w, 200, map[string]any{"count": count})
return
}
summary, err := pg.TaskPendingInterceptSummary(taskID)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if summary.AgentNames == nil {
summary.AgentNames = []string{}
}
writeJSON(w, 200, summary)
}
func (s *Server) interceptGetOne(w http.ResponseWriter, r *http.Request) {
pg := s.pg(w)
if pg == nil {
@@ -308,7 +343,7 @@ func (s *Server) interceptListTaskItems(w http.ResponseWriter, r *http.Request)
return
}
if q.Get("page") == "" && q.Get("size") == "" && filter == (db.InterceptApprovalFilter{}) {
items, err := pg.ListTaskIntercepts(taskID)
items, err := pg.ListTaskInterceptsLimit(taskID, 200)
if err != nil {
writeErr(w, 500, err.Error())
return
@@ -320,15 +355,12 @@ func (s *Server) interceptListTaskItems(w http.ResponseWriter, r *http.Request)
return
}
page, size := interceptPageParams(q)
items, total, err := pg.ListTaskInterceptsPage(taskID, page, size, filter)
res, err := pg.ListTaskInterceptsPage(taskID, page, size, filter)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if items == nil {
items = []db.InterceptApprovalRow{}
}
writeJSON(w, 200, map[string]any{"items": items, "total": total, "page": page, "page_size": size})
writeInterceptPage(w, res, page, size)
}
func (s *Server) interceptHistory(w http.ResponseWriter, r *http.Request) {
@@ -355,15 +387,33 @@ func (s *Server) interceptHistory(w http.ResponseWriter, r *http.Request) {
return
}
page, size := interceptPageParams(q)
items, total, err := pg.ListAllInterceptsPage(page, size, filter)
res, err := pg.ListAllInterceptsPage(page, size, filter)
if err != nil {
writeErr(w, 500, err.Error())
return
}
writeInterceptPage(w, res, page, size)
}
func writeInterceptPage(w http.ResponseWriter, res db.InterceptApprovalPage, page, size int) {
items := res.Items
if items == nil {
items = []db.InterceptApprovalRow{}
}
writeJSON(w, 200, map[string]any{"items": items, "total": total, "page": page, "page_size": size})
payload := map[string]any{
"items": items,
"total": res.Total,
"has_more": res.HasMore,
"page": page,
"page_size": size,
}
if res.TotalApproximate {
payload["total_approximate"] = true
}
if res.TotalCapped {
payload["total_capped"] = true
}
writeJSON(w, 200, payload)
}
func interceptFilterParams(q url.Values) (db.InterceptApprovalFilter, error) {
+48 -1
View File
@@ -63,10 +63,11 @@ func TestInterceptFilterHTTP(t *testing.T) {
}
scope := "approval-http-filter"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id IN ($1,$2)`, scope, scope+"-other") })
_, baseline, err := d.ListAllInterceptsPage(1, 20, db.InterceptApprovalFilter{Status: "denied", DecisionSource: "model"})
basePage, err := d.ListAllInterceptsPage(1, 20, db.InterceptApprovalFilter{Status: "denied", DecisionSource: "model"})
if err != nil {
t.Fatal(err)
}
baseline := basePage.Total
for _, state := range []string{"pending", "allowed", "denied", "timeout"} {
if _, err := d.CreateDecidedIntercept(0, 0, scope, "test", "Bash", []byte(`{}`), state, "[模型] fixture"); err != nil {
t.Fatal(err)
@@ -143,4 +144,50 @@ func TestInterceptFilterHTTP(t *testing.T) {
t.Fatalf("%s: %d %s", tc.query, rec.Code, rec.Body.String())
}
}
// Pending summary endpoints must require auth and return lightweight counts
// without historical rows.
if rec := do("/api/intercept/pending/summary", false); rec.Code != 401 {
t.Fatalf("unprotected summary: %d", rec.Code)
}
rec := do("/api/intercept/pending/summary", true)
var globalSummary struct {
Count int `json:"count"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &globalSummary) != nil || globalSummary.Count < 1 {
t.Fatalf("global summary: %d %s", rec.Code, rec.Body.String())
}
rec = do("/api/intercept/pending/summary?task_id="+scope, true)
var taskSummary struct {
Count int `json:"count"`
AgentNames []string `json:"agent_names"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &taskSummary) != nil || taskSummary.Count != 1 || len(taskSummary.AgentNames) != 1 || taskSummary.AgentNames[0] != "test" {
t.Fatalf("task summary: %d %s", rec.Code, rec.Body.String())
}
rec = do("/api/intercept/pending?task_id="+scope, true)
var taskPending struct {
Pending []db.InterceptPending `json:"pending"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &taskPending) != nil || len(taskPending.Pending) != 1 {
t.Fatalf("task pending: %d %s", rec.Code, rec.Body.String())
}
// Unpaginated task history must stay bounded so large tasks never dump full history.
bigScope := scope + "-cap"
t.Cleanup(func() { _, _ = d.Exec(`DELETE FROM intercept_pending WHERE task_id=$1`, bigScope) })
if _, err := d.Exec(`
INSERT INTO intercept_pending (task_id, agent_name, tool_name, tool_input, status, reason, decision_source)
SELECT $1, 'worker', 'Bash', '{}'::jsonb, 'allowed', 'ok', 'rule'
FROM generate_series(1, 205)`, bigScope); err != nil {
t.Fatal(err)
}
rec = do("/api/intercept/task/"+bigScope, true)
var cappedTask struct {
Items []db.InterceptApprovalRow `json:"items"`
Total int `json:"total"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &cappedTask) != nil || len(cappedTask.Items) != 200 || cappedTask.Total != 200 {
t.Fatalf("unpaginated task cap: %d len=%d total=%d", rec.Code, len(cappedTask.Items), cappedTask.Total)
}
}
+16 -91
View File
@@ -18,7 +18,6 @@ import (
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/Autumn-27/artex/agent"
"github.com/Autumn-27/artex/db"
@@ -1153,6 +1152,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /api/asset-intercept/rules/{id}/toggle", s.assetInterceptToggleRule)
mux.HandleFunc("GET /api/intercept/pending", s.interceptListPending)
mux.HandleFunc("GET /api/intercept/pending/summary", s.interceptPendingSummary)
mux.HandleFunc("GET /api/intercept/pending/{id}", s.interceptGetOne)
mux.HandleFunc("POST /api/intercept/pending/{id}/decide", s.interceptDecide)
mux.HandleFunc("GET /api/intercept/history", s.interceptHistory)
@@ -2621,10 +2621,10 @@ func (s *Server) findingLineage(w http.ResponseWriter, r *http.Request) {
writeJSON(w, 200, map[string]any{"nodes": taskNodeDTOs(nodes), "edges": edgeDTOs(edges)})
}
// patchFinding partially updates a finding: any subset of {status, severity, name, vulnclass,
// summary, evidence, report, remark}. The id is the standalone findings-table id (DTO finding_id).
// Core text fields are mirrored onto the originating exploration node so the per-task view stays
// in sync. Returns the updated finding DTO.
// patchFinding partially updates a finding: any subset of {status, severity}.
// The id is the standalone findings-table id (DTO finding_id). Severity edits are
// mirrored onto the originating exploration node so the per-task view stays in
// sync. Returns the updated finding DTO.
func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
id := int64(atoiDefault(r.PathValue("id"), 0))
if id <= 0 {
@@ -2636,38 +2636,20 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
Severity *string `json:"severity"`
Name *string `json:"name"`
VulnClass *string `json:"vulnclass"`
Summary *string `json:"summary"`
Evidence *string `json:"evidence"`
Report *string `json:"report"`
Remark *string `json:"remark"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeErr(w, 400, "bad json: "+err.Error())
return
}
if body.Status == nil && body.Severity == nil && body.Name == nil && body.VulnClass == nil &&
body.Summary == nil && body.Evidence == nil && body.Report == nil && body.Remark == nil {
writeErr(w, 400, "nothing to update: provide status/severity/name/vulnclass/summary/evidence/report/remark")
if body.Status == nil && body.Severity == nil && body.Name == nil && body.VulnClass == nil {
writeErr(w, 400, "nothing to update: provide status/severity/name/vulnclass")
return
}
// Validate all fields before mutating so invalid input never leaves partial writes.
if body.Status != nil && !db.ValidFindingStatus(*body.Status) {
writeErr(w, 400, "bad status: "+*body.Status)
return
}
if body.Severity != nil && !db.ValidSeverity(*body.Severity) {
writeErr(w, 400, "bad severity: "+*body.Severity)
return
}
var remark string
if body.Remark != nil {
remark = strings.TrimSpace(*body.Remark)
if utf8.RuneCountInString(remark) > db.MaxFindingRemarkRunes {
writeErr(w, 400, fmt.Sprintf("备注最多 %d 个字符", db.MaxFindingRemarkRunes))
return
}
}
if body.Status != nil {
if !db.ValidFindingStatus(*body.Status) {
writeErr(w, 400, "bad status: "+*body.Status)
return
}
// 走带通知的版本:状态更新与「状态变更推送事件」在同一事务里落库,
// 避免出现状态已改而推送事件丢失的窗口。事件登记失败不影响状态更新,
// 所以只记日志、不向调用方报错。
@@ -2685,6 +2667,10 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
}
}
if body.Severity != nil {
if !db.ValidSeverity(*body.Severity) {
writeErr(w, 400, "bad severity: "+*body.Severity)
return
}
n, err := s.m.pg.SetFindingSeverity(id, *body.Severity)
if err != nil {
writeErr(w, 500, err.Error())
@@ -2717,58 +2703,6 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
return
}
}
if body.Summary != nil {
n, err := s.m.pg.SetFindingSummary(id, strings.TrimSpace(*body.Summary))
if err != nil {
writeErr(w, 500, err.Error())
return
}
if n == 0 {
writeErr(w, 404, "finding not found")
return
}
}
if body.Evidence != nil {
ev := *body.Evidence
if strings.TrimSpace(ev) == "" {
ev = ""
}
n, err := s.m.pg.SetFindingEvidence(id, ev)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if n == 0 {
writeErr(w, 404, "finding not found")
return
}
}
if body.Report != nil {
rep := *body.Report
if strings.TrimSpace(rep) == "" {
rep = ""
}
n, err := s.m.pg.SetFindingReport(id, rep)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if n == 0 {
writeErr(w, 404, "finding not found")
return
}
}
if body.Remark != nil {
n, err := s.m.pg.SetFindingRemark(id, remark)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if n == 0 {
writeErr(w, 404, "finding not found")
return
}
}
f, err := s.m.pg.GetFinding(id)
if err != nil {
writeErr(w, 500, err.Error())
@@ -2778,16 +2712,7 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
writeErr(w, 404, "finding not found")
return
}
dto := findingFromDB(f, s.resolveAssetIDs(f.AssetIDs))
cid, err := s.m.pg.FindingCaseID(f.ID)
if err != nil {
writeErr(w, 500, err.Error())
return
}
if cid > 0 {
dto.CaseID = i64s(cid)
}
writeJSON(w, 200, dto)
writeJSON(w, 200, findingFromDB(f, s.resolveAssetIDs(f.AssetIDs)))
}
// deleteFinding removes a finding (findings row + originating exploration node).
@@ -161,21 +161,36 @@ function NavItem({ item, isItemActive, isSubItemActive, isSubmenuOpen }: NavItem
);
}
// InterceptPendingBadge polls /api/intercept/pending every 5 s and shows a red
// count badge when there are unresolved approval requests.
// InterceptPendingBadge polls /api/intercept/pending/summary every 5 s (while
// visible) and shows an amber count badge when there are unresolved requests.
function InterceptPendingBadge() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
let live = true;
let inFlight = false;
async function poll() {
if (inFlight || document.hidden) return;
inFlight = true;
try {
const list = await api.interceptPending();
if (live) setCount(list.length);
} catch { /* ignore */ }
const summary = await api.interceptPendingSummary();
if (live) setCount(summary.count);
} catch {
/* ignore */
} finally {
inFlight = false;
}
}
poll();
const t = setInterval(poll, 5000);
return () => { live = false; clearInterval(t); };
void poll();
const t = setInterval(() => void poll(), 5000);
const onVisible = () => {
if (!document.hidden) void poll();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
live = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
};
}, []);
if (count === 0) return null;
return (
@@ -12,7 +12,6 @@ import {
FolderOpenIcon,
RotateCcwIcon,
ShieldAlertIcon,
StickyNoteIcon,
Trash2Icon,
} from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -68,12 +67,11 @@ export const FINDING_STATUSES: FindingStatus[] = [
export const UNASSIGNED_TASK = "__unassigned__";
// 行内编辑缓冲:当前展开行的名称/类别/严重等级/备注。
// 行内编辑缓冲:当前展开行的名称/类别/严重等级。
export interface FindingEdit {
name: string;
vulnclass: string;
severity: Severity;
remark: string;
}
export type FindingReport = { status: "loading" | "done" | "error"; text: string };
@@ -289,15 +287,6 @@ export function FindingsTable({
</span>
)}
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
{f.remark ? (
<span
className="inline-flex min-w-0 items-center gap-1 truncate text-xs text-amber-700 dark:text-amber-400"
title={f.remark}
>
<StickyNoteIcon className="size-3 shrink-0" />
<span className="truncate">{f.remark}</span>
</span>
) : null}
{matchedIds && !matchedIds.includes(Number(f.finding_id)) ? (
<Badge variant="outline" className="w-fit">
{ui("screen.7852ff0b787df8")}
@@ -446,14 +435,6 @@ export function FindingsTable({
</SelectContent>
</Select>
</div>
<div className="flex min-w-[14rem] flex-1 flex-col gap-1">
<Label className="text-xs text-muted-foreground">{ui("findingDetail.remark")}</Label>
<Input
value={edit.remark}
onChange={(e) => onEditChange((s) => (s ? { ...s, remark: e.target.value } : s))}
placeholder={ui("findingDetail.remarkPlaceholder")}
/>
</div>
<Button size="sm" disabled={saving} onClick={() => onSave(f)}>
{saving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
</Button>
@@ -1,282 +0,0 @@
"use client";
import * as React from "react";
import { Loader2Icon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { taskError } from "@/i18n/task-runtime";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { useUITranslation } from "@/i18n/use-ui-translation";
import { api } from "@/lib/api";
import { statusMeta } from "@/lib/status";
import { type Finding, type FindingStatus, MAX_FINDING_REMARK_RUNES, type Severity } from "@/lib/types";
import { cn } from "@/lib/utils";
const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
const FINDING_STATUSES: FindingStatus[] = [
"pending",
"in_progress",
"confirmed",
"resolved",
"fixed",
"false_positive",
"ignored",
"duplicate",
"risk_accepted",
];
type FindingDraft = {
name: string;
vulnclass: string;
severity: Severity;
status: FindingStatus;
summary: string;
evidence: string;
report: string;
remark: string;
};
function draftFromFinding(f: Finding): FindingDraft {
return {
name: f.name ?? "",
vulnclass: f.vulnclass,
severity: f.severity,
status: f.status,
summary: f.summary,
evidence: f.evidence,
report: f.report ?? "",
remark: f.remark ?? "",
};
}
export function FindingEditDialog({
finding,
open,
onOpenChange,
onSaved,
}: {
finding: Finding;
open: boolean;
onOpenChange: (open: boolean) => void;
onSaved: (updated: Finding) => void;
}) {
const { ui, liveUI } = useUITranslation();
const { t, liveT } = useLiveTranslation();
const [draft, setDraft] = React.useState<FindingDraft>(() => draftFromFinding(finding));
const [saving, setSaving] = React.useState(false);
React.useEffect(() => {
if (open) {
setDraft(draftFromFinding(finding));
}
}, [open, finding]);
const trimmedRemark = draft.remark.trim();
const remarkRunes = Array.from(trimmedRemark).length;
const remarkTooLong = remarkRunes > MAX_FINDING_REMARK_RUNES;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (saving || remarkTooLong) return;
const patchPayload: Parameters<typeof api.updateFinding>[1] = {};
const nextName = draft.name.trim();
const nextVulnClass = draft.vulnclass.trim();
const nextSummary = draft.summary.trim();
const nextEvidence = draft.evidence.trim() ? draft.evidence : "";
const nextReport = draft.report.trim() ? draft.report : "";
if (nextName !== (finding.name ?? "").trim()) patchPayload.name = nextName;
if (nextVulnClass !== finding.vulnclass.trim()) patchPayload.vulnclass = nextVulnClass;
if (draft.severity !== finding.severity) patchPayload.severity = draft.severity;
if (draft.status !== finding.status) patchPayload.status = draft.status;
if (nextSummary !== finding.summary.trim()) patchPayload.summary = nextSummary;
if (nextEvidence !== finding.evidence) patchPayload.evidence = nextEvidence;
if (nextReport !== (finding.report ?? "")) patchPayload.report = nextReport;
if (trimmedRemark !== (finding.remark ?? "").trim()) patchPayload.remark = trimmedRemark;
if (Object.keys(patchPayload).length === 0) {
onOpenChange(false);
return;
}
setSaving(true);
try {
const updated = await api.updateFinding(finding.id, patchPayload);
onSaved(updated);
toast.success(liveUI("findingDetail.findingSaved"));
onOpenChange(false);
} catch (err) {
toast.error(liveUI("screen.20e1b0f2590bc7", { v0: taskError(err, liveT) }));
} finally {
setSaving(false);
}
};
return (
<Dialog open={open} onOpenChange={(next) => !saving && onOpenChange(next)}>
<DialogContent className="flex max-h-[90dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">
<DialogHeader className="border-b px-6 py-4">
<DialogTitle>{ui("findingDetail.editTitle")}</DialogTitle>
<DialogDescription>{ui("findingDetail.editDescription")}</DialogDescription>
</DialogHeader>
<form onSubmit={(e) => void handleSubmit(e)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-6 py-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="finding-edit-name">{ui("findingDetail.nameLabel")}</Label>
<Input
id="finding-edit-name"
autoFocus
value={draft.name}
onChange={(e) => setDraft((cur) => ({ ...cur, name: e.target.value }))}
placeholder={ui("screen.e4ca1c94d239bd")}
disabled={saving}
/>
</div>
<div className="grid gap-3 sm:grid-cols-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="finding-edit-vulnclass">{ui("screen.5600494fad709b")}</Label>
<Input
id="finding-edit-vulnclass"
value={draft.vulnclass}
onChange={(e) => setDraft((cur) => ({ ...cur, vulnclass: e.target.value }))}
placeholder={ui("screen.18f8e077cc27a6")}
disabled={saving}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label>{ui("screen.2e21284b7229e6")}</Label>
<Select
value={draft.severity}
onValueChange={(v) => setDraft((cur) => ({ ...cur, severity: v as Severity }))}
disabled={saving}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{SEVERITIES.map((sv) => (
<SelectItem key={sv} value={sv}>
{statusMeta("severity", sv, t).label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
<div className="flex flex-col gap-1.5">
<Label>{ui("screen.d5e74de3449e74")}</Label>
<Select
value={draft.status}
onValueChange={(v) => setDraft((cur) => ({ ...cur, status: v as FindingStatus }))}
disabled={saving}
>
<SelectTrigger className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{FINDING_STATUSES.map((st) => (
<SelectItem key={st} value={st}>
{statusMeta("finding", st, t).label}
</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
</div>
</div>
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-2">
<Label htmlFor="finding-edit-remark">{ui("findingDetail.remark")}</Label>
<span
className={cn("text-xs tabular-nums", remarkTooLong ? "text-destructive" : "text-muted-foreground")}
>
{remarkRunes} / {MAX_FINDING_REMARK_RUNES}
</span>
</div>
<Textarea
id="finding-edit-remark"
rows={3}
value={draft.remark}
onChange={(e) => setDraft((cur) => ({ ...cur, remark: e.target.value }))}
placeholder={ui("findingDetail.remarkPlaceholder")}
aria-invalid={remarkTooLong}
disabled={saving}
/>
{remarkTooLong ? (
<p role="alert" className="text-destructive text-xs">
{ui("findingDetail.remarkTooLong", { max: MAX_FINDING_REMARK_RUNES })}
</p>
) : null}
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="finding-edit-summary">{ui("screen.21c04b2eeeb431")}</Label>
<Textarea
id="finding-edit-summary"
rows={3}
value={draft.summary}
onChange={(e) => setDraft((cur) => ({ ...cur, summary: e.target.value }))}
placeholder={ui("findingDetail.summaryPlaceholder")}
disabled={saving}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="finding-edit-evidence">{ui("screen.c13ed981c63391")}</Label>
<Textarea
id="finding-edit-evidence"
rows={4}
className="font-mono text-xs"
value={draft.evidence}
onChange={(e) => setDraft((cur) => ({ ...cur, evidence: e.target.value }))}
placeholder={ui("findingDetail.evidencePlaceholder")}
disabled={saving}
/>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="finding-edit-report">{ui("screen.566e5ab4ab0638")}</Label>
<Textarea
id="finding-edit-report"
rows={6}
className="font-mono text-xs"
value={draft.report}
onChange={(e) => setDraft((cur) => ({ ...cur, report: e.target.value }))}
placeholder={ui("findingDetail.reportPlaceholder")}
disabled={saving}
/>
</div>
</div>
<DialogFooter className="mx-0 mb-0 border-t px-6 py-3">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
{ui("common.cancel")}
</Button>
<Button type="submit" disabled={saving || remarkTooLong}>
{saving ? <Loader2Icon data-icon="inline-start" className="animate-spin" /> : null}
{saving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -4,16 +4,8 @@ import * as React from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import {
ArrowLeftIcon,
ArrowUpRightIcon,
BotIcon,
FileTextIcon,
Loader2Icon,
PencilIcon,
ShieldAlertIcon,
StickyNoteIcon,
} from "lucide-react";
import { ArrowLeftIcon, ArrowUpRightIcon, BotIcon, FileTextIcon, Loader2Icon, ShieldAlertIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
@@ -31,16 +23,11 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger } from "@
import { Separator } from "@/components/ui/separator";
import { SidebarTrigger } from "@/components/ui/sidebar";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { taskError } from "@/i18n/task-runtime";
import { useLiveTranslation } from "@/i18n/use-live-translation";
import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
import { api } from "@/lib/api";
import { statusMeta } from "@/lib/status";
import { type Finding, type FindingStatus, MAX_FINDING_REMARK_RUNES, type Severity } from "@/lib/types";
import { cn } from "@/lib/utils";
import type { Finding, FindingStatus, Severity } from "@/lib/types";
import { FindingEditDialog } from "./finding-edit-dialog";
import { FindingLineageView } from "./lineage";
const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
@@ -79,7 +66,7 @@ function FieldRow({ label, children }: { label: string; children: React.ReactNod
function FindingDetailInner() {
const { ui, liveUI } = useUITranslation();
const { t, liveT } = useLiveTranslation();
const { t } = useTranslation();
const searchParams = useSearchParams();
const id = searchParams.get("id") ?? "";
const contextTaskId = searchParams.get("context_task") ?? "";
@@ -90,10 +77,6 @@ function FindingDetailInner() {
const [reportGenerating, setReportGenerating] = React.useState(false);
const [autoChatOpen, setAutoChatOpen] = React.useState(false);
const [reportChatOpen, setReportChatOpen] = React.useState(false);
const [editOpen, setEditOpen] = React.useState(false);
const [remarkEditing, setRemarkEditing] = React.useState(false);
const [remarkDraft, setRemarkDraft] = React.useState("");
const [remarkSaving, setRemarkSaving] = React.useState(false);
const title = finding?.name || finding?.vulnclass || ui("screen.54b89f90127458");
const load = React.useCallback(() => {
@@ -111,12 +94,6 @@ function FindingDetailInner() {
load();
}, [load]);
React.useEffect(() => {
if (!remarkEditing) {
setRemarkDraft(finding?.remark ?? "");
}
}, [finding?.remark, remarkEditing]);
const changeSeverity = React.useCallback(
async (next: Severity) => {
if (!finding || finding.inherited || next === finding.severity) return;
@@ -168,43 +145,6 @@ function FindingDetailInner() {
}
}, [finding, id, load, reportGenerating, liveUI]);
const trimmedRemarkDraft = remarkDraft.trim();
const remarkRunes = Array.from(trimmedRemarkDraft).length;
const remarkTooLong = remarkRunes > MAX_FINDING_REMARK_RUNES;
const startRemarkEdit = React.useCallback(() => {
if (!finding || finding.inherited) return;
setRemarkDraft(finding.remark ?? "");
setRemarkEditing(true);
}, [finding]);
const cancelRemarkEdit = React.useCallback(() => {
if (remarkSaving) return;
setRemarkDraft(finding?.remark ?? "");
setRemarkEditing(false);
}, [finding?.remark, remarkSaving]);
const saveRemark = React.useCallback(async () => {
if (!finding || finding.inherited || remarkSaving || remarkTooLong) return;
const next = remarkDraft.trim();
if (next === (finding.remark ?? "").trim()) {
setRemarkEditing(false);
return;
}
setRemarkSaving(true);
try {
const updated = await api.updateFinding(id, { remark: next });
setFinding(updated);
setRemarkDraft(updated.remark ?? "");
setRemarkEditing(false);
toast.success(next ? liveUI("findingDetail.remarkSaved") : liveUI("findingDetail.remarkCleared"));
} catch (e) {
toast.error(liveUI("screen.20e1b0f2590bc7", { v0: taskError(e, liveT) }));
} finally {
setRemarkSaving(false);
}
}, [finding, id, liveT, liveUI, remarkDraft, remarkSaving, remarkTooLong]);
if (!finding) {
return (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
@@ -275,17 +215,6 @@ function FindingDetailInner() {
{ui("screen.552b1bc6b1d807")}
</Button>
) : null}
{!finding.inherited ? (
<Button
variant="outline"
size="sm"
onClick={() => setEditOpen(true)}
title={ui("findingDetail.editTitle")}
>
<PencilIcon data-icon="inline-start" />
{ui("findingDetail.editButton")}
</Button>
) : null}
{finding.inherited && finding.source_task_id && (
<Badge variant="outline">
{ui("screen.88b75b1fbea969")}
@@ -497,110 +426,6 @@ function FindingDetailInner() {
</FieldRow>
</CardContent>
</Card>
<Card className="h-fit">
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<CardTitle className="flex items-center gap-1.5 text-sm">
<StickyNoteIcon className="size-4 text-muted-foreground" />
{ui("findingDetail.remark")}
</CardTitle>
{!finding.inherited && !remarkEditing ? (
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 px-2 text-xs"
onClick={startRemarkEdit}
>
<PencilIcon data-icon="inline-start" className="size-3.5" />
{finding.remark ? ui("findingDetail.editRemark") : ui("findingDetail.addRemark")}
</Button>
) : null}
</CardHeader>
<CardContent>
{remarkEditing && !finding.inherited ? (
<div className="flex flex-col gap-2">
<Textarea
autoFocus
rows={4}
value={remarkDraft}
disabled={remarkSaving}
aria-label={ui("findingDetail.remark")}
aria-invalid={remarkTooLong}
placeholder={ui("findingDetail.remarkPlaceholder")}
onChange={(e) => setRemarkDraft(e.target.value)}
onKeyDown={(e) => {
if (e.nativeEvent.isComposing) return;
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void saveRemark();
} else if (e.key === "Escape") {
e.preventDefault();
cancelRemarkEdit();
}
}}
/>
<div className="flex items-center justify-between gap-2 text-xs">
<span className="text-muted-foreground">{ui("findingDetail.remarkHint")}</span>
<span
className={cn(
"shrink-0 tabular-nums",
remarkTooLong ? "text-destructive" : "text-muted-foreground",
)}
>
{remarkRunes} / {MAX_FINDING_REMARK_RUNES}
</span>
</div>
{remarkTooLong ? (
<p role="alert" className="text-xs text-destructive">
{ui("findingDetail.remarkTooLong", { max: MAX_FINDING_REMARK_RUNES })}
</p>
) : null}
<div className="flex justify-end gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={cancelRemarkEdit}
disabled={remarkSaving}
>
{ui("common.cancel")}
</Button>
<Button
type="button"
size="sm"
onClick={() => void saveRemark()}
disabled={remarkSaving || remarkTooLong}
>
{remarkSaving ? <Loader2Icon data-icon="inline-start" className="animate-spin" /> : null}
{remarkSaving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
</Button>
</div>
</div>
) : finding.remark ? (
finding.inherited ? (
<p className="text-sm leading-relaxed whitespace-pre-wrap break-words">{finding.remark}</p>
) : (
<button
type="button"
onClick={startRemarkEdit}
className="w-full rounded-md text-left text-sm leading-relaxed whitespace-pre-wrap break-words hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{finding.remark}
</button>
)
) : finding.inherited ? (
<p className="text-xs text-muted-foreground">{ui("findingDetail.remarkEmptyReadOnly")}</p>
) : (
<button
type="button"
onClick={startRemarkEdit}
className="w-full rounded-md border border-dashed px-3 py-2.5 text-left text-xs text-muted-foreground transition-colors hover:border-primary/40 hover:bg-muted/40 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
{ui("findingDetail.remarkEmpty")}
</button>
)}
</CardContent>
</Card>
<FindingRetestPanel
key={`retest:${id}`}
findingId={id}
@@ -629,17 +454,6 @@ function FindingDetailInner() {
open={reportChatOpen}
onOpenChange={setReportChatOpen}
/>
{!finding.inherited ? (
<FindingEditDialog
finding={finding}
open={editOpen}
onOpenChange={setEditOpen}
onSaved={(updated) => {
setFinding(updated);
if (!remarkEditing) setRemarkDraft(updated.remark ?? "");
}}
/>
) : null}
</>
);
}
@@ -745,7 +745,7 @@ export default function FindingsPage() {
setEdit(null);
return;
}
setEdit({ name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity, remark: f.remark ?? "" });
setEdit({ name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity });
if (!f.finding_id || reports[key]) return;
const fid = f.finding_id;
setReports((r) => ({ ...r, [key]: { status: "loading", text: "" } }));
@@ -767,18 +767,11 @@ export default function FindingsPage() {
name: edit.name.trim(),
vulnclass: edit.vulnclass.trim(),
severity: edit.severity,
remark: edit.remark.trim(),
});
setFindings((cur) =>
cur.map((x) =>
isSameFinding(x, f)
? {
...x,
name: updated.name,
vulnclass: updated.vulnclass,
severity: updated.severity,
remark: updated.remark,
}
? { ...x, name: updated.name, vulnclass: updated.vulnclass, severity: updated.severity }
: x,
),
);
@@ -3,14 +3,7 @@ import * as React from "react";
import Link from "next/link";
import {
ArrowDownIcon,
ArrowUpIcon,
ArrowUpRightIcon,
ChevronRightIcon,
SearchIcon,
StickyNoteIcon,
} from "lucide-react";
import { ArrowDownIcon, ArrowUpIcon, ArrowUpRightIcon, ChevronRightIcon, SearchIcon } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
@@ -87,15 +80,6 @@ function Row({
)}
</div>
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
{f.remark ? (
<span
className="inline-flex min-w-0 items-center gap-1 truncate text-xs text-amber-700 dark:text-amber-400"
title={f.remark}
>
<StickyNoteIcon className="size-3 shrink-0" />
<span className="truncate">{f.remark}</span>
</span>
) : null}
</div>
</button>
<Badge variant="outline">
@@ -59,7 +59,6 @@ import type {
Activity,
ChatAttachment,
IntentAsset,
InterceptApprovalRow,
Session,
SessionStatus,
SessionTokenUsage,
@@ -491,7 +490,17 @@ function WorkerAssetBadge({ assets }: { assets: IntentAsset[] }) {
);
}
export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string; requestedSession?: string }) {
const EMPTY_PENDING_AGENTS: string[] = [];
export function SessionsTab({
taskId,
requestedSession = "",
pendingAgentNames = EMPTY_PENDING_AGENTS,
}: {
taskId: string;
requestedSession?: string;
pendingAgentNames?: string[];
}) {
const { ui, liveUI } = useUITranslation();
const approvalFocus = useApprovalFocus({ taskId });
@@ -676,8 +685,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
const [taskTokens, setTaskTokens] = React.useState<TokenTotal | null>(null);
const [sessionTokens, setSessionTokens] = React.useState<Record<string, SessionTokenUsage>>({});
const [llmResolutions, setLLMResolutions] = React.useState<TaskLLMResolutions | null>(null);
// Pending intercept requests for this task — used to show warning icons on sessions.
const [pendingIntercepts, setPendingIntercepts] = React.useState<InterceptApprovalRow[]>([]);
// Refs backing SSE/loading without re-render churn.
const snapshotRef = React.useRef(0); // task-level snapshot cursor → SSE since=
@@ -885,25 +892,6 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
};
}, [taskId]);
React.useEffect(() => {
let alive = true;
const load = () =>
api
.interceptTask(taskId)
.then((rows) => {
if (alive) setPendingIntercepts(rows.filter((r) => r.status === "pending"));
})
.catch(() => {
// Polling is best-effort; the next interval retries automatically.
});
void load();
const t = setInterval(load, 5000);
return () => {
alive = false;
clearInterval(t);
};
}, [taskId]);
// Re-render on a timer so "streaming" liveness recomputes as activity goes stale.
const [, setTick] = React.useState(0);
React.useEffect(() => {
@@ -1225,16 +1213,16 @@ export function SessionsTab({ taskId, requestedSession = "" }: { taskId: string;
const hasPendingForSession = React.useCallback(
(s: Session): boolean => {
if (s.inherited) return false;
if (!pendingIntercepts.length) return false;
if (s.role === "mainagent") return pendingIntercepts.some((r) => r.agent_name === "mainagent");
if (s.role === "planner") return pendingIntercepts.some((r) => r.agent_name === "planner");
if (!pendingAgentNames.length) return false;
if (s.role === "mainagent") return pendingAgentNames.includes("mainagent");
if (s.role === "planner") return pendingAgentNames.includes("planner");
// Worker: extract intent ID from "work#N · #<intentID>"
return pendingIntercepts.some((r) => {
const m = r.agent_name.match(/·\s*#(\d+)$/);
return pendingAgentNames.some((agentName) => {
const m = agentName.match(/·\s*#(\d+)$/);
return m ? m[1] === s.intent_id : false;
});
},
[pendingIntercepts],
[pendingAgentNames],
);
// Liveness from each session's last-seen activity time (kept fresh by the 1.5s tick).
@@ -314,6 +314,7 @@ function TaskDetailInner() {
if (TABS(liveUI).some((item) => item.value === normalizedRequestedTab)) setTab(normalizedRequestedTab);
}, [normalizedRequestedTab, liveUI]);
const [interceptPendingCount, setInterceptPendingCount] = React.useState(0);
const [pendingAgentNames, setPendingAgentNames] = React.useState<string[]>([]);
const [profiles, setProfiles] = React.useState<LLMProfile[]>([]);
const [archiving, setArchiving] = React.useState(false);
@@ -326,20 +327,36 @@ function TaskDetailInner() {
React.useEffect(() => {
let alive = true;
const load = () =>
let inFlight = false;
setInterceptPendingCount(0);
setPendingAgentNames([]);
const loadSummary = () => {
if (inFlight || document.hidden) return;
inFlight = true;
api
.interceptTask(id)
.then((rows) => {
if (alive) setInterceptPendingCount(rows.filter((r) => r.status === "pending").length);
.interceptPendingSummary(id)
.then((summary) => {
if (!alive) return;
setInterceptPendingCount(summary.count);
setPendingAgentNames(summary.agent_names);
})
.catch(() => {
// Polling is best-effort; the next interval retries automatically.
})
.finally(() => {
inFlight = false;
});
void load();
const t = setInterval(load, 5000);
};
loadSummary();
const t = setInterval(loadSummary, 5000);
const onVisible = () => {
if (!document.hidden) loadSummary();
};
document.addEventListener("visibilitychange", onVisible);
return () => {
alive = false;
clearInterval(t);
document.removeEventListener("visibilitychange", onVisible);
};
}, [id]);
@@ -598,7 +615,12 @@ function TaskDetailInner() {
{/* Tab content */}
<div className="flex-1 p-4 lg:p-6">
<TabsContent value="sessions" className="mt-0">
<SessionsTab key={id} taskId={id} requestedSession={searchParams.get("session") ?? ""} />
<SessionsTab
key={id}
taskId={id}
requestedSession={searchParams.get("session") ?? ""}
pendingAgentNames={pendingAgentNames}
/>
</TabsContent>
<TabsContent value="traffic" className="mt-0">
<TrafficHistory taskId={id} />
+94 -30
View File
@@ -34,6 +34,7 @@ import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
import { api } from "@/lib/api";
import type {
InterceptApprovalFilter,
InterceptApprovalPage,
InterceptApprovalRow,
InterceptAudit,
InterceptDetail,
@@ -902,6 +903,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
const [page, setPage] = React.useState(1);
const [pageSize, setPageSize] = React.useState(20);
const [total, setTotal] = React.useState(0);
const [totalApproximate, setTotalApproximate] = React.useState(false);
const [totalCapped, setTotalCapped] = React.useState(false);
const [hasMore, setHasMore] = React.useState(false);
const [filter, setFilter] = React.useState<InterceptApprovalFilter>({});
const [searchText, setSearchText] = React.useState("");
const [fromDate, setFromDate] = React.useState("");
@@ -913,6 +917,8 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
const [deciding, setDeciding] = React.useState(false);
const [revision, setRevision] = React.useState(0);
const request = React.useRef(0);
const inFlight = React.useRef<number | null>(null);
const pendingKeyRef = React.useRef<string | null>(null);
const decisionLock = React.useRef(false);
const filterID = React.useId();
const filtered = Boolean(filter.status || filter.decision_source || filter.q || filter.from || filter.to);
@@ -925,37 +931,77 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
}, [taskId]);
const load = React.useCallback(
async (manual = false) => {
async (mode: "full" | "manual" | "poll" = "full") => {
if (mode === "poll" && (document.hidden || inFlight.current !== null)) return;
const id = ++request.current;
if (manual) setRefreshing(true);
inFlight.current = id;
if (mode === "manual") setRefreshing(true);
const fetchHistory = () =>
taskId
? api.interceptTaskPage(taskId, page, pageSize, filter)
: api.interceptHistoryPage(page, pageSize, filter);
const applyHistory = (value: InterceptApprovalPage) => {
setRows(value.items);
setTotal(value.total);
setTotalApproximate(Boolean(value.total_approximate));
setTotalCapped(Boolean(value.total_capped));
setHasMore(Boolean(value.has_more));
setError("");
};
const pendingSignature = (list: InterceptPending[]) =>
list
.map((row) => row.id)
.sort((a, b) => a - b)
.join(",");
try {
// The approval queue is independent of the current history page and its
// filter. Older requests must remain actionable even when newer decisions
// fill the page or a filter would hide them.
const [history, pending] = await Promise.allSettled([
taskId
? api.interceptTaskPage(taskId, page, pageSize, filter)
: api.interceptHistoryPage(page, pageSize, filter),
api.interceptPending(),
]);
if (id !== request.current) return;
if (history.status === "fulfilled") {
setRows(history.value.items);
setTotal(history.value.total);
setError("");
// Keep the actionable pending queue fresh on every tick. Only auto-refresh
// history on page 1 without a free-text search (or when pending IDs change)
// so background polls neither re-run full-text scans nor shift deeper pages.
const pollHistory = mode !== "poll" || (page === 1 && !filter.q);
if (pollHistory) {
// The approval queue is independent of the current history page and its
// filter. Older requests must remain actionable even when newer decisions
// fill the page or a filter would hide them.
const [history, pending] = await Promise.allSettled([fetchHistory(), api.interceptPending(taskId)]);
if (id !== request.current) return;
if (history.status === "fulfilled") {
applyHistory(history.value);
} else {
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
if (pending.status === "fulfilled") {
pendingKeyRef.current = pendingSignature(pending.value);
setPendingRows(pending.value);
setPendingError("");
} else {
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
} else {
setError((history.reason as Error).message || liveUI("screen.d1d044826a45ef"));
try {
const pending = await api.interceptPending(taskId);
if (id !== request.current) return;
const nextKey = pendingSignature(pending);
const changed = pendingKeyRef.current !== null && nextKey !== pendingKeyRef.current;
pendingKeyRef.current = nextKey;
setPendingRows(pending);
setPendingError("");
if (changed) {
try {
const history = await fetchHistory();
if (id === request.current) applyHistory(history);
} catch (e) {
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
}
}
} catch (e) {
if (id === request.current) setPendingError((e as Error).message || liveUI("screen.d1d044826a45ef"));
}
}
if (pending.status === "fulfilled") {
setPendingRows(pending.value);
setPendingError("");
} else {
setPendingError((pending.reason as Error).message || liveUI("screen.d1d044826a45ef"));
}
if (manual) setRevision((v) => v + 1);
if (mode === "manual") setRevision((v) => v + 1);
} catch (e) {
if (id === request.current) setError((e as Error).message || liveUI("screen.d1d044826a45ef"));
} finally {
if (inFlight.current === id) inFlight.current = null;
if (id === request.current) {
setLoading(false);
setRefreshing(false);
@@ -968,11 +1014,17 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
latestLoad.current = load;
React.useEffect(() => {
void load();
const timer = setInterval(() => void load(), 5000);
void load("full");
const timer = setInterval(() => void load("poll"), 5000);
const onVisible = () => {
if (!document.hidden) void load("poll");
};
document.addEventListener("visibilitychange", onVisible);
return () => {
request.current++;
inFlight.current = null;
clearInterval(timer);
document.removeEventListener("visibilitychange", onVisible);
};
}, [load]);
@@ -991,6 +1043,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setPage(1);
setRows([]);
setTotal(0);
setTotalApproximate(false);
setTotalCapped(false);
setHasMore(false);
setError("");
setLoading(true);
};
@@ -1013,6 +1068,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setPage(1);
setRows([]);
setTotal(0);
setTotalApproximate(false);
setTotalCapped(false);
setHasMore(false);
setError("");
setLoading(true);
}, 300);
@@ -1036,10 +1094,10 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
setRevision((v) => v + 1);
toast.success(decision === "allowed" ? ui("screen.c90e80972b10bf") : ui("screen.846e5cf371bfdc"));
// Re-fetch counts and rows: a decided item may no longer match the filter.
await latestLoad.current(true);
await latestLoad.current("manual");
} catch (e) {
toast.error((e as Error).message);
await latestLoad.current(true);
await latestLoad.current("manual");
} finally {
decisionLock.current = false;
setDeciding(false);
@@ -1056,6 +1114,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
...historyById.get(row.id),
...row,
}));
let totalDisplay: string | number = total;
if (totalCapped) totalDisplay = `${total}+`;
else if (totalApproximate) totalDisplay = `~${total}`;
const title = taskId ? ui("screen.b4c245b6421a35") : ui("screen.b75d0f43cd1eb7");
return (
<div className="flex min-w-0 flex-col gap-5">
@@ -1069,7 +1130,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
</Badge>
) : null}
</div>
<Button variant="outline" size="sm" onClick={() => void load(true)} disabled={loading || refreshing}>
<Button variant="outline" size="sm" onClick={() => void load("manual")} disabled={loading || refreshing}>
<RefreshCwIcon data-icon="inline-start" className={cn(refreshing && "animate-spin")} />
{ui("screen.aee88743413144")}
</Button>
@@ -1217,7 +1278,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
<div className="border-b px-4 py-3 font-medium text-sm">
{filtered ? ui("screen.479424539ce56d") : ui("screen.e4257920848098")}
{ui("punctuation.da047c04c9")}
{total}
{totalDisplay}
{ui("punctuation.f2e44c6c95")}
{filter.q ? (
<span className="ml-2 break-all font-normal text-muted-foreground text-xs">
@@ -1260,6 +1321,9 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
page={page}
pageSize={pageSize}
total={total}
totalApproximate={totalApproximate}
totalCapped={totalCapped}
hasMore={hasMore}
onPageChange={setPage}
onPageSizeChange={changePageSize}
pageSizeOptions={[10, 20, 50]}
+15 -5
View File
@@ -13,6 +13,9 @@ interface TablePaginationProps {
page: number; // 1-based
pageSize: number;
total: number; // total (after filtering)
totalApproximate?: boolean;
totalCapped?: boolean;
hasMore?: boolean;
onPageChange: (p: number) => void;
onPageSizeChange: (s: number) => void;
pageSizeOptions?: number[];
@@ -35,15 +38,22 @@ export function TablePagination({
page,
pageSize,
total,
totalApproximate = false,
totalCapped = false,
hasMore = false,
onPageChange,
onPageSizeChange,
pageSizeOptions = [10, 20, 50],
}: TablePaginationProps) {
const { t } = useTranslation();
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const totalPages = Math.max(1, Math.ceil(total / pageSize), hasMore ? page + 1 : 0);
const safePage = Math.min(Math.max(1, page), totalPages);
const from = total === 0 ? 0 : (safePage - 1) * pageSize + 1;
const to = Math.min(safePage * pageSize, total);
const hasItems = total > 0 || hasMore;
const from = hasItems ? (safePage - 1) * pageSize + 1 : 0;
const to = hasMore ? safePage * pageSize : Math.min(safePage * pageSize, total);
let totalLabel: string | number = total;
if (totalCapped) totalLabel = `${total}+`;
else if (totalApproximate) totalLabel = `~${total}`;
const onPageChangeRef = useRef(onPageChange);
onPageChangeRef.current = onPageChange;
@@ -67,8 +77,8 @@ export function TablePagination({
</SelectContent>
</Select>
<span>{t("pagination.perPage")}</span>
{total > 0 ? (
<span className="tabular-nums">{t("pagination.range", { from, to, total, count: total })}</span>
{hasItems ? (
<span className="tabular-nums">{t("pagination.range", { from, to, total: totalLabel, count: total })}</span>
) : (
<span>{t("pagination.empty")}</span>
)}
-38
View File
@@ -1,38 +0,0 @@
export const findingMessages = {
"findingDetail.remark": ["备注", "Notes"],
"findingDetail.addRemark": ["添加备注", "Add notes"],
"findingDetail.editRemark": ["编辑备注", "Edit notes"],
"findingDetail.remarkEmpty": [
"暂无备注,点击添加排查记录或复核备忘",
"No notes yet. Click to add review notes or reminders.",
],
"findingDetail.remarkEmptyReadOnly": ["暂无备注", "No notes"],
"findingDetail.remarkPlaceholder": [
"记录排查结论、利用条件或复核备忘…",
"Record triage notes, exploit conditions, or follow-up reminders…",
],
"findingDetail.remarkHint": [
"Ctrl/⌘ + Enter 保存,Esc 取消;留空保存可清除备注",
"Ctrl/⌘ + Enter to save, Esc to cancel; save empty to clear",
],
"findingDetail.remarkTooLong": ["备注最多 {{max}} 个字符", "Notes must be {{max}} characters or fewer"],
"findingDetail.remarkSaved": ["备注已保存", "Notes saved"],
"findingDetail.remarkCleared": ["备注已清除", "Notes cleared"],
"findingDetail.editButton": ["编辑", "Edit"],
"findingDetail.editTitle": ["编辑漏洞", "Edit finding"],
"findingDetail.editDescription": [
"手工修改当前漏洞的标题、分类、严重等级、状态、内容与备注。",
"Manually update the finding title, category, severity, status, details, and notes.",
],
"findingDetail.nameLabel": ["漏洞标题", "Title"],
"findingDetail.summaryPlaceholder": [
"简要描述漏洞位置、成因与影响…",
"Summarize the affected component, root cause, and impact…",
],
"findingDetail.evidencePlaceholder": [
"粘贴关键请求、响应片段或复现 PoC…",
"Paste key requests, response snippets, or PoC…",
],
"findingDetail.reportPlaceholder": ["支持 Markdown 格式的详细漏洞报告…", "Detailed Markdown vulnerability report…"],
"findingDetail.findingSaved": ["漏洞信息已更新", "Finding updated"],
} as const;
-2
View File
@@ -1,6 +1,5 @@
import { chatUIMessages } from "./chat-ui-messages";
import { errorMessages } from "./error-messages";
import { findingMessages } from "./finding-messages";
import { inlineEditorMessages } from "./inline-editor-messages";
import { notifyMessages } from "./notify-messages";
import { overviewMessages } from "./overview-messages";
@@ -17,7 +16,6 @@ export const messages = {
...termsMessages,
...taskMessages,
...notifyMessages,
...findingMessages,
...inlineEditorMessages,
...scheduleMessages,
...chatUIMessages,
+3 -3
View File
@@ -253,8 +253,8 @@ test("populated findings translate actions and headers while retaining original
name: "Original title",
vulnclass: "SQL Injection",
summary: "原始 AI 发现内容",
remark: "人工排查备注",
ts: "2026-11-10T12:30:00Z",
assets: [],
};
const props = {
items: [finding],
@@ -279,9 +279,9 @@ test("populated findings translate actions and headers while retaining original
props[k] = noop;
await i18n.changeLanguage("en");
const english = visible(render(FindingsTable, props));
for (const word of ["Finding name", "Retest", "Investigate", "Original title", "原始 AI 发现内容", "人工排查备注"])
for (const word of ["Finding name", "Retest", "Investigate", "Original title", "原始 AI 发现内容"])
assert.ok(english.includes(word), word);
assert.doesNotMatch(english.replaceAll("原始 AI 发现内容", "").replaceAll("人工排查备注", ""), /[\p{Script=Han}]/u);
assert.doesNotMatch(english.replaceAll("原始 AI 发现内容", ""), /[\p{Script=Han}]/u);
await i18n.changeLanguage("zh-CN");
assert.match(visible(render(FindingsTable, props)), /漏洞名称/);
});
+42 -22
View File
@@ -55,9 +55,11 @@ import type {
IntelligencePage,
IntentAsset,
InterceptApprovalFilter,
InterceptApprovalPage,
InterceptApprovalRow,
InterceptDetail,
InterceptPending,
InterceptPendingSummary,
InterceptRule,
JudgeConfig,
JudgeUsage,
@@ -1004,19 +1006,10 @@ export const api = {
findingLineage: (id: string) => get<{ nodes: TaskNode[]; edges: Edge[] }>(`/exploration/findings/${id}/lineage`),
setFindingStatus: (id: string, status: FindingStatus) => patch<Finding>(`/exploration/findings/${id}`, { status }),
setFindingSeverity: (id: string, severity: Severity) => patch<Finding>(`/exploration/findings/${id}`, { severity }),
// 保存漏洞的可编辑字段(列表行内编辑与详情页编辑/备注共用),只传出现的字段。
// 一次保存漏洞的名称/类别/严重等级(发现列表行内编辑用),只传出现的字段。
updateFinding: (
id: string,
fields: {
name?: string;
vulnclass?: string;
severity?: Severity;
status?: FindingStatus;
summary?: string;
evidence?: string;
report?: string;
remark?: string;
},
fields: { name?: string; vulnclass?: string; severity?: Severity; status?: FindingStatus },
) => patch<Finding>(`/exploration/findings/${id}`, fields),
// 删除漏洞:移除 findings 记录 + 来源探索节点(从发现列表/任务发现 Tab/探索图一并消失)。
deleteFinding: (id: string) => del<{ deleted: boolean; id: number }>(`/exploration/findings/${id}`),
@@ -1677,7 +1670,17 @@ export const api = {
post<{ ok: boolean; enabled: boolean }>(`/asset-intercept/rules/${id}/toggle`, { enabled }),
// ---- intercept pending (ask) ----
interceptPending: () => get<{ pending: InterceptPending[] }>("/intercept/pending").then((r) => arr(r.pending)),
interceptPending: (taskId?: string) =>
get<{ pending: InterceptPending[] }>(
taskId ? `/intercept/pending?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending",
).then((r) => arr(r.pending)),
interceptPendingSummary: (taskId?: string): Promise<InterceptPendingSummary> =>
get<{ count?: number; agent_names?: string[] }>(
taskId ? `/intercept/pending/summary?task_id=${encodeURIComponent(taskId)}` : "/intercept/pending/summary",
).then((r) => ({
count: r.count ?? 0,
agent_names: arr(r.agent_names),
})),
interceptGetOne: (id: number) => get<InterceptPending>(`/intercept/pending/${id}`),
interceptDecide: (id: number, decision: "allowed" | "denied") =>
post<{ ok: boolean }>(`/intercept/pending/${id}/decide`, { decision }),
@@ -1687,21 +1690,38 @@ export const api = {
),
interceptDetail: (id: number) => get<InterceptDetail>(`/intercept/history/${id}`),
interceptHistory: () => get<{ items: InterceptApprovalRow[] }>("/intercept/history").then((r) => arr(r.items)),
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
get<{ items: InterceptApprovalRow[]; total?: number }>(
`/intercept/history?${interceptPageQuery(page, size, filter)}`,
).then((r) => ({
interceptHistoryPage: (page = 1, size = 20, filter: InterceptApprovalFilter = {}): Promise<InterceptApprovalPage> =>
get<{
items: InterceptApprovalRow[];
total?: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}>(`/intercept/history?${interceptPageQuery(page, size, filter)}`).then((r) => ({
items: arr(r.items),
total: r.total ?? r.items?.length ?? 0,
total_approximate: Boolean(r.total_approximate),
total_capped: Boolean(r.total_capped),
has_more: Boolean(r.has_more),
})),
interceptTask: (taskId: string) =>
get<{ items: InterceptApprovalRow[] }>(`/intercept/task/${taskId}`).then((r) => arr(r.items)),
interceptTaskPage: (taskId: string, page = 1, size = 20, filter: InterceptApprovalFilter = {}) =>
get<{ items: InterceptApprovalRow[]; total?: number }>(
`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`,
).then((r) => ({
interceptTaskPage: (
taskId: string,
page = 1,
size = 20,
filter: InterceptApprovalFilter = {},
): Promise<InterceptApprovalPage> =>
get<{
items: InterceptApprovalRow[];
total?: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}>(`/intercept/task/${encodeURIComponent(taskId)}?${interceptPageQuery(page, size, filter)}`).then((r) => ({
items: arr(r.items),
total: r.total ?? r.items?.length ?? 0,
total_approximate: Boolean(r.total_approximate),
total_capped: Boolean(r.total_capped),
has_more: Boolean(r.has_more),
})),
// ---- intercept tool-config (全局工具拦截范围) ----
+1 -1
View File
@@ -102,7 +102,7 @@ test("filtering and sorting preserve the polling snapshot", () => {
});
test("keywords match each searchable field as a trimmed, case-insensitive substring", () => {
for (const field of ["name", "vulnclass", "summary", "evidence", "remark"]) {
for (const field of ["name", "vulnclass", "summary", "evidence"]) {
const match = finding("match", "high", rows[0].ts, { [field]: "prefix NeEdLe suffix" });
assert.deepEqual(
filterAndSortFindings([rows[0], match], "all", { field: "severity", direction: "desc" }, " nEEdle "),
+1 -1
View File
@@ -17,7 +17,7 @@ export function filterAndSortFindings(
(finding) =>
(severity === "all" || finding.severity === severity) &&
(!keyword ||
[finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.remark].some((value) =>
[finding.name, finding.vulnclass, finding.summary, finding.evidence].some((value) =>
(value ?? "").toLowerCase().includes(keyword),
)),
)
+24 -15
View File
@@ -520,11 +520,10 @@ function mockFilterFindings(q: URLSearchParams): (typeof mockFindings)[number][]
function mockFindingMatchesQuery(finding: (typeof mockFindings)[number], query: string | null): boolean {
const needle = query?.trim().toLowerCase();
if (!needle) return true;
return [finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.remark, finding.report].some(
(value) =>
String(value ?? "")
.toLowerCase()
.includes(needle),
return [finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.report].some((value) =>
String(value ?? "")
.toLowerCase()
.includes(needle),
);
}
@@ -2361,12 +2360,8 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
if (m === "PATCH") {
if (typeof b.status === "string") f.status = b.status as typeof f.status;
if (typeof b.severity === "string") f.severity = b.severity as typeof f.severity;
if (typeof b.name === "string") f.name = b.name.trim();
if (typeof b.vulnclass === "string") f.vulnclass = b.vulnclass.trim();
if (typeof b.summary === "string") f.summary = b.summary.trim();
if (typeof b.evidence === "string") f.evidence = b.evidence.trim() ? b.evidence : "";
if (typeof b.report === "string") f.report = b.report.trim() ? b.report : "";
if (b.remark !== undefined) f.remark = mockRemark(b.remark);
if (typeof b.name === "string") f.name = b.name;
if (typeof b.vulnclass === "string") f.vulnclass = b.vulnclass;
}
const contextTaskId = q.get("context_task");
const contextTask = contextTaskId ? mockTasks.find((item) => item.id === contextTaskId) : undefined;
@@ -2779,8 +2774,19 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
if (path === "/intercept/rules" && m === "GET") return { rules: D.interceptRules };
if (seg[0] === "intercept" && seg[1] === "rules" && seg[3] === "toggle")
return { ok: true, enabled: b.enabled ?? true };
if (path === "/intercept/pending" && m === "GET")
return { pending: mockInterceptHistory.filter((r) => r.status === "pending") };
if (path === "/intercept/pending/summary" && m === "GET") {
const taskId = q.get("task_id")?.trim() || "";
const pending = mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId));
if (!taskId) return { count: pending.length };
const agentNames = [...new Set(pending.map((r) => r.agent_name).filter(Boolean))].sort();
return { count: pending.length, agent_names: agentNames };
}
if (path === "/intercept/pending" && m === "GET") {
const taskId = q.get("task_id")?.trim() || "";
return {
pending: mockInterceptHistory.filter((r) => r.status === "pending" && (!taskId || r.task_id === taskId)),
};
}
if (seg[0] === "intercept" && seg[1] === "pending" && seg[3] === "decide") {
const id = Number(seg[2]);
const row = mockInterceptHistory.find((r) => r.id === id) ?? mockInterceptPending.find((r) => r.id === id);
@@ -2839,14 +2845,17 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
(search.startsWith("#") ? row.id === Number(search.slice(1)) : haystack.includes(search.toLowerCase())))
);
});
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to)
return { items: filtered, total: filtered.length };
if (!q.has("page") && !q.has("size") && !status && !decisionSource && !search && !from && !to) {
const capped = filtered.slice(0, 200);
return { items: capped, total: capped.length };
}
const page = Math.max(1, Number(q.get("page")) || 1);
const size = Math.min(100, Math.max(1, Number(q.get("size")) || 20));
const offset = (page - 1) * size;
return {
items: filtered.slice(offset, offset + size),
total: filtered.length,
has_more: offset + size < filtered.length,
page,
page_size: size,
};
+13 -2
View File
@@ -6,7 +6,6 @@ export type EngineMode = "exploring" | "paused" | "stalled" | "idle";
// Keep these limits aligned with db.MaxTaskRemarkRunes and db.MaxTaskWorkerCount.
export const MAX_TASK_REMARK_RUNES = 2000;
export const MAX_FINDING_REMARK_RUNES = 2000;
export const MAX_TASK_WORKER_COUNT = 50;
// Parse the optional worker-count input without silently changing invalid values.
@@ -539,7 +538,6 @@ export interface Finding {
status: FindingStatus;
summary: string;
evidence: string;
remark?: string; // 人工备注
report?: string; // 详细报告(Markdown);仅详情接口返回,列表为空
report_conversation_id?: number;
intent_id?: string;
@@ -1470,6 +1468,11 @@ export interface InterceptPending {
created_at: string;
}
export interface InterceptPendingSummary {
count: number;
agent_names: string[];
}
// JudgeConfig: 模型兜底审批(仅当没有任何拦截规则命中时由模型判断)的全局配置。
export interface JudgeConfig {
enabled: boolean;
@@ -1516,6 +1519,14 @@ export interface InterceptApprovalRow extends InterceptPending {
rule_name: string; // "" if rule was deleted
}
export interface InterceptApprovalPage {
items: InterceptApprovalRow[];
total: number;
total_approximate?: boolean;
total_capped?: boolean;
has_more?: boolean;
}
// ── 资产同步 (ScopeSentry 数据源) ──────────────────────────────────────────────
export interface SSProject {
id: string; // MongoDB ObjectID — used as filter.project