diff --git a/db/intercept.go b/db/intercept.go index cfb0416..a5e6dcd 100644 --- a/db/intercept.go +++ b/db/intercept.go @@ -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 } diff --git a/db/intercept_filter_test.go b/db/intercept_filter_test.go index 4b23437..80efe38 100644 --- a/db/intercept_filter_test.go +++ b/db/intercept_filter_test.go @@ -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) } } diff --git a/db/schema.sql b/db/schema.sql index fe0d4ec..ecfac47 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -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. diff --git a/server/intercept.go b/server/intercept.go index ae71743..0dc4b03 100644 --- a/server/intercept.go +++ b/server/intercept.go @@ -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) { diff --git a/server/intercept_filter_test.go b/server/intercept_filter_test.go index 4f6774f..73b1114 100644 --- a/server/intercept_filter_test.go +++ b/server/intercept_filter_test.go @@ -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) + } } diff --git a/server/server.go b/server/server.go index 3222b0c..4021ba3 100644 --- a/server/server.go +++ b/server/server.go @@ -1152,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) diff --git a/web/src/app/(main)/_components/sidebar/nav-main.tsx b/web/src/app/(main)/_components/sidebar/nav-main.tsx index 5e5f5c3..4d895fe 100644 --- a/web/src/app/(main)/_components/sidebar/nav-main.tsx +++ b/web/src/app/(main)/_components/sidebar/nav-main.tsx @@ -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 ( diff --git a/web/src/app/(main)/function/tasks/detail/_tabs/sessions-tab.tsx b/web/src/app/(main)/function/tasks/detail/_tabs/sessions-tab.tsx index 5379a01..88aefcc 100644 --- a/web/src/app/(main)/function/tasks/detail/_tabs/sessions-tab.tsx +++ b/web/src/app/(main)/function/tasks/detail/_tabs/sessions-tab.tsx @@ -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(null); const [sessionTokens, setSessionTokens] = React.useState>({}); const [llmResolutions, setLLMResolutions] = React.useState(null); - // Pending intercept requests for this task — used to show warning icons on sessions. - const [pendingIntercepts, setPendingIntercepts] = React.useState([]); // 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 · #" - 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). diff --git a/web/src/app/(main)/function/tasks/detail/page.tsx b/web/src/app/(main)/function/tasks/detail/page.tsx index 13bb77b..6b2ae43 100644 --- a/web/src/app/(main)/function/tasks/detail/page.tsx +++ b/web/src/app/(main)/function/tasks/detail/page.tsx @@ -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([]); const [profiles, setProfiles] = React.useState([]); 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 */}
- + diff --git a/web/src/components/approval-records.tsx b/web/src/components/approval-records.tsx index e602bef..de10677 100644 --- a/web/src/components/approval-records.tsx +++ b/web/src/components/approval-records.tsx @@ -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({}); 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(null); + const pendingKeyRef = React.useRef(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 (
@@ -1069,7 +1130,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) { ) : null}
- @@ -1217,7 +1278,7 @@ export function ApprovalRecords({ taskId }: { taskId?: string }) {
{filtered ? ui("screen.479424539ce56d") : ui("screen.e4257920848098")} {ui("punctuation.da047c04c9")} - {total} + {totalDisplay} {ui("punctuation.f2e44c6c95")} {filter.q ? ( @@ -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]} diff --git a/web/src/components/table-pagination.tsx b/web/src/components/table-pagination.tsx index ce7d7fa..6a0bec5 100644 --- a/web/src/components/table-pagination.tsx +++ b/web/src/components/table-pagination.tsx @@ -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({ {t("pagination.perPage")} - {total > 0 ? ( - {t("pagination.range", { from, to, total, count: total })} + {hasItems ? ( + {t("pagination.range", { from, to, total: totalLabel, count: total })} ) : ( {t("pagination.empty")} )} diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts index bf1ba57..d632fe8 100644 --- a/web/src/lib/api.ts +++ b/web/src/lib/api.ts @@ -54,9 +54,11 @@ import type { IntelligencePage, IntentAsset, InterceptApprovalFilter, + InterceptApprovalPage, InterceptApprovalRow, InterceptDetail, InterceptPending, + InterceptPendingSummary, InterceptRule, JudgeConfig, JudgeUsage, @@ -1672,7 +1674,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 => + 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(`/intercept/pending/${id}`), interceptDecide: (id: number, decision: "allowed" | "denied") => post<{ ok: boolean }>(`/intercept/pending/${id}/decide`, { decision }), @@ -1682,21 +1694,38 @@ export const api = { ), interceptDetail: (id: number) => get(`/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 => + 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 => + 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 (全局工具拦截范围) ---- diff --git a/web/src/lib/mock/handler.ts b/web/src/lib/mock/handler.ts index bed33a5..776451a 100644 --- a/web/src/lib/mock/handler.ts +++ b/web/src/lib/mock/handler.ts @@ -2774,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); @@ -2834,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, }; diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 567d547..005a39a 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -1468,6 +1468,11 @@ export interface InterceptPending { created_at: string; } +export interface InterceptPendingSummary { + count: number; + agent_names: string[]; +} + // JudgeConfig: 模型兜底审批(仅当没有任何拦截规则命中时由模型判断)的全局配置。 export interface JudgeConfig { enabled: boolean; @@ -1514,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