mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-24 09:41:51 +08:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # web/src/i18n/messages.ts
This commit is contained in:
commit
044f420c48
34 files changed
+2279
-150
No files matched your search
@@ -4,6 +4,15 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### 新增与改进
|
||||
|
||||
- 支持热更新运行中任务的 Worker 并发:任务详情可设置 0(跟随全局)或 1–50;全局工作并发与 Worker 池变更会同步至跟随全局的任务。增容立即补起 Worker,缩容等待当前意图完成后退出,不中断正在执行的工作;详情展示实际存活 Worker 数与目标数。配置持久化,重启恢复时沿用。
|
||||
- `PATCH /api/tasks/{id}` 新增 `worker_count`;任务接口返回 `worker_actual_count`(存活池循环,含缩容等待中的 Worker)与 `worker_target_count`(有效目标数),与 `in_flight`(执行中意图数)区分。
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复运行中任务仍使用旧 Worker 池模型配置的问题(#141):即使并发数和 slot 名称不变,保存新的 profile 绑定也会替换运行时 Worker;旧配置不可用的空闲 Worker 立即退出,正在执行的 Worker 完成当前意图后切换,新意图不再由旧绑定领取。任务模型链不覆盖显式 Worker 池绑定,历史 blocked 意图不自动重跑。
|
||||
|
||||
## [0.3.30] - 2026-11-14
|
||||
|
||||
### 新增与改进
|
||||
|
||||
+129
@@ -787,6 +787,135 @@ func (d *DB) DeleteFinding(id int64) (n int64, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteFindings bulk-removes findings matching either an explicit id list
|
||||
// (when ids is non-empty, ignoring f) or a FindingFilter (empty f = all
|
||||
// findings). Like DeleteFinding, each deleted finding's originating
|
||||
// exploration node (kind='finding') is also removed inside the same evidence
|
||||
// transaction so the findings list, per-task 发现 Tab, and exploration graph
|
||||
// stay consistent. Returns the number of findings deleted.
|
||||
func (d *DB) DeleteFindings(ctx context.Context, f FindingFilter, ids []int64) (deleted int64, err error) {
|
||||
var scoped FindingFilter
|
||||
var uniqueIDs []int64
|
||||
if len(ids) > 0 {
|
||||
seen := make(map[int64]struct{}, len(ids))
|
||||
for _, id := range ids {
|
||||
if id <= 0 {
|
||||
continue
|
||||
}
|
||||
if _, ok := seen[id]; ok {
|
||||
continue
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
uniqueIDs = append(uniqueIDs, id)
|
||||
}
|
||||
if len(uniqueIDs) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
} else {
|
||||
scoped, err = d.applyAssetScope(f)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
err = d.WithEvidenceTx(ctx, func(tx *sql.Tx) error {
|
||||
deleted = 0
|
||||
var (
|
||||
rows *sql.Rows
|
||||
qerr error
|
||||
)
|
||||
if len(uniqueIDs) > 0 {
|
||||
rows, qerr = tx.QueryContext(ctx, `SELECT f.id, f.task_id FROM findings f WHERE f.id = ANY($1::bigint[]) ORDER BY f.id ASC`, uniqueIDs)
|
||||
} else {
|
||||
where, args := scoped.where()
|
||||
rows, qerr = tx.QueryContext(ctx, `SELECT f.id, f.task_id FROM findings f LEFT JOIN tasks t ON f.task_id = t.id`+where+` ORDER BY f.id ASC`, args...)
|
||||
}
|
||||
if qerr != nil {
|
||||
return qerr
|
||||
}
|
||||
var targetIDs []int64
|
||||
taskSet := map[int64]struct{}{}
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var taskID sql.NullInt64
|
||||
if err := rows.Scan(&id, &taskID); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
targetIDs = append(targetIDs, id)
|
||||
if taskID.Valid && taskID.Int64 > 0 {
|
||||
taskSet[taskID.Int64] = struct{}{}
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(targetIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
taskIDs := make([]int64, 0, len(taskSet))
|
||||
for tid := range taskSet {
|
||||
taskIDs = append(taskIDs, tid)
|
||||
}
|
||||
sort.Slice(taskIDs, func(i, j int) bool { return taskIDs[i] < taskIDs[j] })
|
||||
for _, tid := range taskIDs {
|
||||
if err := LockTaskEvidenceTx(tx, tid); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
lockRows, err := tx.QueryContext(ctx, `SELECT id FROM findings WHERE id = ANY($1::bigint[]) ORDER BY id ASC FOR UPDATE`, targetIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for lockRows.Next() {
|
||||
}
|
||||
if err := lockRows.Err(); err != nil {
|
||||
lockRows.Close()
|
||||
return err
|
||||
}
|
||||
if err := lockRows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
delRows, err := tx.QueryContext(ctx, `DELETE FROM findings WHERE id = ANY($1::bigint[]) RETURNING node_id`, targetIDs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var nodeIDs []int64
|
||||
for delRows.Next() {
|
||||
var nodeID sql.NullInt64
|
||||
if err := delRows.Scan(&nodeID); err != nil {
|
||||
delRows.Close()
|
||||
return err
|
||||
}
|
||||
deleted++
|
||||
if nodeID.Valid {
|
||||
nodeIDs = append(nodeIDs, nodeID.Int64)
|
||||
}
|
||||
}
|
||||
if err := delRows.Err(); err != nil {
|
||||
delRows.Close()
|
||||
return err
|
||||
}
|
||||
if err := delRows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(nodeIDs) > 0 {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM exploration_nodes WHERE id = ANY($1::bigint[]) AND kind='finding'`, nodeIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// DeleteFindingsByTask removes all findings rows of a task. The originating
|
||||
// exploration finding nodes are cascade-deleted separately when the task's
|
||||
// exploration subgraph is dropped. Returns rows deleted.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -517,3 +518,129 @@ func TestAddFindingFollowUpIntent(t *testing.T) {
|
||||
t.Fatalf("missing source node: want ErrFindingOriginUnavailable, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeleteFindings exercises bulk deletion by explicit ids, by FindingFilter,
|
||||
// and atomic rollback on task archive state conflicts.
|
||||
func TestDeleteFindings(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
marker := fmt.Sprintf("__bulk_delete_%d__", time.Now().UnixNano())
|
||||
tk, err := d.CreateTask("批量清理测试", "目标", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = d.Exec(`DELETE FROM findings WHERE vulnclass=$1`, marker)
|
||||
_ = d.DeleteTask(tk.ID)
|
||||
})
|
||||
|
||||
es := d.Exploration(tk.ExplorationID)
|
||||
node1, err := es.AddNode(KindFinding, map[string]any{"summary": "f1", "severity": "high"}, 5, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
node2, err := es.AddNode(KindFinding, map[string]any{"summary": "f2", "severity": "low"}, 5, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keepNode, err := es.AddNode(KindFinding, map[string]any{"summary": "keep", "severity": "medium"}, 5, "confirmed", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intentNode, err := es.AddNode(KindIntent, map[string]any{"summary": "intent"}, 5, "open", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f1, err := d.AddFinding(tk.ID, node1, marker, "f1", SeverityHigh, "sum1", "poc1", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f2, err := d.AddFinding(tk.ID, node2, marker, "f2", SeverityLow, "sum2", "poc2", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fKeep, err := d.AddFinding(tk.ID, keepNode, marker, "keep", SeverityMedium, "sum3", "poc3", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fOrphan, err := d.AddFinding(0, 0, marker, "orphan", SeverityLow, "orphan-sum", "poc4", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.SetFindingStatus(f2, FindingFalsePositive); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 1. Delete by explicit ids (with duplicate and missing id).
|
||||
n, err := d.DeleteFindings(context.Background(), FindingFilter{}, []int64{f1, f1, 999999999})
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteFindings(ids): %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("DeleteFindings(ids): want 1, got %d", n)
|
||||
}
|
||||
if got, _ := d.GetFinding(f1); got != nil {
|
||||
t.Fatalf("f1 should be deleted")
|
||||
}
|
||||
var cnt int
|
||||
_ = d.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE id=$1`, node1).Scan(&cnt)
|
||||
if cnt != 0 {
|
||||
t.Fatalf("node1 should be deleted, got %d", cnt)
|
||||
}
|
||||
_ = d.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE id=$1`, intentNode).Scan(&cnt)
|
||||
if cnt != 1 {
|
||||
t.Fatalf("intent node should remain, got %d", cnt)
|
||||
}
|
||||
|
||||
// 2. Delete by FindingFilter (status=false_positive + unique marker).
|
||||
n, err = d.DeleteFindings(context.Background(), FindingFilter{VulnClass: marker, Status: FindingFalsePositive}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteFindings(filtered): %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("DeleteFindings(filtered): want 1, got %d", n)
|
||||
}
|
||||
if got, _ := d.GetFinding(f2); got != nil {
|
||||
t.Fatalf("f2 should be deleted")
|
||||
}
|
||||
_ = d.QueryRow(`SELECT count(*) FROM exploration_nodes WHERE id=$1`, node2).Scan(&cnt)
|
||||
if cnt != 0 {
|
||||
t.Fatalf("node2 should be deleted, got %d", cnt)
|
||||
}
|
||||
|
||||
// 3. Delete unassigned historical finding via TaskID=FindingUnassignedTask.
|
||||
n, err = d.DeleteFindings(context.Background(), FindingFilter{VulnClass: marker, TaskID: FindingUnassignedTask}, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("DeleteFindings(unassigned): %v", err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("DeleteFindings(unassigned): want 1, got %d", n)
|
||||
}
|
||||
if got, _ := d.GetFinding(fOrphan); got != nil {
|
||||
t.Fatalf("fOrphan should be deleted")
|
||||
}
|
||||
|
||||
// fKeep must remain untouched.
|
||||
if got, _ := d.GetFinding(fKeep); got == nil {
|
||||
t.Fatalf("fKeep should remain")
|
||||
}
|
||||
|
||||
// 4. Task in archive/soft-deleted state must fail atomically with ErrTaskArchiveState.
|
||||
if _, err := d.Exec(`UPDATE tasks SET deleted_at=now() WHERE id=$1`, tk.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := d.DeleteFindings(context.Background(), FindingFilter{}, []int64{fKeep}); !errors.Is(err, ErrTaskArchiveState) {
|
||||
t.Fatalf("soft-deleted task: want ErrTaskArchiveState, got %v", err)
|
||||
}
|
||||
if got, _ := d.GetFinding(fKeep); got == nil {
|
||||
t.Fatalf("fKeep should survive rolled-back delete")
|
||||
}
|
||||
if _, err := d.Exec(`UPDATE tasks SET deleted_at=NULL WHERE id=$1`, tk.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -102,3 +102,41 @@ func TestDeleteConversationsReturnsExistingIDs(t *testing.T) {
|
||||
t.Fatalf("deleted=%v, want existing ids only", deleted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskPatchWorkerCountPersistsAndValidates(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
task, err := d.CreateTask("worker count patch", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = d.DeleteTask(task.ID) }()
|
||||
for _, count := range []int{1, MaxTaskWorkerCount, 0, 4} {
|
||||
updated, err := d.UpdateTask(task.ID, TaskPatch{WorkerCount: &count})
|
||||
if err != nil || updated == nil || updated.WorkerCount != count {
|
||||
t.Fatalf("patch worker_count=%d task=%+v err=%v", count, updated, err)
|
||||
}
|
||||
persisted, err := d.GetTask(task.ID)
|
||||
if err != nil || persisted == nil || persisted.WorkerCount != count {
|
||||
t.Fatalf("read worker_count=%d task=%+v err=%v", count, persisted, err)
|
||||
}
|
||||
}
|
||||
name := "renamed without worker override"
|
||||
updated, err := d.UpdateTask(task.ID, TaskPatch{Name: &name})
|
||||
if err != nil || updated == nil || updated.WorkerCount != 4 {
|
||||
t.Fatalf("omitted worker_count changed override: task=%+v err=%v", updated, err)
|
||||
}
|
||||
for _, count := range []int{-1, MaxTaskWorkerCount + 1} {
|
||||
invalidName := "must not commit"
|
||||
if updated, err := d.UpdateTask(task.ID, TaskPatch{Name: &invalidName, WorkerCount: &count}); err == nil || updated != nil {
|
||||
t.Fatalf("accepted invalid worker_count=%d: task=%+v err=%v", count, updated, err)
|
||||
}
|
||||
persisted, err := d.GetTask(task.ID)
|
||||
if err != nil || persisted == nil || persisted.WorkerCount != 4 || persisted.Name != name {
|
||||
t.Fatalf("invalid patch changed task=%+v err=%v", persisted, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-4
@@ -165,6 +165,9 @@ func normalizeWorkerCount(n int) int {
|
||||
}
|
||||
|
||||
func validateWorkerCount(n int) error {
|
||||
if n < 0 {
|
||||
return fmt.Errorf("Worker 运行数量不能为负数")
|
||||
}
|
||||
if n > MaxTaskWorkerCount {
|
||||
return fmt.Errorf("Worker 运行数量最多 %d", MaxTaskWorkerCount)
|
||||
}
|
||||
@@ -471,17 +474,23 @@ ORDER BY (pinned_at IS NOT NULL) DESC, pinned_at DESC NULLS LAST, id DESC`)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TaskPatch updates editable metadata and global asset visibility.
|
||||
// TaskPatch updates editable metadata, asset visibility, and worker concurrency.
|
||||
type TaskPatch struct {
|
||||
Name *string
|
||||
Remark *string
|
||||
Pinned *bool
|
||||
ShareGlobalAssets *bool
|
||||
WorkerCount *int
|
||||
}
|
||||
|
||||
// UpdateTask applies a partial metadata/visibility mutation and returns the updated row.
|
||||
// UpdateTask applies a partial metadata/runtime-policy mutation and returns the updated row.
|
||||
// Re-pinning an already pinned task preserves its original position.
|
||||
func (d *DB) UpdateTask(id int64, patch TaskPatch) (*Task, error) {
|
||||
if patch.WorkerCount != nil {
|
||||
if err := validateWorkerCount(*patch.WorkerCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
task, err := scanTask(d.QueryRow(`UPDATE tasks SET
|
||||
name = CASE WHEN $2::boolean THEN $3 ELSE name END,
|
||||
remark = CASE WHEN $5::boolean THEN $6 ELSE remark END,
|
||||
@@ -490,9 +499,10 @@ func (d *DB) UpdateTask(id int64, patch TaskPatch) (*Task, error) {
|
||||
WHEN $4::boolean THEN COALESCE(pinned_at, now())
|
||||
ELSE NULL
|
||||
END,
|
||||
share_global_assets = COALESCE($7::boolean, share_global_assets)
|
||||
share_global_assets = COALESCE($7::boolean, share_global_assets),
|
||||
worker_count = COALESCE($8::integer, worker_count)
|
||||
WHERE id=$1 AND deleted_at IS NULL
|
||||
RETURNING `+taskCols, id, patch.Name != nil, patch.Name, patch.Pinned, patch.Remark != nil, patch.Remark, patch.ShareGlobalAssets))
|
||||
RETURNING `+taskCols, id, patch.Name != nil, patch.Name, patch.Pinned, patch.Remark != nil, patch.Remark, patch.ShareGlobalAssets, patch.WorkerCount))
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
+4
-2
@@ -70,7 +70,9 @@ type TaskDTO struct {
|
||||
CompanyIDs []int64 `json:"company_ids"`
|
||||
CoverageEnabled bool `json:"coverage_enabled"` // 资产覆盖度功能开关(创建时定)
|
||||
ShareGlobalAssets bool `json:"share_global_assets"`
|
||||
WorkerCount int `json:"worker_count"` // 本任务 Worker 数;0=用全局默认
|
||||
WorkerCount int `json:"worker_count"` // 本任务 Worker 数;0=用全局默认
|
||||
WorkerActualCount int `json:"worker_actual_count"` // live pool loops, including draining workers
|
||||
WorkerTargetCount int `json:"worker_target_count"` // desired worker slots
|
||||
|
||||
NoResultSeconds int `json:"no_result_seconds"`
|
||||
NoResultMinFindings int `json:"no_result_min_findings"`
|
||||
@@ -170,7 +172,7 @@ func taskDTO(t *Task, status string) TaskDTO {
|
||||
CompanyIDs: lifecycle.CompanyIDs,
|
||||
CoverageEnabled: t.CoverageEnabled,
|
||||
ShareGlobalAssets: lifecycle.ShareGlobalAssets,
|
||||
WorkerCount: t.WorkerCount,
|
||||
WorkerCount: lifecycle.WorkerCount,
|
||||
|
||||
NoResultSeconds: t.NoResultSeconds,
|
||||
NoResultMinFindings: t.NoResultMinFindings,
|
||||
|
||||
+42
-47
@@ -111,8 +111,9 @@ type Engine struct {
|
||||
// Every long-lived task goroutine (planner, workers and deadline coordinator)
|
||||
// runs under one task-scoped context. Successful deletion cancels that context,
|
||||
// waits for all goroutines, then releases every task-level Engine reference.
|
||||
runtimeMu sync.Mutex
|
||||
runtimes map[string]*taskRuntime
|
||||
runtimeMu sync.Mutex
|
||||
runtimes map[string]*taskRuntime
|
||||
workerPools sync.Map // taskID -> *taskWorkerPool; each pool serializes claims with resizing
|
||||
|
||||
// per-task execution context: each planner.Plan / worker.Execute runs under it,
|
||||
// so pausing can CANCEL an in-flight run (not just skip the next one). Recreated
|
||||
@@ -150,7 +151,7 @@ type Engine struct {
|
||||
resolveAuthoritative bool
|
||||
workerResolve func(t *Task, slot WorkerSlot) (*agent.Worker, error)
|
||||
slotState sync.Map // task/slot -> slotAvailability
|
||||
slotPlans sync.Map // task -> map[slot name]profile ID; immutable for a run
|
||||
slotPlans sync.Map // task -> immutable snapshot of slot name/profile routing
|
||||
// readiness reports whether a global LLM provider is configured — the signal behind
|
||||
// Ready()/the llm_configured indicator. Wired once at startup; nil → not ready.
|
||||
readiness func() bool
|
||||
@@ -297,6 +298,7 @@ func (e *Engine) StopTask(taskID string) {
|
||||
e.inflight.Delete(taskID)
|
||||
e.coordStarted.Delete(taskID)
|
||||
e.slotPlans.Delete(taskID)
|
||||
e.workerPools.Delete(taskID)
|
||||
e.slotState.Range(func(key, _ any) bool {
|
||||
keyText, ok := key.(string)
|
||||
if ok && strings.HasPrefix(keyText, taskID+"/") {
|
||||
@@ -406,10 +408,14 @@ func (e *Engine) ActiveLLMCalls(taskID string) int64 {
|
||||
func (e *Engine) touch(taskID string) { e.lastAct.Store(taskID, time.Now().Unix()) }
|
||||
|
||||
func NewEngine(m *Manager) *Engine {
|
||||
return &Engine{m: m, debounce: 800 * time.Millisecond, bc: NewBroadcaster(),
|
||||
e := &Engine{m: m, debounce: 800 * time.Millisecond, bc: NewBroadcaster(),
|
||||
execCancel: map[string]context.CancelCauseFunc{}, execCtx: map[string]context.Context{},
|
||||
work: map[int64]*workExecution{}, steerBox: map[int64][]string{},
|
||||
runtimes: map[string]*taskRuntime{}}
|
||||
if m != nil {
|
||||
m.SetWorkerConfigChangedCallback(e.ReconcileDefaultWorkers)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// registerWork records the cancel for the work currently running intentID.
|
||||
@@ -796,11 +802,6 @@ func (e *Engine) ReadyFor(t *Task) bool {
|
||||
// but no-op until an LLM is configured (so a task created while idle picks up
|
||||
// automatically once LLM is set from the UI).
|
||||
func (e *Engine) Run(ctx context.Context, t *Task) {
|
||||
slots, err := workerSlotsForTask(t, e.m.WorkerPools(), e.m.Workers())
|
||||
if err != nil {
|
||||
log.Printf("[engine] task %s worker pool invalid, using legacy workers: %v", t.ID, err)
|
||||
slots, _ = ExpandWorkerSlots(nil, workerCountForTask(t, e.m.Workers()))
|
||||
}
|
||||
e.deleteMu.RLock()
|
||||
if e.IsDeleting(t.ID) {
|
||||
e.deleteMu.RUnlock()
|
||||
@@ -811,19 +812,13 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
||||
t.Notify() // already running — just nudge a planning round
|
||||
return
|
||||
}
|
||||
rt := e.registerTaskRoutines(ctx, t.ID, 1+len(slots))
|
||||
plan := make(map[string]int64, len(slots))
|
||||
for _, slot := range slots {
|
||||
plan[slot.Name] = slot.ProfileID
|
||||
}
|
||||
e.slotPlans.Store(t.ID, plan)
|
||||
rt := e.registerTaskRoutines(ctx, t.ID, 1)
|
||||
pool := &taskWorkerPool{runtime: rt, task: t, loops: make(map[string]*workerSlotRuntime)}
|
||||
e.workerPools.Store(t.ID, pool)
|
||||
e.deleteMu.RUnlock()
|
||||
e.touch(t.ID)
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.plannerLoop(loopCtx, t) })
|
||||
for _, slot := range slots {
|
||||
slot := slot
|
||||
runTaskRoutine(rt, func(loopCtx context.Context) { e.workerLoop(loopCtx, t, slot) })
|
||||
}
|
||||
e.ReconcileWorkers(t)
|
||||
e.startDeadlineCoordinator(ctx, t) // 任务级超时定时器(仅 timeout>0;去重)
|
||||
// 仅在「完全没有活动意图(open+running)」时才 kick 首轮规划。带种子意图的任务:种子已
|
||||
// 是 open,或已被上面刚起的 worker 抢先 claim 成 running——两种都算「有活干」,一律跳过
|
||||
@@ -838,20 +833,20 @@ func (e *Engine) Run(ctx context.Context, t *Task) {
|
||||
// workerSlotsForTask preserves an explicit task concurrency override. Tasks
|
||||
// using the global default inherit its model pools and their pinned profiles.
|
||||
func workerSlotsForTask(t *Task, pools []WorkerPool, global int) ([]WorkerSlot, error) {
|
||||
if t != nil && t.WorkerCount > 0 {
|
||||
if t != nil && t.lifecycleSnapshot().WorkerCount > 0 {
|
||||
return ExpandWorkerSlots(nil, workerCountForTask(t, global))
|
||||
}
|
||||
return ExpandWorkerSlots(pools, global)
|
||||
}
|
||||
|
||||
func workerCountForTask(t *Task, global int) int {
|
||||
if t != nil && t.WorkerCount > 0 {
|
||||
// Direct database edits can bypass validation; cap those values so the
|
||||
// engine never starts more than the supported per-task worker count.
|
||||
if t.WorkerCount > db.MaxTaskWorkerCount {
|
||||
return db.MaxTaskWorkerCount
|
||||
if t != nil {
|
||||
if count := t.lifecycleSnapshot().WorkerCount; count > 0 {
|
||||
if count > db.MaxTaskWorkerCount {
|
||||
return db.MaxTaskWorkerCount
|
||||
}
|
||||
return count
|
||||
}
|
||||
return t.WorkerCount
|
||||
}
|
||||
return global
|
||||
}
|
||||
@@ -1004,11 +999,12 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) {
|
||||
}
|
||||
}
|
||||
|
||||
func (e *Engine) workerLoop(ctx context.Context, t *Task, slot WorkerSlot) {
|
||||
func (e *Engine) workerLoop(ctx context.Context, t *Task, slot WorkerSlot, control *workerSlotRuntime) {
|
||||
name := slot.Name
|
||||
idleCtx := control.idleCtx
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-idleCtx.Done():
|
||||
return
|
||||
default:
|
||||
}
|
||||
@@ -1031,13 +1027,13 @@ func (e *Engine) workerLoop(ctx context.Context, t *Task, slot WorkerSlot) {
|
||||
_, worker = e.snapshotFor(t)
|
||||
}
|
||||
if worker == nil {
|
||||
if sleepCtx(ctx, 1500*time.Millisecond) {
|
||||
if sleepCtx(idleCtx, 1500*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if e.IsPaused(t.ID) {
|
||||
if sleepCtx(ctx, 1000*time.Millisecond) {
|
||||
if sleepCtx(idleCtx, 1000*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue // user-paused: don't claim/execute intents
|
||||
@@ -1046,13 +1042,13 @@ func (e *Engine) workerLoop(ctx context.Context, t *Task, slot WorkerSlot) {
|
||||
return
|
||||
}
|
||||
if e.isSettling(t.ID) {
|
||||
if sleepCtx(ctx, 1000*time.Millisecond) {
|
||||
if sleepCtx(idleCtx, 1000*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue // 任务超时收尾中:不再领新意图(在跑的自行收尾,协调器等其 drain)
|
||||
}
|
||||
if isTerminalStatus(e.m.TaskStatus(t.ID)) {
|
||||
if sleepCtx(ctx, 1000*time.Millisecond) {
|
||||
if sleepCtx(idleCtx, 1000*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
continue // 任务已终态(done/failed/timeout):停止领取遗留意图,别在完成后空跑 frontier
|
||||
@@ -1060,28 +1056,27 @@ func (e *Engine) workerLoop(ctx context.Context, t *Task, slot WorkerSlot) {
|
||||
if !e.beginTaskOperation(t.ID) {
|
||||
return
|
||||
}
|
||||
claimed := e.runWorkerStep(ctx, t, name, worker)
|
||||
// A resize and the next claim share the pool lock. Once retirement is
|
||||
// requested this loop cannot claim again; execution keeps the task context.
|
||||
control.pool.mu.Lock()
|
||||
var intent *db.Node
|
||||
if idleCtx.Err() == nil {
|
||||
intent = e.claimNext(t, name)
|
||||
}
|
||||
control.pool.mu.Unlock()
|
||||
if intent != nil {
|
||||
log.Printf("[worker %s] task %s 领取意图 #%d", name, t.ID, intent.ID)
|
||||
e.runIntent(ctx, t, name, worker, intent, "", "")
|
||||
}
|
||||
e.decInflight(t.ID)
|
||||
if !claimed && sleepCtx(ctx, 800*time.Millisecond) {
|
||||
if intent == nil && sleepCtx(idleCtx, 800*time.Millisecond) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runWorkerStep claims one intent from the frontier and fully settles it via
|
||||
// runIntent. Returns false when nothing was claimable. The pool worker loop is its
|
||||
// only caller.
|
||||
func (e *Engine) runWorkerStep(ctx context.Context, t *Task, name string, worker *agent.Worker) bool {
|
||||
intent := e.claimNext(t, name)
|
||||
if intent == nil {
|
||||
return false
|
||||
}
|
||||
log.Printf("[worker %s] task %s 领取意图 #%d", name, t.ID, intent.ID)
|
||||
return e.runIntent(ctx, t, name, worker, intent, "", "")
|
||||
}
|
||||
|
||||
// runIntent executes and fully settles one already-claimed (state=running) intent.
|
||||
// Both the pool worker loop (via runWorkerStep) and the human-message handler (via
|
||||
// Both the pool worker loop and the human-message handler (via
|
||||
// runDetachedIntent, a dedicated goroutine outside the worker pool) call it, so the
|
||||
// execute/retry/state-write logic lives in exactly one place. A non-empty message
|
||||
// is injected as this turn's input through ExecuteWithMessage; requestID keys the
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
)
|
||||
|
||||
// Issue #141: saving a different pool profile must replace a running task's
|
||||
// pinned worker even when the slot name and pool size do not change.
|
||||
func TestWorkerPoolProfileHotReload(t *testing.T) {
|
||||
for _, unavailable := range []bool{true, false} {
|
||||
t.Run(fmt.Sprintf("old_profile_unavailable=%t", unavailable), func(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
oldPools, poolsSet, err := m.pg.GetSetting(settingWorkerPools)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldWorkers, workersSet, err := m.pg.GetSetting(settingWorkers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
for key, value := range map[string]struct {
|
||||
text string
|
||||
set bool
|
||||
}{settingWorkerPools: {oldPools, poolsSet}, settingWorkers: {oldWorkers, workersSet}} {
|
||||
if value.set {
|
||||
_ = m.pg.SetSetting(key, value.text)
|
||||
} else {
|
||||
_, _ = m.pg.Exec("DELETE FROM settings WHERE key=$1", key)
|
||||
}
|
||||
}
|
||||
}()
|
||||
oldID, err := m.pg.SaveProfile(&db.LLMProfile{Name: "old-worker", Format: "openai", Model: "old-model"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.pg.DeleteProfile(oldID)
|
||||
newID, err := m.pg.SaveProfile(&db.LLMProfile{Name: "new-worker", Format: "openai", Model: "new-model"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.pg.DeleteProfile(newID)
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: oldID, Workers: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := m.CreateTask("worker profile switch", "fixture", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.DeleteTask(task.ID, DeleteTaskOptions{})
|
||||
intentID, err := task.Store.AddIntent(map[string]any{"text": "first intent"}, 0, nil, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := NewEngine(m)
|
||||
defer e.StopTask(task.ID)
|
||||
oldProvider := &resizingProvider{calls: make(chan resizingCall, 4)}
|
||||
newProvider := &resizingProvider{calls: make(chan resizingCall, 4)}
|
||||
s := &Server{
|
||||
m: m, engine: e,
|
||||
provByProfile: map[int64]*provEntry{
|
||||
newID: {prov: newProvider, cfg: agent.Config{Model: "new-model", Retry: agent.RetryConfig{StreamAttempts: -1}}},
|
||||
},
|
||||
taskAgents: map[string]*taskAgentBundle{task.ID: {pinnedWorkers: map[int64]*agent.Worker{}}},
|
||||
}
|
||||
// The unavailable fixture has no usable credentials and no cached
|
||||
// provider; workerForTaskSlot must reject it without claiming work.
|
||||
if !unavailable {
|
||||
s.provByProfile[oldID] = &provEntry{prov: oldProvider, cfg: agent.Config{Model: "old-model"}}
|
||||
}
|
||||
e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return nil, nil })
|
||||
oldResolved := make(chan struct{})
|
||||
var once sync.Once
|
||||
e.SetWorkerResolver(func(task *Task, slot WorkerSlot) (*agent.Worker, error) {
|
||||
worker, err := s.workerForTaskSlot(task, slot)
|
||||
if slot.ProfileID == oldID {
|
||||
once.Do(func() { close(oldResolved) })
|
||||
}
|
||||
return worker, err
|
||||
})
|
||||
e.Run(t.Context(), task)
|
||||
select {
|
||||
case <-oldResolved:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("old slot was never resolved")
|
||||
}
|
||||
getCall := func(provider *resizingProvider) resizingCall {
|
||||
t.Helper()
|
||||
select {
|
||||
case call := <-provider.calls:
|
||||
return call
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("worker did not call the expected provider")
|
||||
return resizingCall{}
|
||||
}
|
||||
}
|
||||
var oldCall resizingCall
|
||||
if !unavailable {
|
||||
oldCall = getCall(oldProvider)
|
||||
intentID, err = task.Store.AddIntent(map[string]any{"text": "next intent"}, 0, nil, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
node, err := task.Store.GetNode(intentID)
|
||||
if err != nil || node == nil || node.State != "open" {
|
||||
t.Fatalf("unavailable profile claimed intent: node=%+v err=%v", node, err)
|
||||
}
|
||||
}
|
||||
// Same count, different profile. Repeated saves must be harmless.
|
||||
for range 2 {
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: newID, Workers: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if !unavailable {
|
||||
if oldCall.ctx.Err() != nil {
|
||||
t.Fatal("profile switch cancelled the in-flight intent")
|
||||
}
|
||||
select {
|
||||
case <-newProvider.calls:
|
||||
t.Fatal("replacement started before the old slot settled")
|
||||
default:
|
||||
}
|
||||
close(oldCall.release)
|
||||
}
|
||||
newCall := getCall(newProvider)
|
||||
node, err := task.Store.GetNode(intentID)
|
||||
if err != nil || node == nil || node.State != "running" || node.Owner != "work#1" {
|
||||
t.Fatalf("replacement did not claim intent: node=%+v err=%v", node, err)
|
||||
}
|
||||
close(newCall.release)
|
||||
waitWorkerCondition(t, func() bool {
|
||||
node, _ := task.Store.GetNode(intentID)
|
||||
return node != nil && node.State == "done" && e.inflightCount(task.ID) == 0
|
||||
})
|
||||
select {
|
||||
case <-oldProvider.calls:
|
||||
t.Fatal("retired slot called the old provider again")
|
||||
default:
|
||||
}
|
||||
if actual, target := e.WorkerCounts(task); actual != 1 || target != 1 {
|
||||
t.Fatalf("replacement loop counts=%d/%d, want 1/1", actual, target)
|
||||
}
|
||||
// StopTask must include the dynamically replaced slot in its wait.
|
||||
e.StopTask(task.ID)
|
||||
if e.Started(task.ID) {
|
||||
t.Fatal("replacement survived StopTask")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// taskWorkerPool owns the desired plan and all live loops, including retirees.
|
||||
// A slot name is never reused until its previous loop has fully settled its work.
|
||||
type taskWorkerPool struct {
|
||||
mu sync.Mutex
|
||||
runtime *taskRuntime
|
||||
task *Task
|
||||
loops map[string]*workerSlotRuntime
|
||||
desired map[string]WorkerSlot
|
||||
}
|
||||
|
||||
type workerSlotRuntime struct {
|
||||
pool *taskWorkerPool
|
||||
slot WorkerSlot
|
||||
idleCtx context.Context
|
||||
retire context.CancelFunc // stops claiming/sleeping, never cancels Execute
|
||||
}
|
||||
|
||||
func (e *Engine) desiredWorkerSlots(t *Task) []WorkerSlot {
|
||||
slots, err := workerSlotsForTask(t, e.m.WorkerPools(), e.m.Workers())
|
||||
if err != nil {
|
||||
log.Printf("[engine] task %s worker pool invalid, using legacy workers: %v", t.ID, err)
|
||||
slots, _ = ExpandWorkerSlots(nil, workerCountForTask(t, e.m.Workers()))
|
||||
}
|
||||
return slots
|
||||
}
|
||||
|
||||
// ReconcileWorkers applies the latest persisted settings without restarting a task.
|
||||
// Claims and retirement share the pool lock, so no retired slot takes new work.
|
||||
func (e *Engine) ReconcileWorkers(t *Task) {
|
||||
e.deleteMu.RLock()
|
||||
defer e.deleteMu.RUnlock()
|
||||
if e.IsDeleting(t.ID) {
|
||||
return
|
||||
}
|
||||
value, ok := e.workerPools.Load(t.ID)
|
||||
if !ok {
|
||||
return // queued/not started: Run will read the latest configuration
|
||||
}
|
||||
pool := value.(*taskWorkerPool)
|
||||
pool.mu.Lock()
|
||||
defer pool.mu.Unlock()
|
||||
if pool.runtime.ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
slots := e.desiredWorkerSlots(t)
|
||||
pool.desired = make(map[string]WorkerSlot, len(slots))
|
||||
for _, slot := range slots {
|
||||
pool.desired[slot.Name] = slot
|
||||
}
|
||||
for name, loop := range pool.loops {
|
||||
if slot, keep := pool.desired[name]; !keep || slot != loop.slot {
|
||||
loop.retire()
|
||||
}
|
||||
}
|
||||
for _, slot := range slots {
|
||||
if pool.loops[slot.Name] == nil {
|
||||
e.startWorkerSlotLocked(pool, slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ReconcileDefaultWorkers is called after a global workers/pool save. Explicit
|
||||
// task overrides keep both their concurrency and legacy task-router profiles.
|
||||
func (e *Engine) ReconcileDefaultWorkers() {
|
||||
e.workerPools.Range(func(_, value any) bool {
|
||||
t := value.(*taskWorkerPool).task
|
||||
if t.lifecycleSnapshot().WorkerCount == 0 {
|
||||
e.ReconcileWorkers(t)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
// WorkerCounts distinguishes live pool loops (including draining workers) from
|
||||
// the effective configured target. Neither count is the number of busy intents.
|
||||
func (e *Engine) WorkerCounts(t *Task) (actual, target int) {
|
||||
if value, ok := e.workerPools.Load(t.ID); ok {
|
||||
pool := value.(*taskWorkerPool)
|
||||
pool.mu.Lock()
|
||||
defer pool.mu.Unlock()
|
||||
return len(pool.loops), len(pool.desired)
|
||||
}
|
||||
return 0, len(e.desiredWorkerSlots(t))
|
||||
}
|
||||
|
||||
// Caller holds deleteMu.RLock and pool.mu. The delete barrier protects wg.Add
|
||||
// from StopTask.Wait, including replacements started as a retiree exits.
|
||||
func (e *Engine) startWorkerSlotLocked(pool *taskWorkerPool, slot WorkerSlot) {
|
||||
idleCtx, retire := context.WithCancel(pool.runtime.ctx)
|
||||
loop := &workerSlotRuntime{pool: pool, slot: slot, idleCtx: idleCtx, retire: retire}
|
||||
pool.loops[slot.Name] = loop
|
||||
// Publish a fresh immutable routing snapshot. Retired slot routes remain
|
||||
// available for human continuation of paused intents until the name is reused.
|
||||
plan := make(map[string]int64)
|
||||
if old, ok := e.slotPlans.Load(pool.task.ID); ok {
|
||||
for name, profile := range old.(map[string]int64) {
|
||||
plan[name] = profile
|
||||
}
|
||||
}
|
||||
plan[slot.Name] = slot.ProfileID
|
||||
e.slotPlans.Store(pool.task.ID, plan)
|
||||
pool.runtime.wg.Add(1)
|
||||
runTaskRoutine(pool.runtime, func(ctx context.Context) {
|
||||
defer e.finishWorkerSlot(loop)
|
||||
e.workerLoop(ctx, pool.task, slot, loop)
|
||||
})
|
||||
}
|
||||
|
||||
func (e *Engine) finishWorkerSlot(loop *workerSlotRuntime) {
|
||||
loop.retire()
|
||||
e.deleteMu.RLock()
|
||||
defer e.deleteMu.RUnlock()
|
||||
pool := loop.pool
|
||||
pool.mu.Lock()
|
||||
defer pool.mu.Unlock()
|
||||
delete(pool.loops, loop.slot.Name)
|
||||
e.slotState.Delete(pool.task.ID + "/" + loop.slot.Name)
|
||||
if !e.IsDeleting(pool.task.ID) && pool.runtime.ctx.Err() == nil {
|
||||
if slot, needed := pool.desired[loop.slot.Name]; needed {
|
||||
e.startWorkerSlotLocked(pool, slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"iter"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/norma/llm"
|
||||
)
|
||||
|
||||
type resizingCall struct {
|
||||
ctx context.Context
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
type resizingProvider struct{ calls chan resizingCall }
|
||||
|
||||
func (p *resizingProvider) Complete(ctx context.Context, _ llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
|
||||
call := resizingCall{ctx: ctx, release: make(chan struct{})}
|
||||
select {
|
||||
case p.calls <- call:
|
||||
case <-ctx.Done():
|
||||
return llm.Message{}, "", llm.Usage{}, ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-call.release:
|
||||
return llm.Message{Role: llm.RoleAssistant, Content: []llm.ContentBlock{llm.TextBlock("fixture completed")}}, "end_turn", llm.Usage{}, nil
|
||||
case <-ctx.Done():
|
||||
return llm.Message{}, "", llm.Usage{}, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
func (*resizingProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
|
||||
panic("resizing fixture uses non-streaming calls")
|
||||
}
|
||||
|
||||
func waitWorkerCondition(t *testing.T, condition func() bool) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if condition() {
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("timed out waiting for worker state")
|
||||
}
|
||||
|
||||
// Exercises the real worker claim/Execute/settlement path. Both slots remain
|
||||
// blocked in provider calls while shrinking; only the retained slot may claim
|
||||
// another intent, and re-expansion must reuse a name without overlapping loops.
|
||||
func TestWorkerHotResizeDrainsBeforeReusingSlot(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
task, err := m.CreateTask("resize workers", "fixture", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.DeleteTask(task.ID, DeleteTaskOptions{})
|
||||
count := 2
|
||||
if _, err := m.UpdateTaskMetadata(task.ID, db.TaskPatch{WorkerCount: &count}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
if _, err := task.Store.AddIntent(map[string]any{"text": "fixture"}, 0, nil, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
e := NewEngine(m)
|
||||
defer e.StopTask(task.ID)
|
||||
var mu sync.Mutex
|
||||
providers := make(map[string]*resizingProvider)
|
||||
e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) { return nil, nil })
|
||||
// Use a pinned pool so each slot's blocked call can be released independently.
|
||||
profileID, err := m.pg.SaveProfile(&db.LLMProfile{Name: "resize-fixture", Format: "openai", Model: "fixture"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.pg.DeleteProfile(profileID)
|
||||
oldPools, _, _ := m.pg.GetSetting(settingWorkerPools)
|
||||
oldWorkers, _, _ := m.pg.GetSetting(settingWorkers)
|
||||
defer m.pg.SetSetting(settingWorkerPools, oldPools)
|
||||
defer m.pg.SetSetting(settingWorkers, oldWorkers)
|
||||
count = 0
|
||||
if _, err := m.UpdateTaskMetadata(task.ID, db.TaskPatch{WorkerCount: &count}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
workDir := t.TempDir()
|
||||
e.SetWorkerResolver(func(_ *Task, slot WorkerSlot) (*agent.Worker, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p := providers[slot.Name]
|
||||
if p == nil {
|
||||
p = &resizingProvider{calls: make(chan resizingCall, 4)}
|
||||
providers[slot.Name] = p
|
||||
}
|
||||
w := agent.NewWorker(p, "fixture", workDir, nil, 0, 0)
|
||||
w.SetNonStreaming(func() bool { return true })
|
||||
return w, nil
|
||||
})
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 2}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.Run(t.Context(), task)
|
||||
getCall := func(name string) resizingCall {
|
||||
t.Helper()
|
||||
var p *resizingProvider
|
||||
waitWorkerCondition(t, func() bool {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
p = providers[name]
|
||||
return p != nil
|
||||
})
|
||||
select {
|
||||
case call := <-p.calls:
|
||||
return call
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s did not execute an intent", name)
|
||||
return resizingCall{}
|
||||
}
|
||||
}
|
||||
first, second := getCall("work#1"), getCall("work#2")
|
||||
thirdID, err := task.Store.AddIntent(map[string]any{"text": "next"}, 0, nil, "test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual, target := e.WorkerCounts(task); actual != 2 || target != 1 {
|
||||
t.Fatalf("draining counts=%d/%d, want 2/1", actual, target)
|
||||
}
|
||||
if second.ctx.Err() != nil || first.ctx.Err() != nil {
|
||||
t.Fatal("resize cancelled an executing intent")
|
||||
}
|
||||
close(second.release)
|
||||
waitWorkerCondition(t, func() bool { actual, target := e.WorkerCounts(task); return actual == 1 && target == 1 })
|
||||
third, err := task.Store.GetNode(thirdID)
|
||||
if err != nil || third.State != "open" {
|
||||
t.Fatalf("retired slot claimed queued intent: node=%+v err=%v", third, err)
|
||||
}
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 2}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
thirdCall := getCall("work#2")
|
||||
third, err = task.Store.GetNode(thirdID)
|
||||
if err != nil || third.State != "running" || third.Owner != "work#2" {
|
||||
t.Fatalf("expanded slot did not claim queued intent: node=%+v err=%v", third, err)
|
||||
}
|
||||
// A rapid shrink/grow must not start a duplicate work#2 while it drains.
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 2}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual, target := e.WorkerCounts(task); actual != 2 || target != 2 || thirdCall.ctx.Err() != nil {
|
||||
t.Fatalf("rapid resize interrupted work or duplicated slot: %d/%d err=%v", actual, target, thirdCall.ctx.Err())
|
||||
}
|
||||
close(thirdCall.release)
|
||||
close(first.release)
|
||||
waitWorkerCondition(t, func() bool {
|
||||
node, _ := task.Store.GetNode(thirdID)
|
||||
return node != nil && node.State != "running" && e.inflightCount(task.ID) == 0
|
||||
})
|
||||
}
|
||||
|
||||
func TestWorkerHotResizeTaskOverrideAndGlobalDefault(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
oldPools, _, _ := m.pg.GetSetting(settingWorkerPools)
|
||||
oldWorkers, _, _ := m.pg.GetSetting(settingWorkers)
|
||||
defer m.pg.SetSetting(settingWorkerPools, oldPools)
|
||||
defer m.pg.SetSetting(settingWorkers, oldWorkers)
|
||||
if err := m.SetWorkerPools(nil, 2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e := NewEngine(m)
|
||||
global, err := m.CreateTask("global resize fixture", "fixture", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.DeleteTask(global.ID, DeleteTaskOptions{})
|
||||
defer e.StopTask(global.ID)
|
||||
override, err := m.CreateTask("explicit resize fixture", "fixture", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.DeleteTask(override.ID, DeleteTaskOptions{})
|
||||
defer e.StopTask(override.ID)
|
||||
count := 3
|
||||
if _, err := m.UpdateTaskMetadata(override.ID, db.TaskPatch{WorkerCount: &count}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
e.Run(t.Context(), global)
|
||||
e.Run(t.Context(), override)
|
||||
if err := m.SetWorkers(4); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual, target := e.WorkerCounts(global); actual != 4 || target != 4 {
|
||||
t.Fatalf("global default did not expand: %d/%d", actual, target)
|
||||
}
|
||||
if actual, target := e.WorkerCounts(override); actual != 3 || target != 3 {
|
||||
t.Fatalf("global setting changed explicit override: %d/%d", actual, target)
|
||||
}
|
||||
if err := m.SetWorkers(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitWorkerCondition(t, func() bool { actual, target := e.WorkerCounts(global); return actual == 1 && target == 1 })
|
||||
if actual, target := e.WorkerCounts(override); actual != 3 || target != 3 {
|
||||
t.Fatalf("global shrink changed explicit override: %d/%d", actual, target)
|
||||
}
|
||||
// Exercise the live PATCH path, then restore global inheritance through PATCH.
|
||||
s := &Server{m: m, engine: e, ctx: t.Context()}
|
||||
patch := func(count int) {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/tasks/"+override.ID, strings.NewReader(fmt.Sprintf(`{"worker_count":%d}`, count)))
|
||||
req.SetPathValue("id", override.ID)
|
||||
rec := httptest.NewRecorder()
|
||||
s.updateTaskMetadata(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("live patch=%d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
patch(5)
|
||||
if actual, target := e.WorkerCounts(override); actual != 5 || target != 5 {
|
||||
t.Fatalf("task PATCH did not expand: %d/%d", actual, target)
|
||||
}
|
||||
patch(0)
|
||||
waitWorkerCondition(t, func() bool { actual, target := e.WorkerCounts(override); return actual == 1 && target == 1 })
|
||||
persisted, err := m.pg.GetTask(taskIDInt(t, override.ID))
|
||||
if err != nil || persisted.WorkerCount != 0 {
|
||||
t.Fatalf("inheritance not persisted: task=%+v err=%v", persisted, err)
|
||||
}
|
||||
// Reconstructing a task after restart must use the persisted override policy.
|
||||
restored := taskFromPG(persisted, override.Store, m.interceptor)
|
||||
if slots, err := workerSlotsForTask(restored, m.WorkerPools(), m.Workers()); err != nil || len(slots) != 1 {
|
||||
t.Fatalf("restored task lost concurrency policy: slots=%v err=%v", slots, err)
|
||||
}
|
||||
}
|
||||
@@ -416,3 +416,156 @@ func TestDeepenAdmissionFailureDiscardsFollowUpIntent(t *testing.T) {
|
||||
t.Fatalf("failed admission left an orphan audit: before=%d after=%d", activitiesBefore, activitiesAfter)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteFindingsValidation(t *testing.T) {
|
||||
s := &Server{}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
url string
|
||||
body string
|
||||
}{
|
||||
{name: "missing scope", url: "/api/exploration/findings", body: `{}`},
|
||||
{name: "empty body and query", url: "/api/exploration/findings", body: ""},
|
||||
{name: "bad scope", url: "/api/exploration/findings", body: `{"scope":"unknown"}`},
|
||||
{name: "selected without ids", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[]}`},
|
||||
{name: "selected bad string id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["abc"]}`},
|
||||
{name: "selected zero id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[0]}`},
|
||||
{name: "selected negative id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["-5"]}`},
|
||||
{name: "selected query bad id", url: "/api/exploration/findings?scope=selected&ids=1,bad", body: ""},
|
||||
{name: "invalid json", url: "/api/exploration/findings", body: `{`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
var body *strings.Reader
|
||||
if tc.body != "" {
|
||||
body = strings.NewReader(tc.body)
|
||||
}
|
||||
var req *http.Request
|
||||
if body != nil {
|
||||
req = httptest.NewRequest(http.MethodDelete, tc.url, body)
|
||||
} else {
|
||||
req = httptest.NewRequest(http.MethodDelete, tc.url, nil)
|
||||
}
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteFindingsEndpoint(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { m.Close() })
|
||||
|
||||
marker := fmt.Sprintf("__cleanup_endpoint_%d__", time.Now().UnixNano())
|
||||
task, err := m.CreateTask("cleanup endpoint test", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskID := mustTaskID(t, task.ID)
|
||||
t.Cleanup(func() {
|
||||
_, _ = m.pg.Exec(`DELETE FROM findings WHERE vulnclass=$1`, marker)
|
||||
_, _ = m.pg.Exec(`UPDATE tasks SET deleted_at=NULL WHERE id=$1`, taskID)
|
||||
_ = m.pg.DeleteTask(taskID)
|
||||
})
|
||||
|
||||
f1, err := m.pg.AddFinding(taskID, 0, marker, "first", db.SeverityHigh, "s1", "p1", "test", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f2, err := m.pg.AddFinding(taskID, 0, marker, "second", db.SeverityLow, "s2", "p2", "test", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f3, err := m.pg.AddFinding(0, 0, marker, "orphan", db.SeverityMedium, "s3", "p3", "test", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := &Server{m: m}
|
||||
|
||||
// Validation errors.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
url string
|
||||
body string
|
||||
}{
|
||||
{name: "missing scope", url: "/api/exploration/findings", body: `{}`},
|
||||
{name: "bad scope", url: "/api/exploration/findings", body: `{"scope":"unknown"}`},
|
||||
{name: "selected without ids", url: "/api/exploration/findings", body: `{"scope":"selected","ids":[]}`},
|
||||
{name: "selected bad id", url: "/api/exploration/findings", body: `{"scope":"selected","ids":["abc"]}`},
|
||||
{name: "invalid json", url: "/api/exploration/findings", body: `{`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodDelete, tc.url, strings.NewReader(tc.body))
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Selected delete via JSON body (string id).
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
|
||||
strings.NewReader(fmt.Sprintf(`{"scope":"selected","ids":["%d"]}`, f1)))
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("selected delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Deleted int64 `json:"deleted"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
|
||||
t.Fatalf("selected delete resp=%s err=%v", rec.Body.String(), err)
|
||||
}
|
||||
|
||||
// Filtered delete via JSON body filters (unassigned only).
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
|
||||
strings.NewReader(fmt.Sprintf(`{"scope":"filtered","filters":{"vulnclass":%q,"task_id":%q}}`, marker, db.FindingUnassignedTask)))
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("filtered delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
|
||||
t.Fatalf("filtered delete resp=%s err=%v", rec.Body.String(), err)
|
||||
}
|
||||
if got, _ := m.pg.GetFinding(f3); got != nil {
|
||||
t.Fatalf("f3 should have been deleted")
|
||||
}
|
||||
|
||||
// Archive-state conflict returns 409.
|
||||
if _, err := m.pg.Exec(`UPDATE tasks SET deleted_at=now() WHERE id=$1`, taskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings",
|
||||
strings.NewReader(fmt.Sprintf(`{"scope":"selected","ids":[%d]}`, f2)))
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusConflict {
|
||||
t.Fatalf("archive conflict status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := m.pg.Exec(`UPDATE tasks SET deleted_at=NULL WHERE id=$1`, taskID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Query-string fallback for filtered cleanup.
|
||||
rec = httptest.NewRecorder()
|
||||
req = httptest.NewRequest(http.MethodDelete, "/api/exploration/findings?scope=filtered&vulnclass="+marker, nil)
|
||||
s.deleteFindings(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("query filtered delete status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil || resp.Deleted != 1 {
|
||||
t.Fatalf("query filtered delete resp=%s err=%v", rec.Body.String(), err)
|
||||
}
|
||||
if got, _ := m.pg.GetFinding(f2); got != nil {
|
||||
t.Fatalf("f2 should have been deleted")
|
||||
}
|
||||
}
|
||||
+55
-19
@@ -99,6 +99,7 @@ type Task struct {
|
||||
// directly after the task has been published by Manager.
|
||||
type taskLifecycleState struct {
|
||||
ShareGlobalAssets bool
|
||||
WorkerCount int
|
||||
Name string
|
||||
Remark string
|
||||
PinnedAt int64
|
||||
@@ -140,6 +141,7 @@ func (t *Task) lifecycleSnapshot() taskLifecycleState {
|
||||
func (t *Task) lifecycleSnapshotLocked() taskLifecycleState {
|
||||
return taskLifecycleState{
|
||||
ShareGlobalAssets: t.ShareGlobalAssets,
|
||||
WorkerCount: t.WorkerCount,
|
||||
Name: t.Name,
|
||||
Remark: t.Remark,
|
||||
PinnedAt: t.PinnedAt,
|
||||
@@ -171,6 +173,7 @@ func (t *Task) updateLifecycle(update func(*taskLifecycleState)) {
|
||||
state := t.lifecycleSnapshotLocked()
|
||||
update(&state)
|
||||
t.ShareGlobalAssets = state.ShareGlobalAssets
|
||||
t.WorkerCount = state.WorkerCount
|
||||
t.Name = state.Name
|
||||
t.Remark = state.Remark
|
||||
t.PinnedAt = state.PinnedAt
|
||||
@@ -282,13 +285,14 @@ type Manager struct {
|
||||
// taskStateMu preserves commit order between PostgreSQL lifecycle writes and
|
||||
// their in-memory mirrors. lifecycleMu makes snapshots race-free, but without
|
||||
// this outer write lock an older request could commit first and publish last.
|
||||
taskStateMu sync.Mutex
|
||||
controlMu *sync.Mutex // Server's admission/task-control mutex, when attached.
|
||||
mu sync.RWMutex
|
||||
tasks map[string]*Task
|
||||
active string
|
||||
trafficOn bool // 流量捕获开关(默认关;settings.traffic_capture)
|
||||
llmRecOn bool // LLM 录制开关(默认关;settings.llm_record)
|
||||
taskStateMu sync.Mutex
|
||||
controlMu *sync.Mutex // Server's admission/task-control mutex, when attached.
|
||||
mu sync.RWMutex
|
||||
tasks map[string]*Task
|
||||
workerConfigChanged func()
|
||||
active string
|
||||
trafficOn bool // 流量捕获开关(默认关;settings.traffic_capture)
|
||||
llmRecOn bool // LLM 录制开关(默认关;settings.llm_record)
|
||||
// 联网搜索开关与来源(默认关;settings.web_search_*)。brave-free 需要 braveKey;tavily 需要 tavilyKey。
|
||||
// webSearchProxy 是独立出口代理(http/https/socks5),与记录流量的 MITM 代理无关。
|
||||
webSearchOn bool
|
||||
@@ -310,6 +314,23 @@ type Manager struct {
|
||||
// participate in the Server's admission/task-control critical section.
|
||||
func (m *Manager) SetTaskControlMutex(mu *sync.Mutex) { m.controlMu = mu }
|
||||
|
||||
// SetWorkerConfigChangedCallback installs the engine's live worker reconciler.
|
||||
// Successful worker-setting writes invoke it after releasing Manager locks.
|
||||
func (m *Manager) SetWorkerConfigChangedCallback(callback func()) {
|
||||
m.mu.Lock()
|
||||
m.workerConfigChanged = callback
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) notifyWorkerConfigChanged() {
|
||||
m.mu.RLock()
|
||||
callback := m.workerConfigChanged
|
||||
m.mu.RUnlock()
|
||||
if callback != nil {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
// Settings keys the UI toggles at runtime.
|
||||
const (
|
||||
settingTrafficCapture = "traffic_capture"
|
||||
@@ -433,6 +454,9 @@ func ExpandWorkerSlots(pools []WorkerPool, legacy int) ([]WorkerSlot, error) {
|
||||
if legacy <= 0 {
|
||||
legacy = defaultWorkers
|
||||
}
|
||||
if legacy > pgdb.MaxTaskWorkerCount {
|
||||
legacy = pgdb.MaxTaskWorkerCount
|
||||
}
|
||||
slots := make([]WorkerSlot, legacy)
|
||||
for i := range slots {
|
||||
slots[i] = WorkerSlot{Name: fmt.Sprintf("work#%d", i+1)}
|
||||
@@ -478,8 +502,8 @@ func (m *Manager) SetConcurrency(enabled bool, limit int) error {
|
||||
return m.pg.SetSetting(settingConcurrencyOn, strconv.FormatBool(enabled))
|
||||
}
|
||||
|
||||
// Workers returns the configured concurrent work-agent count (default 3). Read
|
||||
// per-task at engine.Run, so a change applies to tasks started afterwards.
|
||||
// Workers returns the configured concurrent work-agent count (default 3),
|
||||
// capped at the supported maximum even for settings saved by older versions.
|
||||
func (m *Manager) Workers() int {
|
||||
v, ok, err := m.pg.GetSetting(settingWorkers)
|
||||
if err != nil || !ok {
|
||||
@@ -489,6 +513,9 @@ func (m *Manager) Workers() int {
|
||||
if err != nil || n <= 0 {
|
||||
return defaultWorkers
|
||||
}
|
||||
if n > pgdb.MaxTaskWorkerCount {
|
||||
return pgdb.MaxTaskWorkerCount
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
@@ -542,23 +569,31 @@ func (m *Manager) SetWorkerPools(pools []WorkerPool, legacyWorkers ...int) error
|
||||
workerCount += pool.Workers
|
||||
}
|
||||
} else if len(legacyWorkers) > 0 {
|
||||
if legacyWorkers[0] <= 0 {
|
||||
return fmt.Errorf("workers 必须 >0")
|
||||
if legacyWorkers[0] <= 0 || legacyWorkers[0] > pgdb.MaxTaskWorkerCount {
|
||||
return fmt.Errorf("workers 必须在 1 到 %d 之间", pgdb.MaxTaskWorkerCount)
|
||||
}
|
||||
workerCount = legacyWorkers[0]
|
||||
}
|
||||
return m.pg.SetSettingsAtomic(context.Background(), map[string]string{
|
||||
if err := m.pg.SetSettingsAtomic(context.Background(), map[string]string{
|
||||
settingWorkerPools: string(b),
|
||||
settingWorkers: strconv.Itoa(workerCount),
|
||||
})
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
m.notifyWorkerConfigChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetWorkers persists the concurrent work-agent count. Values <=0 are rejected.
|
||||
// SetWorkers persists the concurrent work-agent count and reconciles live tasks.
|
||||
func (m *Manager) SetWorkers(n int) error {
|
||||
if n <= 0 {
|
||||
return fmt.Errorf("workers 必须 >0")
|
||||
if n <= 0 || n > pgdb.MaxTaskWorkerCount {
|
||||
return fmt.Errorf("workers 必须在 1 到 %d 之间", pgdb.MaxTaskWorkerCount)
|
||||
}
|
||||
return m.pg.SetSetting(settingWorkers, strconv.Itoa(n))
|
||||
if err := m.pg.SetSetting(settingWorkers, strconv.Itoa(n)); err != nil {
|
||||
return err
|
||||
}
|
||||
m.notifyWorkerConfigChanged()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Enrich returns the asset auto-completion engine (may be nil if init failed).
|
||||
@@ -1179,8 +1214,8 @@ func taskFromPG(pt *pgdb.Task, store *pgdb.ExplorationStore, ic *intercept.Inter
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateTaskMetadata changes task metadata and asset visibility without interrupting any
|
||||
// planner, main-agent, or worker call.
|
||||
// UpdateTaskMetadata changes task metadata, asset visibility, and worker policy
|
||||
// without interrupting any planner, main-agent, or worker call.
|
||||
func (m *Manager) UpdateTaskMetadata(taskID string, patch pgdb.TaskPatch) (*Task, error) {
|
||||
m.taskStateMu.Lock()
|
||||
defer m.taskStateMu.Unlock()
|
||||
@@ -1200,6 +1235,7 @@ func (m *Manager) UpdateTaskMetadata(taskID string, patch pgdb.TaskPatch) (*Task
|
||||
}
|
||||
task.updateLifecycle(func(state *taskLifecycleState) {
|
||||
state.ShareGlobalAssets = updated.ShareGlobalAssets
|
||||
state.WorkerCount = updated.WorkerCount
|
||||
state.Name = updated.Name
|
||||
state.Remark = updated.Remark
|
||||
state.PinnedAt = unixOrZero(updated.PinnedAt)
|
||||
|
||||
@@ -55,6 +55,7 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) {
|
||||
state.CompletedAt = generation
|
||||
state.FirstRunAt = generation
|
||||
state.DeadlineAt = generation
|
||||
state.WorkerCount = int(generation % 51)
|
||||
state.SourceTaskIDs = []int64{generation, generation + 1}
|
||||
state.CompanyIDs = []int64{generation, generation + 1}
|
||||
})
|
||||
@@ -93,7 +94,7 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) {
|
||||
}
|
||||
generation := state.QueuedAt
|
||||
if state.CompletedAt != generation || state.FirstRunAt != generation || state.DeadlineAt != generation ||
|
||||
len(state.SourceTaskIDs) != 2 || len(state.CompanyIDs) != 2 ||
|
||||
state.WorkerCount != int(generation%51) || len(state.SourceTaskIDs) != 2 || len(state.CompanyIDs) != 2 ||
|
||||
state.SourceTaskIDs[0] != generation || state.CompanyIDs[0] != generation {
|
||||
errCh <- fmt.Errorf("mixed lifecycle snapshot: %+v", state)
|
||||
return
|
||||
@@ -107,3 +108,19 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskLifecycleWorkerCountSnapshot(t *testing.T) {
|
||||
task := &Task{WorkerCount: 2}
|
||||
if got := taskDTO(task, "created").WorkerCount; got != 2 {
|
||||
t.Fatalf("DTO worker_count=%d, want 2", got)
|
||||
}
|
||||
task.updateLifecycle(func(state *taskLifecycleState) {
|
||||
state.WorkerCount = 7
|
||||
})
|
||||
if got := task.lifecycleSnapshot().WorkerCount; got != 7 {
|
||||
t.Fatalf("snapshot worker_count=%d, want 7", got)
|
||||
}
|
||||
if got := taskDTO(task, "created").WorkerCount; got != 7 {
|
||||
t.Fatalf("DTO worker_count=%d, want 7", got)
|
||||
}
|
||||
}
|
||||
+127
-8
@@ -104,15 +104,14 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, "url 必填")
|
||||
return
|
||||
}
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil || u.Host == "" || u.Hostname() == "" ||
|
||||
!strings.EqualFold(u.Scheme, "http") && !strings.EqualFold(u.Scheme, "https") {
|
||||
target, err := parseRepeaterURL(rawURL)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "仅支持绝对 http/https URL")
|
||||
return
|
||||
}
|
||||
// This check is needed even when a proxy is used: the proxy must remain usable
|
||||
// for normal targets, while obvious literal metadata/loopback URLs stay blocked.
|
||||
if err := repeaterCheckURL(u); err != nil {
|
||||
if err := repeaterCheckURL(target.origin); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
@@ -138,11 +137,12 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeoutMs)*time.Millisecond)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, method, u.String(), body)
|
||||
req, err := http.NewRequestWithContext(ctx, method, target.origin.String(), body)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "构造请求失败")
|
||||
return
|
||||
}
|
||||
req.URL = target.requestURL()
|
||||
httpidentity.Apply(req)
|
||||
for key, value := range in.Headers {
|
||||
name := strings.TrimSpace(key)
|
||||
@@ -180,7 +180,15 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
|
||||
tr.Protocols = new(http.Protocols)
|
||||
tr.Protocols.SetHTTP1(in.HTTPVersion == "HTTP/1.1")
|
||||
tr.Protocols.SetHTTP2(in.HTTPVersion == "HTTP/2.0")
|
||||
tr.Protocols.SetUnencryptedHTTP2(in.HTTPVersion == "HTTP/2.0" && strings.EqualFold(u.Scheme, "http"))
|
||||
tr.Protocols.SetUnencryptedHTTP2(in.HTTPVersion == "HTTP/2.0" && strings.EqualFold(target.origin.Scheme, "http"))
|
||||
}
|
||||
if target.needsOpaque && strings.EqualFold(req.URL.Scheme, "http") {
|
||||
if tr, ok := transport.(*http.Transport); ok && tr.Proxy != nil {
|
||||
if proxyURL, perr := tr.Proxy(req); perr == nil && proxyURL != nil &&
|
||||
(strings.EqualFold(proxyURL.Scheme, "http") || strings.EqualFold(proxyURL.Scheme, "https")) {
|
||||
req.URL.Opaque = "//" + req.URL.Host + target.rawPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
@@ -207,16 +215,20 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, repeaterSendResponse{
|
||||
Headers: map[string][]string{}, URL: u.String(),
|
||||
Headers: map[string][]string{}, URL: target.displayURL,
|
||||
ElapsedMs: time.Since(started).Milliseconds(), Error: repeaterRedactError(err),
|
||||
})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respURL := target.displayURL
|
||||
if resp.Request != nil && resp.Request.URL != nil && resp.Request.URL.Opaque == "" {
|
||||
respURL = resp.Request.URL.String()
|
||||
}
|
||||
out := repeaterSendResponse{
|
||||
Status: resp.StatusCode, StatusText: resp.Status, Proto: resp.Proto,
|
||||
Headers: resp.Header.Clone(), URL: resp.Request.URL.String(),
|
||||
Headers: resp.Header.Clone(), URL: respURL,
|
||||
}
|
||||
if method != http.MethodHead {
|
||||
// Read one byte beyond the cap so truncation is exact. The MVP keeps the
|
||||
@@ -236,6 +248,113 @@ func (s *Server) sendRepeater(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
type repeaterTargetURL struct {
|
||||
origin *url.URL
|
||||
parsed *url.URL
|
||||
rawPath string
|
||||
rawQuery string
|
||||
forceQuery bool
|
||||
needsOpaque bool
|
||||
displayURL string
|
||||
}
|
||||
|
||||
func (t *repeaterTargetURL) requestURL() *url.URL {
|
||||
if !t.needsOpaque {
|
||||
u := *t.parsed
|
||||
return &u
|
||||
}
|
||||
u := *t.origin
|
||||
u.Path = ""
|
||||
u.RawPath = ""
|
||||
u.RawQuery = t.rawQuery
|
||||
u.ForceQuery = t.forceQuery
|
||||
u.Opaque = t.rawPath
|
||||
return &u
|
||||
}
|
||||
|
||||
// parseRepeaterURL validates the scheme and authority while preserving the raw
|
||||
// request-target (path and query). Normal targets keep Opaque empty so net/http
|
||||
// handles proxies, redirects and HTTP/2 natively; Opaque is only engaged when
|
||||
// rawPath contains characters that net/url would percent-encode or reject.
|
||||
func parseRepeaterURL(rawURL string) (*repeaterTargetURL, error) {
|
||||
for i := range len(rawURL) {
|
||||
if rawURL[i] < 0x20 || rawURL[i] == 0x7f {
|
||||
return nil, errors.New("control character in URL")
|
||||
}
|
||||
}
|
||||
schemeSep := strings.Index(rawURL, "://")
|
||||
if schemeSep <= 0 {
|
||||
return nil, errors.New("missing scheme")
|
||||
}
|
||||
scheme := rawURL[:schemeSep]
|
||||
if !strings.EqualFold(scheme, "http") && !strings.EqualFold(scheme, "https") {
|
||||
return nil, errors.New("unsupported scheme")
|
||||
}
|
||||
afterScheme := rawURL[schemeSep+3:]
|
||||
restIdx := strings.IndexAny(afterScheme, "/?#")
|
||||
authority, rest := afterScheme, ""
|
||||
if restIdx >= 0 {
|
||||
authority, rest = afterScheme[:restIdx], afterScheme[restIdx:]
|
||||
}
|
||||
if authority == "" || strings.Contains(authority, "\\") {
|
||||
return nil, errors.New("invalid authority")
|
||||
}
|
||||
origin, err := url.Parse(rawURL[:schemeSep+3+len(authority)])
|
||||
if err != nil || origin.Host == "" || origin.Hostname() == "" ||
|
||||
(!strings.EqualFold(origin.Scheme, "http") && !strings.EqualFold(origin.Scheme, "https")) {
|
||||
return nil, errors.New("invalid origin")
|
||||
}
|
||||
|
||||
beforeHash := rest
|
||||
if hash := strings.IndexByte(beforeHash, '#'); hash >= 0 {
|
||||
beforeHash = beforeHash[:hash]
|
||||
}
|
||||
rawPath, rawQuery := beforeHash, ""
|
||||
hasQuery := false
|
||||
if q := strings.IndexByte(beforeHash, '?'); q >= 0 {
|
||||
rawPath = beforeHash[:q]
|
||||
rawQuery = beforeHash[q+1:]
|
||||
hasQuery = true
|
||||
}
|
||||
if rawPath == "" {
|
||||
rawPath = "/"
|
||||
}
|
||||
|
||||
u, parseErr := url.Parse(rawURL)
|
||||
needsOpaque := false
|
||||
if parseErr != nil {
|
||||
if strings.HasPrefix(rawPath, "//") {
|
||||
return nil, parseErr
|
||||
}
|
||||
needsOpaque = true
|
||||
} else {
|
||||
escapedPath := u.EscapedPath()
|
||||
if escapedPath == "" {
|
||||
escapedPath = "/"
|
||||
}
|
||||
if escapedPath != rawPath && !strings.HasPrefix(rawPath, "//") {
|
||||
needsOpaque = true
|
||||
}
|
||||
}
|
||||
|
||||
displayURL := origin.String() + rawPath
|
||||
if hasQuery {
|
||||
displayURL += "?" + rawQuery
|
||||
}
|
||||
if !needsOpaque {
|
||||
displayURL = u.String()
|
||||
}
|
||||
return &repeaterTargetURL{
|
||||
origin: origin,
|
||||
parsed: u,
|
||||
rawPath: rawPath,
|
||||
rawQuery: rawQuery,
|
||||
forceQuery: hasQuery && rawQuery == "",
|
||||
needsOpaque: needsOpaque,
|
||||
displayURL: displayURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// repeaterBodyText keeps the response preview as text for the MVP. Invalid
|
||||
// UTF-8 and NUL bytes are replaced so a binary response cannot inject control
|
||||
// characters into the JSON/UI raw view; the original bytes are not base64
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
@@ -440,3 +441,143 @@ func TestRepeaterExplicitHTTP2Cleartext(t *testing.T) {
|
||||
t.Fatalf("status=%d response=%s", code, raw)
|
||||
}
|
||||
}
|
||||
|
||||
func startRawWireCaptureServer(t *testing.T) (string, <-chan string) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = ln.Close() })
|
||||
lines := make(chan string, 16)
|
||||
go func() {
|
||||
for {
|
||||
conn, err := ln.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func(c net.Conn) {
|
||||
defer c.Close()
|
||||
r := bufio.NewReader(c)
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for {
|
||||
h, err := r.ReadString('\n')
|
||||
if err != nil || h == "\r\n" || h == "\n" {
|
||||
break
|
||||
}
|
||||
}
|
||||
lines <- strings.TrimRight(line, "\r\n")
|
||||
_, _ = c.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"))
|
||||
}(conn)
|
||||
}
|
||||
}()
|
||||
return ln.Addr().String(), lines
|
||||
}
|
||||
|
||||
func TestRepeaterPreservesRawRequestTarget(t *testing.T) {
|
||||
t.Setenv(repeaterAllowLocalEnv, "1")
|
||||
addr, wireLines := startRawWireCaptureServer(t)
|
||||
|
||||
cases := []string{
|
||||
"/item?id=1'",
|
||||
"/item?id=1'\"><`{}|\\",
|
||||
"/a/../b/./c?id=1'",
|
||||
"/a/%2e%2e/b?x='",
|
||||
"//a//b?c=1'",
|
||||
"/a\\b?id=1'",
|
||||
"/a\"b?id=1'",
|
||||
"/a%zz/b?id=1'",
|
||||
}
|
||||
for _, target := range cases {
|
||||
t.Run("h1-direct/"+target, func(t *testing.T) {
|
||||
rawURL := "http://" + addr + target
|
||||
code, out, body := repeaterTestSend(t, &Server{}, map[string]any{
|
||||
"method": "GET", "url": rawURL, "use_recording_proxy": false,
|
||||
})
|
||||
if code != http.StatusOK || out.Error != "" || out.Status != http.StatusOK {
|
||||
t.Fatalf("status=%d out=%+v body=%s", code, out, body)
|
||||
}
|
||||
if out.URL != rawURL {
|
||||
t.Fatalf("response url=%q want %q", out.URL, rawURL)
|
||||
}
|
||||
select {
|
||||
case got := <-wireLines:
|
||||
want := "GET " + target + " HTTP/1.1"
|
||||
if got != want {
|
||||
t.Fatalf("wire request line=%q want %q", got, want)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("timed out waiting for wire request line")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Plain HTTP through an HTTP proxy must retain proxy-form absolute URI for both normal and opaque raw paths.
|
||||
proxyAddr, proxyLines := startRawWireCaptureServer(t)
|
||||
proxiedServer := &Server{m: &Manager{globalProxy: "http://" + proxyAddr}}
|
||||
for _, target := range []string{"/item?id=1'", "/a\\b?id=1'"} {
|
||||
t.Run("h1-proxy/"+target, func(t *testing.T) {
|
||||
rawURL := "http://target.example" + target
|
||||
code, out, body := repeaterTestSend(t, proxiedServer, map[string]any{
|
||||
"method": "GET", "url": rawURL, "use_recording_proxy": false,
|
||||
})
|
||||
if code != http.StatusOK || out.Error != "" || out.Status != http.StatusOK {
|
||||
t.Fatalf("status=%d out=%+v body=%s", code, out, body)
|
||||
}
|
||||
select {
|
||||
case got := <-proxyLines:
|
||||
want := "GET " + rawURL + " HTTP/1.1"
|
||||
if got != want {
|
||||
t.Fatalf("proxy request line=%q want %q", got, want)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("timed out waiting for proxy request line")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// HTTP/2 must also preserve raw query and path targets verbatim.
|
||||
h2srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.WriteString(w, r.RequestURI)
|
||||
}))
|
||||
h2srv.EnableHTTP2 = true
|
||||
h2srv.TLS = &tls.Config{NextProtos: []string{"h2"}}
|
||||
h2srv.StartTLS()
|
||||
defer h2srv.Close()
|
||||
for _, target := range []string{"/item?id=1'", "/a/../b?x='", "/a\\b?id=1'"} {
|
||||
t.Run("h2-direct/"+target, func(t *testing.T) {
|
||||
rawURL := h2srv.URL + target
|
||||
code, out, body := repeaterTestSend(t, &Server{}, map[string]any{
|
||||
"method": "GET", "url": rawURL, "http_version": "HTTP/2.0",
|
||||
"insecure_skip_verify": true, "use_recording_proxy": false,
|
||||
})
|
||||
if code != http.StatusOK || out.Error != "" || out.Body != target {
|
||||
t.Fatalf("h2 status=%d body=%q raw=%s", code, out.Body, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepeaterRawURLValidationAndSSRFGuard(t *testing.T) {
|
||||
t.Setenv(repeaterAllowLocalEnv, "")
|
||||
s := &Server{}
|
||||
for _, bad := range []string{
|
||||
"http://example.test\\evil/path",
|
||||
"http://example.test/a\nb",
|
||||
"http://example.test:abc/path",
|
||||
} {
|
||||
code, _, body := repeaterTestSend(t, s, map[string]any{"url": bad, "use_recording_proxy": false})
|
||||
if code != http.StatusBadRequest {
|
||||
t.Fatalf("url=%q status=%d want 400 body=%s", bad, code, body)
|
||||
}
|
||||
}
|
||||
code, _, body := repeaterTestSend(t, s, map[string]any{
|
||||
"url": "http://127.0.0.1/a\\b?id=1'", "use_recording_proxy": false,
|
||||
})
|
||||
if code != http.StatusBadRequest || !strings.Contains(body, "拒绝") {
|
||||
t.Fatalf("opaque loopback status=%d body=%s", code, body)
|
||||
}
|
||||
}
|
||||
+122
-6
@@ -933,6 +933,7 @@ func (s *Server) Handler() http.Handler {
|
||||
|
||||
mux.HandleFunc("GET /api/exploration/frontier", s.frontier)
|
||||
mux.HandleFunc("GET /api/exploration/findings", s.findings)
|
||||
mux.HandleFunc("DELETE /api/exploration/findings", s.deleteFindings)
|
||||
mux.HandleFunc("GET /api/exploration/findings/groups", s.findingGroups)
|
||||
mux.HandleFunc("GET /api/exploration/finding-cases", s.listFindingCases)
|
||||
mux.HandleFunc("POST /api/exploration/finding-cases", s.mergeFindingCase)
|
||||
@@ -1285,6 +1286,7 @@ func (s *Server) listTasks(w http.ResponseWriter, r *http.Request) {
|
||||
dtos := make([]TaskDTO, 0, len(list))
|
||||
for _, t := range list {
|
||||
dto := taskDTO(t, s.resolvedTaskStatus(t))
|
||||
dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t)
|
||||
applyTaskArchiveBlocker(&dto, archiveBlockers)
|
||||
metric := metrics[t.ExpID]
|
||||
dto.Tokens = tokenTotalDTO(metric.Tokens)
|
||||
@@ -2068,6 +2070,7 @@ func (s *Server) getTask(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
dto := taskDTO(t, s.resolvedTaskStatus(t))
|
||||
dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(t)
|
||||
archiveBlockers, _ := s.m.PG().TaskArchiveBlockers()
|
||||
applyTaskArchiveBlocker(&dto, archiveBlockers)
|
||||
writeJSON(w, 200, dto)
|
||||
@@ -2726,6 +2729,123 @@ func (s *Server) deleteFinding(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"deleted": true, "id": id})
|
||||
}
|
||||
|
||||
// deleteFindings bulk-deletes findings according to scope:
|
||||
// - scope="all": delete all findings
|
||||
// - scope="filtered": delete findings matching the shared FindingFilter fields
|
||||
// - scope="selected": delete findings listed in ids (required, positive int64)
|
||||
//
|
||||
// Accepts a JSON body (preferred for large id lists) or query parameters.
|
||||
func (s *Server) deleteFindings(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Scope string `json:"scope"`
|
||||
IDs []json.RawMessage `json:"ids"`
|
||||
Filters *struct {
|
||||
Severity string `json:"severity"`
|
||||
Status string `json:"status"`
|
||||
VulnClass string `json:"vulnclass"`
|
||||
TaskID string `json:"task_id"`
|
||||
Query string `json:"q"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
AssetScope string `json:"asset_scope"`
|
||||
} `json:"filters"`
|
||||
}
|
||||
if r.Body != nil && r.Body != http.NoBody && r.ContentLength != 0 {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil && !errors.Is(err, io.EOF) {
|
||||
writeErr(w, 400, "invalid body")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
scope := strings.TrimSpace(req.Scope)
|
||||
if scope == "" {
|
||||
scope = strings.TrimSpace(q.Get("scope"))
|
||||
}
|
||||
|
||||
var (
|
||||
ids []int64
|
||||
filter db.FindingFilter
|
||||
)
|
||||
switch scope {
|
||||
case "selected":
|
||||
if len(req.IDs) > 0 {
|
||||
for _, raw := range req.IDs {
|
||||
var (
|
||||
id int64
|
||||
str string
|
||||
)
|
||||
if err := json.Unmarshal(raw, &id); err != nil {
|
||||
if err2 := json.Unmarshal(raw, &str); err2 != nil {
|
||||
writeErr(w, 400, "bad finding id")
|
||||
return
|
||||
}
|
||||
parsed, err2 := strconv.ParseInt(strings.TrimSpace(str), 10, 64)
|
||||
if err2 != nil {
|
||||
writeErr(w, 400, "bad finding id: "+str)
|
||||
return
|
||||
}
|
||||
id = parsed
|
||||
}
|
||||
if id <= 0 {
|
||||
writeErr(w, 400, "bad finding id")
|
||||
return
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
} else {
|
||||
for _, part := range strings.Split(q.Get("ids"), ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
id, err := strconv.ParseInt(part, 10, 64)
|
||||
if err != nil || id <= 0 {
|
||||
writeErr(w, 400, "bad finding id: "+part)
|
||||
return
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
writeErr(w, 400, "no findings selected")
|
||||
return
|
||||
}
|
||||
case "all":
|
||||
// Empty filter deletes every finding in the standalone findings table.
|
||||
case "filtered":
|
||||
if req.Filters != nil {
|
||||
filter = db.FindingFilter{
|
||||
Severity: normFilter(req.Filters.Severity),
|
||||
Status: normFilter(req.Filters.Status),
|
||||
VulnClass: normFilter(req.Filters.VulnClass),
|
||||
TaskID: normFilter(req.Filters.TaskID),
|
||||
Query: req.Filters.Query,
|
||||
From: strings.TrimSpace(req.Filters.From),
|
||||
To: strings.TrimSpace(req.Filters.To),
|
||||
AssetScope: strings.TrimSpace(req.Filters.AssetScope),
|
||||
}
|
||||
} else {
|
||||
filter = findingFilterFromQuery(q)
|
||||
}
|
||||
default:
|
||||
writeErr(w, 400, "bad scope: "+scope)
|
||||
return
|
||||
}
|
||||
|
||||
n, err := s.m.pg.DeleteFindings(r.Context(), filter, ids)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrTaskArchiveState) {
|
||||
writeErr(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"deleted": n})
|
||||
}
|
||||
|
||||
func (s *Server) intents(w http.ResponseWriter, r *http.Request) {
|
||||
t := s.m.ResolveTask(r.URL.Query().Get("task"))
|
||||
if t == nil {
|
||||
@@ -3740,7 +3860,7 @@ func (s *Server) settingsPayload() map[string]any {
|
||||
"show_egress_ip": s.m.pg.GetBool(settingShowEgressIP, false),
|
||||
"egress_probe_url": s.m.EgressProbeURL(),
|
||||
"python_interpreter": strings.TrimSpace(pyStored), // 用户/自动设的值(空=用运行时检测)
|
||||
"workers": s.m.Workers(), // 并发工作 agent 数(默认3);对之后启动的任务生效
|
||||
"workers": s.m.Workers(), // 并发工作 agent 数(默认3);实时更新使用全局默认的任务
|
||||
"worker_pools": s.m.WorkerPools(), // 非空时按池顺序绑定 worker 会话
|
||||
"task_concurrency_enabled": concOn, // 任务并发上限开关(默认关)
|
||||
"task_concurrency_limit": concLimit, // 同时运行任务上限(开启后默认5)
|
||||
@@ -3833,7 +3953,7 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
ShowEgressIP *bool `json:"show_egress_ip"` // 在顶栏显示直连/全局代理出口 IP;默认关
|
||||
EgressProbeURL *string `json:"egress_probe_url"` // null=不改;空串=默认公共探测服务
|
||||
PythonInterp *string `json:"python_interpreter"` // 自定义脚本工具的 python 解释器路径
|
||||
Workers *int `json:"workers"` // 并发工作 agent 数(>0);对之后启动的任务生效
|
||||
Workers *int `json:"workers"` // 并发工作 agent 数(1..50);实时更新使用全局默认的任务
|
||||
WorkerPools *[]WorkerPool `json:"worker_pools"`
|
||||
// 任务并发上限:同时「运行中」的任务数上限。关闭=不限;开启后新建任务超限则排队,有空位自动启动。
|
||||
ConcurrencyEnabled *bool `json:"task_concurrency_enabled"`
|
||||
@@ -3923,10 +4043,6 @@ func (s *Server) putSettings(w http.ResponseWriter, r *http.Request) {
|
||||
// synchronizes workers to its total. An empty list clears pools; when workers
|
||||
// is also present it sets the legacy count for the newly restored legacy mode.
|
||||
if req.WorkerPools != nil {
|
||||
if len(*req.WorkerPools) == 0 && req.Workers != nil && *req.Workers <= 0 {
|
||||
writeErr(w, 400, "workers 必须 >0")
|
||||
return
|
||||
}
|
||||
legacyWorkers := []int(nil)
|
||||
if req.Workers != nil {
|
||||
legacyWorkers = []int{*req.Workers}
|
||||
|
||||
+15
-5
@@ -15,7 +15,7 @@ const (
|
||||
maxTaskMetadataRequestSize = 16 << 10
|
||||
)
|
||||
|
||||
// updateTaskMetadata updates editable metadata and the live asset-sharing policy.
|
||||
// updateTaskMetadata updates editable metadata and live task policies.
|
||||
func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
taskID := r.PathValue("id")
|
||||
if _, ok := s.m.Task(taskID); !ok {
|
||||
@@ -28,6 +28,7 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
Remark *string `json:"remark"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
ShareGlobalAssets *bool `json:"share_global_assets"`
|
||||
WorkerCount *int `json:"worker_count"`
|
||||
}
|
||||
if err := decode(r, &request); err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
@@ -38,8 +39,12 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
return
|
||||
}
|
||||
if request.Name == nil && request.Pinned == nil && request.Remark == nil && request.ShareGlobalAssets == nil {
|
||||
writeErr(w, http.StatusBadRequest, "至少需要提供 name、pinned、remark 或 share_global_assets")
|
||||
if request.Name == nil && request.Pinned == nil && request.Remark == nil && request.ShareGlobalAssets == nil && request.WorkerCount == nil {
|
||||
writeErr(w, http.StatusBadRequest, "至少需要提供 name、pinned、remark、share_global_assets 或 worker_count")
|
||||
return
|
||||
}
|
||||
if request.WorkerCount != nil && (*request.WorkerCount < 0 || *request.WorkerCount > db.MaxTaskWorkerCount) {
|
||||
writeErr(w, http.StatusBadRequest, fmt.Sprintf("worker_count 必须在 0 到 %d 之间", db.MaxTaskWorkerCount))
|
||||
return
|
||||
}
|
||||
if request.Name != nil {
|
||||
@@ -63,7 +68,7 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
request.Remark = &remark
|
||||
}
|
||||
task, err := s.m.UpdateTaskMetadata(taskID, db.TaskPatch{Name: request.Name, Pinned: request.Pinned, Remark: request.Remark, ShareGlobalAssets: request.ShareGlobalAssets})
|
||||
task, err := s.m.UpdateTaskMetadata(taskID, db.TaskPatch{Name: request.Name, Pinned: request.Pinned, Remark: request.Remark, ShareGlobalAssets: request.ShareGlobalAssets, WorkerCount: request.WorkerCount})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
@@ -72,5 +77,10 @@ func (s *Server) updateTaskMetadata(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "task not found")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, taskDTO(task, s.resolvedTaskStatus(task)))
|
||||
if request.WorkerCount != nil {
|
||||
s.engine.ReconcileWorkers(task)
|
||||
}
|
||||
dto := taskDTO(task, s.resolvedTaskStatus(task))
|
||||
dto.WorkerActualCount, dto.WorkerTargetCount = s.engine.WorkerCounts(task)
|
||||
writeJSON(w, http.StatusOK, dto)
|
||||
}
|
||||
@@ -159,3 +159,111 @@ func TestConversationBatchDeleteReportsMissing(t *testing.T) {
|
||||
t.Fatalf("missing conversation %s must include an error", fmt.Sprint(missing))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskMetadataPatchWorkerCount(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
task, err := m.CreateTask("worker count patch", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
taskID, _ := strconv.ParseInt(task.ID, 10, 64)
|
||||
defer func() { _ = m.pg.DeleteTask(taskID) }()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
s := &Server{m: m, engine: NewEngine(m), ctx: ctx}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("PATCH /api/tasks/{id}", s.updateTaskMetadata)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.getTask)
|
||||
mux.HandleFunc("GET /api/tasks", s.listTasks)
|
||||
request := func(method, path, body string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
assertCounts := func(body []byte, want int) {
|
||||
t.Helper()
|
||||
var dto struct {
|
||||
WorkerCount int `json:"worker_count"`
|
||||
WorkerActualCount *int `json:"worker_actual_count"`
|
||||
WorkerTargetCount *int `json:"worker_target_count"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &dto); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, target := s.engine.WorkerCounts(task)
|
||||
if dto.WorkerCount != want || dto.WorkerActualCount == nil || dto.WorkerTargetCount == nil {
|
||||
t.Fatalf("missing or incorrect worker counts: %s", body)
|
||||
}
|
||||
if *dto.WorkerActualCount != actual || *dto.WorkerTargetCount != target {
|
||||
t.Fatalf("worker counts=%d/%d, engine=%d/%d", *dto.WorkerActualCount, *dto.WorkerTargetCount, actual, target)
|
||||
}
|
||||
if actual != 0 || (want > 0 && target != want) {
|
||||
t.Fatalf("inactive task worker counts=%d/%d, want actual=0 and configured target=%d", actual, target, want)
|
||||
}
|
||||
}
|
||||
for _, count := range []int{1, 50, 0} {
|
||||
rec := request(http.MethodPatch, "/api/tasks/"+task.ID, fmt.Sprintf(`{"worker_count":%d}`, count))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("patch worker_count=%d status=%d body=%s", count, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCounts(rec.Body.Bytes(), count)
|
||||
if got := task.lifecycleSnapshot().WorkerCount; got != count {
|
||||
t.Fatalf("in-memory worker count=%d, want %d", got, count)
|
||||
}
|
||||
persisted, err := m.pg.GetTask(taskID)
|
||||
if err != nil || persisted == nil || persisted.WorkerCount != count {
|
||||
t.Fatalf("persisted task=%+v err=%v, want worker_count=%d", persisted, err, count)
|
||||
}
|
||||
rec = request(http.MethodGet, "/api/tasks/"+task.ID, "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("get task status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCounts(rec.Body.Bytes(), count)
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"worker_count":-1,"name":"must not commit"}`,
|
||||
`{"worker_count":51,"name":"must not commit"}`,
|
||||
`{"worker_count":1.5}`,
|
||||
`{"worker_count":"2"}`,
|
||||
`{"worker_count":null}`,
|
||||
} {
|
||||
rec := request(http.MethodPatch, "/api/tasks/"+task.ID, body)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("invalid patch %s status=%d body=%s", body, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
state := task.lifecycleSnapshot()
|
||||
persisted, err := m.pg.GetTask(taskID)
|
||||
if err != nil || persisted == nil || persisted.WorkerCount != 0 || persisted.Name != state.Name || state.Name == "must not commit" || state.WorkerCount != 0 {
|
||||
t.Fatalf("invalid patch changed state: memory=%+v persisted=%+v err=%v", state, persisted, err)
|
||||
}
|
||||
rec := request(http.MethodGet, "/api/tasks", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("list tasks status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var list struct {
|
||||
Tasks []json.RawMessage `json:"tasks"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, raw := range list.Tasks {
|
||||
var dto struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &dto); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dto.ID == task.ID {
|
||||
assertCounts(raw, 0)
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatal("updated task missing from list")
|
||||
}
|
||||
@@ -26,6 +26,7 @@ func TestExpandWorkerSlotsLegacy(t *testing.T) {
|
||||
{"configured", 2, 2},
|
||||
{"zero defaults", 0, 3},
|
||||
{"negative defaults", -1, 3},
|
||||
{"oversized caps", db.MaxTaskWorkerCount + 1, db.MaxTaskWorkerCount},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
slots, err := ExpandWorkerSlots(nil, tc.count)
|
||||
@@ -170,6 +171,13 @@ func TestWorkerPoolSettingsRoundTrip(t *testing.T) {
|
||||
if clearResult.Code != http.StatusOK || m.Workers() != 4 || len(m.WorkerPools()) != 0 {
|
||||
t.Fatalf("PUT legacy clear status=%d body=%s workers=%d pools=%+v", clearResult.Code, clearResult.Body.String(), m.Workers(), m.WorkerPools())
|
||||
}
|
||||
for _, body := range []string{`{"workers":51}`, `{"workers":51,"worker_pools":[]}`, `{"workers":0}`} {
|
||||
invalid := httptest.NewRecorder()
|
||||
s.putSettings(invalid, httptest.NewRequest(http.MethodPut, "/api/settings", strings.NewReader(body)))
|
||||
if invalid.Code != http.StatusBadRequest || m.Workers() != 4 || len(m.WorkerPools()) != 0 {
|
||||
t.Fatalf("invalid legacy workers %s status=%d body=%s workers=%d", body, invalid.Code, invalid.Body.String(), m.Workers())
|
||||
}
|
||||
}
|
||||
res = httptest.NewRecorder()
|
||||
s.getSettings(res, httptest.NewRequest(http.MethodGet, "/api/settings", nil))
|
||||
var cleared map[string]any
|
||||
@@ -280,7 +288,7 @@ func TestPinnedWorkerLoopDoesNotConsultTaskRouterAndReportsFailureOnce(t *testin
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
e.workerLoop(ctx, task, WorkerSlot{Name: "work#4", ProfileID: 12})
|
||||
e.workerLoop(ctx, task, WorkerSlot{Name: "work#4", ProfileID: 12}, &workerSlotRuntime{idleCtx: ctx})
|
||||
close(done)
|
||||
}()
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
@@ -391,3 +399,92 @@ func TestDetachedIntentPinnedOwnerUsesPinnedResolver(t *testing.T) {
|
||||
t.Fatalf("intent changed after unavailable resolver: node=%+v err=%v", node, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerSettingsDirectSettersNotifyAfterPersistence(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable: %v", err)
|
||||
}
|
||||
defer m.Close()
|
||||
oldPools, poolsSet, _ := m.pg.GetSetting(settingWorkerPools)
|
||||
oldWorkers, workersSet, _ := m.pg.GetSetting(settingWorkers)
|
||||
defer func() {
|
||||
for key, saved := range map[string]struct {
|
||||
value string
|
||||
set bool
|
||||
}{
|
||||
settingWorkerPools: {oldPools, poolsSet},
|
||||
settingWorkers: {oldWorkers, workersSet},
|
||||
} {
|
||||
if saved.set {
|
||||
_ = m.pg.SetSetting(key, saved.value)
|
||||
} else {
|
||||
_, _ = m.pg.Exec("DELETE FROM settings WHERE key=$1", key)
|
||||
}
|
||||
}
|
||||
}()
|
||||
profileID, err := m.pg.SaveProfile(&db.LLMProfile{Name: "worker-notify-test", Format: "openai", Model: "worker-notify-test", APIKey: "worker-notify-test-key"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer m.pg.DeleteProfile(profileID)
|
||||
var notifications int
|
||||
wantWorkers, wantPools := 0, 0
|
||||
callback := func() {
|
||||
notifications++
|
||||
// Re-enter Manager APIs: callbacks must run after the write and outside mu.
|
||||
if got := m.Workers(); got != wantWorkers {
|
||||
t.Errorf("callback observed workers=%d, want %d", got, wantWorkers)
|
||||
}
|
||||
if got := len(m.WorkerPools()); got != wantPools {
|
||||
t.Errorf("callback observed %d pools, want %d", got, wantPools)
|
||||
}
|
||||
m.SetWorkerConfigChangedCallback(nil)
|
||||
}
|
||||
m.SetWorkerConfigChangedCallback(callback)
|
||||
check := func(want int) {
|
||||
t.Helper()
|
||||
if notifications != want {
|
||||
t.Fatalf("notifications=%d, want %d", notifications, want)
|
||||
}
|
||||
}
|
||||
wantWorkers, wantPools = 50, len(m.WorkerPools())
|
||||
if err := m.SetWorkers(50); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(1)
|
||||
m.SetWorkerConfigChangedCallback(callback)
|
||||
for _, count := range []int{-1, 0, 51} {
|
||||
if err := m.SetWorkers(count); err == nil {
|
||||
t.Fatalf("SetWorkers(%d) accepted", count)
|
||||
}
|
||||
if err := m.SetWorkerPools(nil, count); err == nil {
|
||||
t.Fatalf("SetWorkerPools(nil, %d) accepted", count)
|
||||
}
|
||||
check(1)
|
||||
}
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: 9223372036854775807, Workers: 1}}); err == nil {
|
||||
t.Fatal("missing profile accepted")
|
||||
}
|
||||
check(1)
|
||||
if got := m.Workers(); got != 50 {
|
||||
t.Fatalf("rejected worker settings changed persisted workers=%d, want 50", got)
|
||||
}
|
||||
wantWorkers, wantPools = 2, 1
|
||||
if err := m.SetWorkerPools([]WorkerPool{{ProfileID: profileID, Workers: 2}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(2)
|
||||
m.SetWorkerConfigChangedCallback(callback)
|
||||
wantWorkers, wantPools = 3, 0
|
||||
if err := m.SetWorkerPools(nil, 3); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
check(3)
|
||||
if err := m.pg.SetSetting(settingWorkers, "1000"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := m.Workers(); got != db.MaxTaskWorkerCount {
|
||||
t.Fatalf("old oversized workers=%d, want %d", got, db.MaxTaskWorkerCount)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
InfoIcon,
|
||||
SearchIcon,
|
||||
ShieldAlertIcon,
|
||||
Trash2Icon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -285,6 +286,10 @@ export default function FindingsPage() {
|
||||
const [includeOriginals, setIncludeOriginals] = React.useState(false);
|
||||
const [reviewing, setReviewing] = React.useState(false);
|
||||
const [exporting, setExporting] = React.useState(false);
|
||||
const [cleanupOpen, setCleanupOpen] = React.useState(false);
|
||||
const [cleanupScope, setCleanupScope] = React.useState<"filtered" | "all" | "selected">("all");
|
||||
const [cleaning, setCleaning] = React.useState(false);
|
||||
const [caseRefreshKey, setCaseRefreshKey] = React.useState(0);
|
||||
|
||||
const toggleSelected = React.useCallback((id: string, checked: boolean) => {
|
||||
setSelectedIds((prev) => {
|
||||
@@ -312,6 +317,23 @@ export default function FindingsPage() {
|
||||
setExportOpen(true);
|
||||
}
|
||||
|
||||
const hasActiveFilters =
|
||||
severity !== "all" ||
|
||||
status !== "all" ||
|
||||
vulnclass !== "all" ||
|
||||
task !== "all" ||
|
||||
query !== "" ||
|
||||
Boolean(dateRange.from) ||
|
||||
Boolean(dateRange.to) ||
|
||||
(view === "asset" && assetScope !== null);
|
||||
|
||||
function openCleanup() {
|
||||
if (selectedIds.size > 0) setCleanupScope("selected");
|
||||
else if (hasActiveFilters && stats.total > 0) setCleanupScope("filtered");
|
||||
else setCleanupScope("all");
|
||||
setCleanupOpen(true);
|
||||
}
|
||||
|
||||
async function doExport() {
|
||||
setExporting(true);
|
||||
try {
|
||||
@@ -791,6 +813,58 @@ export default function FindingsPage() {
|
||||
[refreshAfterMutation, refreshStats, setFindings, liveUI],
|
||||
);
|
||||
|
||||
async function doCleanup() {
|
||||
if (cleaning) return;
|
||||
setCleaning(true);
|
||||
try {
|
||||
const res = await api.cleanupFindings({
|
||||
scope: cleanupScope,
|
||||
filters: {
|
||||
severity,
|
||||
status,
|
||||
vulnclass,
|
||||
task,
|
||||
query,
|
||||
sort,
|
||||
...dateRange,
|
||||
assetScope: view === "asset" ? (assetScope ?? undefined) : undefined,
|
||||
},
|
||||
ids: [...selectedIds],
|
||||
});
|
||||
setCleanupOpen(false);
|
||||
setSelectedIds(new Set());
|
||||
setExpanded(null);
|
||||
setEdit(null);
|
||||
setReports({});
|
||||
setPage(1);
|
||||
setFlatPage(1);
|
||||
setExpandedGroups(new Set());
|
||||
setGroupFindings({});
|
||||
if (view === "asset" && cleanupScope === "all") {
|
||||
setAssetScope(null);
|
||||
}
|
||||
setCaseRefreshKey((v) => v + 1);
|
||||
void refreshStats();
|
||||
if (view === "asset") {
|
||||
void loadFlat();
|
||||
void loadAssetTree();
|
||||
} else if (view === "flat") {
|
||||
void loadFlat();
|
||||
} else if (view === "grouped") {
|
||||
void refreshGroups();
|
||||
}
|
||||
if (res.deleted > 0) {
|
||||
toast.success(t("findingsCleanup.success", { count: res.deleted }));
|
||||
} else {
|
||||
toast.info(t("findingsCleanup.empty"));
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error(t("findingsCleanup.failed", { message: (e as Error).message }));
|
||||
} finally {
|
||||
setCleaning(false);
|
||||
}
|
||||
}
|
||||
|
||||
const openDeepen = React.useCallback((f: Finding) => {
|
||||
setDeepenFinding(f);
|
||||
setDeepenDescription("");
|
||||
@@ -1053,6 +1127,15 @@ export default function FindingsPage() {
|
||||
<Button size="sm" variant="outline" onClick={openExport}>
|
||||
<DownloadIcon /> {ui("screen.76420433f22d1c")}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||
disabled={cleaning || (statsLoaded && !hasActiveFilters && stats.total === 0 && selectedIds.size === 0)}
|
||||
onClick={openCleanup}
|
||||
>
|
||||
<Trash2Icon /> {t("findingsCleanup.button")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1121,6 +1204,7 @@ export default function FindingsPage() {
|
||||
query={{ severity, status, vulnclass, task, query, sort, ...dateRange }}
|
||||
selectedIds={selectedIds}
|
||||
onSelect={toggleSelected}
|
||||
refreshKey={caseRefreshKey}
|
||||
/>
|
||||
)}
|
||||
{view === "grouped" && (
|
||||
@@ -1394,6 +1478,62 @@ export default function FindingsPage() {
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<Dialog
|
||||
open={cleanupOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!cleaning) setCleanupOpen(open);
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("findingsCleanup.title")}</DialogTitle>
|
||||
<DialogDescription>{t("findingsCleanup.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-2 py-1">
|
||||
<span className="text-muted-foreground text-xs">{t("findingsCleanup.scopeLabel")}</span>
|
||||
<RadioGroup value={cleanupScope} onValueChange={(v) => setCleanupScope(v as typeof cleanupScope)}>
|
||||
<label
|
||||
htmlFor="cleanup-scope-filtered"
|
||||
className={cn("flex items-center gap-2 text-sm", stats.total === 0 && "text-muted-foreground")}
|
||||
>
|
||||
<RadioGroupItem id="cleanup-scope-filtered" value="filtered" disabled={stats.total === 0} />
|
||||
{t("findingsCleanup.scopeFiltered", { count: stats.total })}
|
||||
</label>
|
||||
<label
|
||||
htmlFor="cleanup-scope-selected"
|
||||
className={cn("flex items-center gap-2 text-sm", selectedIds.size === 0 && "text-muted-foreground")}
|
||||
>
|
||||
<RadioGroupItem id="cleanup-scope-selected" value="selected" disabled={selectedIds.size === 0} />
|
||||
{t("findingsCleanup.scopeSelected", { count: selectedIds.size })}
|
||||
</label>
|
||||
<label htmlFor="cleanup-scope-all" className="flex items-center gap-2 text-sm">
|
||||
<RadioGroupItem id="cleanup-scope-all" value="all" />
|
||||
{t("findingsCleanup.scopeAll")}
|
||||
</label>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => setCleanupOpen(false)} disabled={cleaning}>
|
||||
{t("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={doCleanup}
|
||||
disabled={
|
||||
cleaning ||
|
||||
(cleanupScope === "selected" && selectedIds.size === 0) ||
|
||||
(cleanupScope === "filtered" && stats.total === 0)
|
||||
}
|
||||
>
|
||||
{cleaning ? <Spinner data-icon="inline-start" /> : <Trash2Icon />}
|
||||
{cleaning ? t("findingsCleanup.cleaning") : t("findingsCleanup.confirm")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,8 @@ import {
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
@@ -40,6 +42,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import type { LLMProfile, Task } from "@/lib/types";
|
||||
import { MAX_TASK_WORKER_COUNT, parseWorkerCountInput } from "@/lib/types";
|
||||
|
||||
import { AssetsTab } from "./_tabs/assets-tab";
|
||||
import { BroadcastTab } from "./_tabs/broadcast-tab";
|
||||
@@ -212,6 +215,87 @@ function TaskLLMControl({ task, profiles, onUpdated }: { task: Task; profiles: L
|
||||
);
|
||||
}
|
||||
|
||||
function TaskWorkerControl({ task, onUpdated }: { task: Task; onUpdated: (task: Task) => void }) {
|
||||
const { ui } = useUITranslation();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
const [draft, setDraft] = React.useState(String(task.worker_count ?? 0));
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
const actual = task.worker_actual_count;
|
||||
const target = task.worker_target_count;
|
||||
const draining = actual !== undefined && target !== undefined && actual > target;
|
||||
|
||||
const save = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
const count = parseWorkerCountInput(draft);
|
||||
if (count === null) {
|
||||
toast.error(ui("taskUI.invalidWorkers", { max: MAX_TASK_WORKER_COUNT }));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateTask(task.id, { worker_count: count });
|
||||
onUpdated(updated);
|
||||
setOpen(false);
|
||||
toast.success(ui("taskWorkers.saved"));
|
||||
} catch (error) {
|
||||
toast.error(ui("taskWorkers.saveFailed", { message: (error as Error).message }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="tabular-nums">{ui("taskWorkers.counts", { actual: actual ?? "—", target: target ?? "—" })}</span>
|
||||
<Popover
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
setOpen(next);
|
||||
if (next) setDraft(String(task.worker_count ?? 0));
|
||||
}}
|
||||
>
|
||||
<PopoverTrigger asChild>
|
||||
<Button size="sm" variant="outline" className="h-7 text-xs">
|
||||
{ui("taskWorkers.edit")}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-[min(25rem,calc(100vw-2rem))] gap-4 p-4">
|
||||
<PopoverHeader>
|
||||
<PopoverTitle>{ui("taskWorkers.edit")}</PopoverTitle>
|
||||
<PopoverDescription>{ui("taskWorkers.help")}</PopoverDescription>
|
||||
</PopoverHeader>
|
||||
<form onSubmit={save} className="space-y-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="task-worker-count">{ui("taskWorkers.label")}</Label>
|
||||
<Input
|
||||
id="task-worker-count"
|
||||
type="number"
|
||||
min={0}
|
||||
max={MAX_TASK_WORKER_COUNT}
|
||||
step={1}
|
||||
value={draft}
|
||||
disabled={saving}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{ui("taskWorkers.transitionHelp")}</p>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setOpen(false)} disabled={saving}>
|
||||
{ui("screen.3fd47edce45b36")}
|
||||
</Button>
|
||||
<Button type="submit" size="sm" disabled={saving}>
|
||||
{saving && <Spinner data-icon="inline-start" />}
|
||||
{ui(saving ? "screen.a1a1720d3eb58a" : "screen.a3030bf8f16dc6")}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{draining && <span className="text-amber-600">{ui("taskWorkers.draining")}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TaskDetailInner() {
|
||||
const { ui, liveUI } = useUITranslation();
|
||||
|
||||
@@ -437,6 +521,14 @@ function TaskDetailInner() {
|
||||
</Button>
|
||||
</div>
|
||||
<p className="truncate text-xs text-muted-foreground">{task.goal}</p>
|
||||
<TaskWorkerControl
|
||||
key={task.id}
|
||||
task={task}
|
||||
onUpdated={(updated) => {
|
||||
setTask(updated);
|
||||
load();
|
||||
}}
|
||||
/>
|
||||
{task.paused && task.pause_reason && (
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs text-amber-600">
|
||||
<span>
|
||||
|
||||
@@ -1731,8 +1731,8 @@ export default function SystemSettingsPage() {
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t("settings.workersHelpStart")}
|
||||
<b>{t("settings.futureTasksOnly")}</b>
|
||||
{t("settings.runningTasksUnchanged")}
|
||||
<b>{t("settings.workersLiveUpdate")}</b>
|
||||
{t("settings.workersDrainHelp")}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
|
||||
@@ -448,6 +448,7 @@ export function FindingCaseList({
|
||||
contextTask,
|
||||
readOnly = false,
|
||||
onTotal,
|
||||
refreshKey = 0,
|
||||
}: {
|
||||
query: Omit<FindingQuery, "page" | "pageSize">;
|
||||
selectedIds?: Set<string>;
|
||||
@@ -455,6 +456,7 @@ export function FindingCaseList({
|
||||
contextTask?: string;
|
||||
readOnly?: boolean;
|
||||
onTotal?: (total: number) => void;
|
||||
refreshKey?: number;
|
||||
}) {
|
||||
const { ui } = useUITranslation();
|
||||
|
||||
@@ -464,10 +466,10 @@ export function FindingCaseList({
|
||||
const [error, setError] = React.useState("");
|
||||
const [refresh, setRefresh] = React.useState(0);
|
||||
const key = JSON.stringify(query);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint changes.
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: reset pagination when the filter fingerprint or external refresh changes.
|
||||
React.useEffect(() => {
|
||||
setPage(1);
|
||||
}, [key]);
|
||||
}, [key, refreshKey]);
|
||||
// biome-ignore lint/correctness/useExhaustiveDependencies: refresh is an explicit reload requested after grouping/retry.
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
@@ -490,7 +492,7 @@ export function FindingCaseList({
|
||||
active = false;
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [key, page, pageSize, refresh]);
|
||||
}, [key, page, pageSize, refresh, refreshKey]);
|
||||
React.useEffect(() => {
|
||||
if (data) onTotal?.(data.total);
|
||||
}, [data, onTotal]);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { buildRawResponse } from "./repeater-http";
|
||||
import { buildRawResponse, rawRequestTarget } from "./repeater-http";
|
||||
import type { RepeaterTab } from "./repeater-state";
|
||||
|
||||
export type RepeaterFilters = { query: string; method: string; path: string; response: string; status: string };
|
||||
@@ -7,13 +7,7 @@ export const DEFAULT_FILTERS: RepeaterFilters = { query: "", method: "all", path
|
||||
export function matchesRepeaterFilters(tab: RepeaterTab, filters: RepeaterFilters): boolean {
|
||||
const includes = (text: string, query: string) => text.toLowerCase().includes(query.trim().toLowerCase());
|
||||
if (filters.method !== "all" && tab.method.toUpperCase() !== filters.method) return false;
|
||||
let path = tab.url;
|
||||
try {
|
||||
const url = new URL(tab.url);
|
||||
path = url.pathname + url.search;
|
||||
} catch {
|
||||
/* Incomplete drafts remain searchable. */
|
||||
}
|
||||
const path = rawRequestTarget(tab.url) || tab.url;
|
||||
if (!includes(path, filters.path)) return false;
|
||||
const rawResponse = tab.response ? `${buildRawResponse(tab.response)}\n${tab.response.error || ""}` : "";
|
||||
if (!includes(rawResponse, filters.response)) return false;
|
||||
|
||||
@@ -103,12 +103,7 @@ export function requestFromTraffic(
|
||||
if (/…\[truncated\] @blob sha256:[a-f0-9]{64}/.test(request.body)) {
|
||||
throw new Error("请求正文为截断预览,请下载完整正文后再导入");
|
||||
}
|
||||
let host = exchange.host;
|
||||
try {
|
||||
host = new URL(exchange.url).host || host;
|
||||
} catch {
|
||||
/* Legacy URL uses the indexed host. */
|
||||
}
|
||||
const host = extractHttpHost(exchange.url) || exchange.host;
|
||||
const headersText = getHostHeader(request.headersText)
|
||||
? request.headersText
|
||||
: setHostHeader(request.headersText, host);
|
||||
@@ -124,26 +119,63 @@ export function requestFromTraffic(
|
||||
};
|
||||
}
|
||||
|
||||
export function connectionOrigin(url: string): string {
|
||||
type SplitHttpUrl = {
|
||||
origin: string;
|
||||
host: string;
|
||||
base: string;
|
||||
rest: string;
|
||||
};
|
||||
|
||||
// Parse only the scheme+authority via WHATWG URL so the raw request-target
|
||||
// (path and query) is never percent-encoded, dot-collapsed, or backslash-rewritten.
|
||||
function splitRawHttpUrl(raw: string): SplitHttpUrl | null {
|
||||
const trimmed = raw.trim();
|
||||
if (!/^https?:\/\//i.test(trimmed)) return null;
|
||||
const schemeEnd = trimmed.indexOf("://") + 3;
|
||||
const restOffset = trimmed.slice(schemeEnd).search(/[/?#]/);
|
||||
const restIndex = restOffset < 0 ? trimmed.length : schemeEnd + restOffset;
|
||||
const authority = trimmed.slice(schemeEnd, restIndex);
|
||||
if (!authority || authority.includes("\\")) return null;
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return /^https?:$/.test(parsed.protocol) ? parsed.origin : "";
|
||||
const parsed = new URL(trimmed.slice(0, restIndex));
|
||||
if (!/^https?:$/.test(parsed.protocol) || !parsed.host) return null;
|
||||
return {
|
||||
origin: parsed.origin,
|
||||
host: parsed.host,
|
||||
base: parsed.href.replace(/\/$/, ""),
|
||||
rest: trimmed.slice(restIndex),
|
||||
};
|
||||
} catch {
|
||||
return "";
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeRequestTarget(rest: string): string {
|
||||
if (!rest) return "/";
|
||||
return rest.startsWith("?") ? `/${rest}` : rest;
|
||||
}
|
||||
|
||||
export function extractHttpHost(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
return parsed ? parsed.host : "";
|
||||
}
|
||||
|
||||
export function rawRequestTarget(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
if (!parsed) return "";
|
||||
return normalizeRequestTarget(parsed.rest.split("#", 1)[0]);
|
||||
}
|
||||
|
||||
export function connectionOrigin(url: string): string {
|
||||
const parsed = splitRawHttpUrl(url);
|
||||
return parsed ? parsed.origin : "";
|
||||
}
|
||||
|
||||
export function buildRawRequest(request: RepeaterInitial): string {
|
||||
if (request.rawRequest !== undefined) return request.rawRequest;
|
||||
let target = "/";
|
||||
let host = "";
|
||||
try {
|
||||
const url = new URL(request.url ?? "");
|
||||
target = url.pathname + url.search;
|
||||
host = url.host;
|
||||
} catch {
|
||||
/* New empty draft. */
|
||||
}
|
||||
const parsed = splitRawHttpUrl(request.url ?? "");
|
||||
const target = parsed ? normalizeRequestTarget(parsed.rest.split("#", 1)[0]) : "/";
|
||||
const host = parsed ? parsed.host : "";
|
||||
const headersText = request.headersText?.trim() ? request.headersText : `Host: ${host}`;
|
||||
return `${request.method ?? "GET"} ${target} HTTP/1.1\n${joinRequestText(headersText, request.body ?? "")}`;
|
||||
}
|
||||
@@ -157,19 +189,24 @@ export function parseRawRequest(
|
||||
const match = /^([A-Za-z]+)\s+(\S+)\s+(HTTP\/(?:1\.[01]|2(?:\.0)?))$/.exec(line);
|
||||
if (!match) throw new Error("请求首行应为:POST /path HTTP/1.1");
|
||||
const parts = splitRequestText(newline < 0 ? "" : text.slice(newline + 1));
|
||||
let url: URL;
|
||||
if (/^https?:\/\//i.test(match[2])) url = new URL(match[2]);
|
||||
else {
|
||||
if (!match[2].startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
|
||||
const requestTarget = match[2];
|
||||
let url: string;
|
||||
if (/^https?:\/\//i.test(requestTarget)) {
|
||||
const parsed = splitRawHttpUrl(requestTarget);
|
||||
if (!parsed) throw new TypeError(`Invalid URL: ${requestTarget}`);
|
||||
if (parsed.rest.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
url = `${parsed.base}${normalizeRequestTarget(parsed.rest)}`;
|
||||
} else {
|
||||
if (!requestTarget.startsWith("/")) throw new Error("请求路径必须以 / 开头,或填写完整 http/https URL");
|
||||
const origin = connectionOrigin(targetOrigin) || connectionOrigin(`https://${getHostHeader(parts.headersText)}`);
|
||||
if (!origin) throw new Error("请填写 Host 请求头或设置发送目标");
|
||||
url = new URL(origin + match[2]);
|
||||
if (requestTarget.includes("#")) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
url = `${origin}${requestTarget}`;
|
||||
}
|
||||
if (url.hash) throw new Error("请求路径不能包含 URL 片段,请使用 %23 表示 #");
|
||||
return {
|
||||
...parts,
|
||||
method: match[1].toUpperCase(),
|
||||
url: url.href,
|
||||
url,
|
||||
httpVersion: match[3] === "HTTP/2" ? "HTTP/2.0" : match[3],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { RepeaterSendResponse } from "@/lib/types";
|
||||
|
||||
import type { RepeaterInitial } from "./repeater-http";
|
||||
import { extractHttpHost, type RepeaterInitial } from "./repeater-http";
|
||||
|
||||
export const STORAGE_KEY = "artex_repeater_workspace_v1";
|
||||
export const MAX_HISTORY = 20;
|
||||
@@ -99,12 +99,7 @@ export function seedWorkspace(
|
||||
opts: TabOptions = {},
|
||||
): RepeaterWorkspace {
|
||||
const method = initial.method?.trim().toUpperCase() || "GET";
|
||||
let host = "";
|
||||
try {
|
||||
host = new URL(initial.url ?? "").host;
|
||||
} catch {
|
||||
/* An empty/unfinished URL is a valid draft. */
|
||||
}
|
||||
const host = extractHttpHost(initial.url ?? "");
|
||||
return addTab(
|
||||
workspace,
|
||||
{ ...initial, method, source: meta },
|
||||
|
||||
@@ -582,3 +582,66 @@ test("evidence import preserves captured request line and protocol rather than r
|
||||
assert.equal(imported.targetOrigin, "https://example.test");
|
||||
assert.equal(buildRawRequest(imported), imported.rawRequest);
|
||||
});
|
||||
|
||||
test("raw request-target characters in query and path are preserved without WHATWG URL normalization", () => {
|
||||
const sqli = parseRawRequest("GET /item?id=1' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(sqli.url, "https://example.test/item?id=1'");
|
||||
|
||||
const specialQuery = parseRawRequest(
|
||||
"GET /item?id=1'\"<>`{}\\| HTTP/1.1\nHost: example.test\n\n",
|
||||
"http://example.test:8080",
|
||||
);
|
||||
assert.equal(specialQuery.url, "http://example.test:8080/item?id=1'\"<>`{}\\|");
|
||||
|
||||
const traversal = parseRawRequest("GET /a/../b/./c?id=1' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(traversal.url, "https://example.test/a/../b/./c?id=1'");
|
||||
|
||||
const encodedDots = parseRawRequest("GET /a/%2e%2e/b?x=' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(encodedDots.url, "https://example.test/a/%2e%2e/b?x='");
|
||||
|
||||
const rawPathChars = parseRawRequest("GET /a\\b\"c?q=' HTTP/1.1\nHost: example.test\n\n");
|
||||
assert.equal(rawPathChars.url, "https://example.test/a\\b\"c?q='");
|
||||
|
||||
const absolute = parseRawRequest("GET http://elsewhere.test:8080/a/../item?id=1'\"<> HTTP/1.1\nHost: vhost.test\n\n");
|
||||
assert.equal(absolute.url, "http://elsewhere.test:8080/a/../item?id=1'\"<>");
|
||||
|
||||
assert.equal(
|
||||
parseRawRequest("GET http://elsewhere.test HTTP/1.1\nHost: elsewhere.test\n\n").url,
|
||||
"http://elsewhere.test/",
|
||||
);
|
||||
assert.equal(
|
||||
parseRawRequest("GET http://elsewhere.test?id=1' HTTP/1.1\nHost: elsewhere.test\n\n").url,
|
||||
"http://elsewhere.test/?id=1'",
|
||||
);
|
||||
|
||||
assert.throws(() => parseRawRequest("GET /item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
|
||||
assert.throws(() => parseRawRequest("GET /item# HTTP/1.1\nHost: example.test\n\n"), /URL 片段/);
|
||||
assert.throws(
|
||||
() => parseRawRequest("GET http://example.test/item?id=1'#frag HTTP/1.1\nHost: example.test\n\n"),
|
||||
/URL 片段/,
|
||||
);
|
||||
assert.throws(() => parseRawRequest("GET http://example.test\\evil/path HTTP/1.1\nHost: example.test\n\n"));
|
||||
|
||||
const built = buildRawRequest({
|
||||
method: "GET",
|
||||
url: "https://example.test:8443/a/../item?id=1'",
|
||||
});
|
||||
assert.equal(built, "GET /a/../item?id=1' HTTP/1.1\nHost: example.test:8443\n\n");
|
||||
|
||||
const fromTraffic = requestFromTraffic("GET /item?id=1' HTTP/1.1\r\nHost: example.test\r\n\r\n", {
|
||||
method: "GET",
|
||||
url: "https://example.test/item?id=1'",
|
||||
host: "example.test",
|
||||
});
|
||||
assert.equal(fromTraffic.url, "https://example.test/item?id=1'");
|
||||
assert.match(fromTraffic.rawRequest, /^GET \/item\?id=1' HTTP\/1\.1\n/);
|
||||
|
||||
const tab = {
|
||||
...defaultWorkspace().tabs[0],
|
||||
method: "GET",
|
||||
url: "https://example.test/a/../item?id=1'",
|
||||
rawRequest: "GET /a/../item?id=1' HTTP/1.1\nHost: example.test\n\n",
|
||||
};
|
||||
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "id=1'" }), true);
|
||||
assert.equal(matchesRepeaterFilters(tab, { ...DEFAULT_FILTERS, path: "/a/../item" }), true);
|
||||
});
|
||||
@@ -218,6 +218,21 @@ export const messages = {
|
||||
"仅 openai 格式可选。Gemini 的字段名固定为 maxOutputTokens。",
|
||||
"Only configurable for the openai format. Gemini uses maxOutputTokens.",
|
||||
],
|
||||
"findingsCleanup.button": ["一键清理", "One-click cleanup"],
|
||||
"findingsCleanup.title": ["一键清理历史漏洞", "Clean up historical findings"],
|
||||
"findingsCleanup.description": [
|
||||
"永久删除所选范围内的漏洞发现记录及其来源探索节点、复测记录和归并成员关系,删除后无法恢复。",
|
||||
"Permanently delete matching findings along with their originating exploration nodes, retest records, and case memberships. This action cannot be undone.",
|
||||
],
|
||||
"findingsCleanup.scopeLabel": ["清理范围", "Cleanup scope"],
|
||||
"findingsCleanup.scopeFiltered": ["当前筛选结果({{count}} 条)", "Current filter results ({{count}})"],
|
||||
"findingsCleanup.scopeSelected": ["已勾选漏洞({{count}} 条)", "Selected findings ({{count}})"],
|
||||
"findingsCleanup.scopeAll": ["全部历史漏洞", "All historical findings"],
|
||||
"findingsCleanup.confirm": ["确认清理", "Confirm cleanup"],
|
||||
"findingsCleanup.cleaning": ["清理中…", "Cleaning up…"],
|
||||
"findingsCleanup.success": ["已清理 {{count}} 条漏洞", "Deleted {{count}} finding(s)"],
|
||||
"findingsCleanup.empty": ["没有符合条件的漏洞可清理", "No matching findings to delete"],
|
||||
"findingsCleanup.failed": ["清理失败:{{message}}", "Cleanup failed: {{message}}"],
|
||||
} satisfies Record<string, readonly [string, string]>;
|
||||
|
||||
const statuses: Record<string, readonly (readonly [string, string, string])[]> = {
|
||||
|
||||
@@ -12,14 +12,14 @@ export const settingsMessages = {
|
||||
"settings.workerLimit": ["Worker 总数不能超过 50", "The total number of Workers cannot exceed 50"],
|
||||
"settings.duplicatePoolProfile": ["不能重复选择同一个 LLM 配置", "Each LLM profile can only be selected once"],
|
||||
"settings.workerPoolsSaved": [
|
||||
"已保存多模型 Worker 池(对之后启动的任务生效)",
|
||||
"Model pools saved; applies to tasks started afterward",
|
||||
"已保存多模型 Worker 池,跟随全局配置的任务已热更新",
|
||||
"Model pools saved; tasks following the global configuration have been updated live",
|
||||
],
|
||||
"settings.saveFailed": ["保存失败:{{message}}", "Could not save: {{message}}"],
|
||||
"settings.positiveConcurrency": ["并发数必须是大于 0 的整数", "Concurrency must be a positive whole number"],
|
||||
"settings.workersSaved": [
|
||||
"已保存并发工作 agent 数(对之后启动的任务生效)",
|
||||
"Worker count saved; applies to tasks started afterward",
|
||||
"已保存工作并发,跟随全局配置的任务已热更新",
|
||||
"Worker count saved; tasks following the global configuration have been updated live",
|
||||
],
|
||||
"settings.saveFailedPrefix": ["保存失败:", "Could not save: "],
|
||||
"settings.pythonSaved": ["已保存 Python 解释器配置", "Python interpreter settings saved"],
|
||||
@@ -427,8 +427,14 @@ export const settingsMessages = {
|
||||
"每个任务并发运行的工作 agent 数量(默认 3)。数值越大并发探测越多、消耗也越高。修改后",
|
||||
"The number of Workers running concurrently per task (default: 3). More Workers mean more parallel probes and higher usage. Changes ",
|
||||
],
|
||||
"settings.futureTasksOnly": ["对之后启动的任务生效", "apply to tasks started afterward"],
|
||||
"settings.runningTasksUnchanged": [",正在运行的任务不受影响。", "; running tasks are unaffected."],
|
||||
"settings.workersLiveUpdate": [
|
||||
"即时更新跟随全局配置(worker_count = 0)的任务",
|
||||
"apply immediately to tasks following the global configuration (worker_count = 0)",
|
||||
],
|
||||
"settings.workersDrainHelp": [
|
||||
";单任务覆盖值不受影响。增容启动新 Worker loops;缩容等待在跑意图完成后退出,不会强杀,实际数量可能暂时高于目标。",
|
||||
"; per-task overrides are unchanged. Scaling up starts new Worker loops; scaling down lets running intents finish before loops exit, without force-cancelling them. Actual counts may temporarily exceed target.",
|
||||
],
|
||||
"settings.workerPools": ["多模型 Worker 池", "Model pools"],
|
||||
"settings.addPool": ["添加模型池", "Add model pool"],
|
||||
"settings.unavailableProfile": ["配置 #{{id}} 已删除/不可用", "Profile #{{id}} deleted or unavailable"],
|
||||
|
||||
@@ -1,4 +1,21 @@
|
||||
export const taskMessages = {
|
||||
"taskWorkers.edit": ["调整 Worker 并发", "Adjust Worker concurrency"],
|
||||
"taskWorkers.label": ["Worker 数量(0–50)", "Worker count (0–50)"],
|
||||
"taskWorkers.counts": ["Worker 实际 / 目标:{{actual}} / {{target}}", "Workers actual / target: {{actual}} / {{target}}"],
|
||||
"taskWorkers.help": [
|
||||
"0 表示跟随全局 Worker 配置;1–50 为本任务覆盖值,保存后热更新,无需重启任务。",
|
||||
"Use 0 to follow the global Worker configuration, or 1–50 to override it for this task. Saving applies changes live without restarting the task.",
|
||||
],
|
||||
"taskWorkers.transitionHelp": [
|
||||
"实际数量是存活的 Worker loops(含缩容退出中的 loops),不是正在执行的意图数。增容会启动新 loops;缩容等待正在执行的意图完成后退出,不会强杀意图,因此实际数量可能暂时高于目标。",
|
||||
"Actual counts live Worker loops, including draining loops, not in-flight intents. Scaling up starts new loops. Scaling down lets running intents finish before loops exit, without force-cancelling them, so actual may temporarily exceed target.",
|
||||
],
|
||||
"taskWorkers.draining": [
|
||||
"缩容过渡中:等待在跑意图完成,不会强杀。",
|
||||
"Scaling down: waiting for running intents to finish; they will not be force-cancelled.",
|
||||
],
|
||||
"taskWorkers.saved": ["Worker 并发已更新", "Worker concurrency updated"],
|
||||
"taskWorkers.saveFailed": ["Worker 并发更新失败:{{message}}", "Could not update Worker concurrency: {{message}}"],
|
||||
"taskFiles.tab": ["文件", "Files"],
|
||||
"taskFiles.tree": ["目录树", "Directory tree"],
|
||||
"taskFiles.recent": ["最近文件", "Recent files"],
|
||||
|
||||
+25
-1
@@ -483,7 +483,7 @@ export const api = {
|
||||
taskCategories: () => get<{ categories: TaskCategory[] }>("/task-categories").then((r) => arr(r.categories)),
|
||||
updateTask: (
|
||||
id: string,
|
||||
input: { name?: string; pinned?: boolean; remark?: string; share_global_assets?: boolean },
|
||||
input: { name?: string; pinned?: boolean; remark?: string; share_global_assets?: boolean; worker_count?: number },
|
||||
) => patch<Task>(`/tasks/${id}`, input),
|
||||
renameTask: (id: string, name: string) => patch<Task>(`/tasks/${id}`, { name }),
|
||||
pinTask: (id: string, pinned: boolean) => patch<Task>(`/tasks/${id}`, { pinned }),
|
||||
@@ -970,6 +970,30 @@ export const api = {
|
||||
) => patch<Finding>(`/exploration/findings/${id}`, fields),
|
||||
// 删除漏洞:移除 findings 记录 + 来源探索节点(从发现列表/任务发现 Tab/探索图一并消失)。
|
||||
deleteFinding: (id: string) => del<{ deleted: boolean; id: number }>(`/exploration/findings/${id}`),
|
||||
// 批量一键清理漏洞:按范围(当前筛选/全部/已勾选)移除 findings 记录及来源探索节点。
|
||||
cleanupFindings: (opts: {
|
||||
scope: "filtered" | "all" | "selected";
|
||||
filters?: Omit<FindingQuery, "page" | "pageSize">;
|
||||
ids?: string[];
|
||||
}) => {
|
||||
const body: Record<string, unknown> = { scope: opts.scope };
|
||||
if (opts.scope === "selected") {
|
||||
body.ids = opts.ids ?? [];
|
||||
} else if (opts.scope === "filtered" && opts.filters) {
|
||||
const f = opts.filters;
|
||||
body.filters = {
|
||||
...(f.severity && f.severity !== "all" ? { severity: f.severity } : {}),
|
||||
...(f.status && f.status !== "all" ? { status: f.status } : {}),
|
||||
...(f.vulnclass && f.vulnclass !== "all" ? { vulnclass: f.vulnclass } : {}),
|
||||
...(f.task && f.task !== "all" ? { task_id: f.task } : {}),
|
||||
...(f.query?.trim() ? { q: f.query.trim() } : {}),
|
||||
...(f.from ? { from: f.from } : {}),
|
||||
...(f.to ? { to: f.to } : {}),
|
||||
...(f.assetScope ? { asset_scope: f.assetScope } : {}),
|
||||
};
|
||||
}
|
||||
return del<{ deleted: number }>("/exploration/findings", body);
|
||||
},
|
||||
findingRetests: (id: string) =>
|
||||
get<{ retests: FindingRetest[] }>(`/exploration/findings/${encodeURIComponent(id)}/retests`).then((r) =>
|
||||
arr(r.retests),
|
||||
|
||||
@@ -58,6 +58,9 @@ export const tasks: Task[] = [
|
||||
description: "Acme 官网与后台外部渗透(acme.com)",
|
||||
goal: "拿到 acme.com 后台管理权限,确认可读取用户敏感数据。",
|
||||
status: "running",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-24T09:12:00Z"),
|
||||
created_unix: 1785489120,
|
||||
active_run_seconds: 28800,
|
||||
@@ -87,6 +90,9 @@ export const tasks: Task[] = [
|
||||
description: "api.acme.com 越权与注入测试",
|
||||
goal: "评估 api.acme.com 订单/用户接口的越权(IDOR)与注入风险。",
|
||||
status: "running",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-25T14:05:00Z"),
|
||||
created_unix: 1785592500,
|
||||
active_run_seconds: 14400,
|
||||
@@ -116,6 +122,9 @@ export const tasks: Task[] = [
|
||||
description: "shop.acme.com 支付与订单链路",
|
||||
goal: "评估支付与订单接口的越权、金额篡改与竞态风险。",
|
||||
status: "paused",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 3,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-22T08:30:00Z"),
|
||||
created_unix: 1785313800,
|
||||
active_run_seconds: 21600,
|
||||
@@ -144,6 +153,9 @@ export const tasks: Task[] = [
|
||||
description: "对外暴露面侦察(VPN / 边界服务)",
|
||||
goal: "识别 acme.com 对外暴露的可利用边界服务。",
|
||||
status: "done",
|
||||
worker_count: 0,
|
||||
worker_actual_count: 0,
|
||||
worker_target_count: 3,
|
||||
created_at: T("2026-07-18T08:00:00Z"),
|
||||
created_unix: 1784966400,
|
||||
active_run_seconds: 86400,
|
||||
|
||||
@@ -48,6 +48,7 @@ const mockInterceptHistory = structuredClone(D.interceptHistory);
|
||||
const mockInterceptPending = structuredClone(D.interceptPending);
|
||||
const mockInterceptDetails = structuredClone(D.interceptDetails);
|
||||
const mockTasks = structuredClone(D.tasks);
|
||||
const mockWorkerDrainUntil = new Map<string, number>();
|
||||
const mockFindings = structuredClone(D.findings);
|
||||
const mockLLMRecords = structuredClone(D.llmRecords);
|
||||
const mockTaskTemplates = structuredClone(D.taskTemplates);
|
||||
@@ -256,7 +257,33 @@ function mockTaskArchiveBlocker(taskID: string): string | undefined {
|
||||
)?.id;
|
||||
}
|
||||
|
||||
function reconcileMockWorkers(task: Task): void {
|
||||
const target = task.worker_count || D.settings.workers || 3;
|
||||
const previousTarget = task.worker_target_count;
|
||||
task.worker_target_count = target;
|
||||
if (task.status !== "running" && task.status !== "paused") {
|
||||
task.worker_actual_count = 0;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
return;
|
||||
}
|
||||
const actual = task.worker_actual_count ?? target;
|
||||
if (actual <= target) {
|
||||
task.worker_actual_count = target;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
} else {
|
||||
// Demo loops drain independently of in_flight; retain them across polls briefly.
|
||||
if (!mockWorkerDrainUntil.has(task.id) || previousTarget !== target) {
|
||||
mockWorkerDrainUntil.set(task.id, Date.now() + 10_000);
|
||||
}
|
||||
if (Date.now() >= (mockWorkerDrainUntil.get(task.id) ?? 0)) {
|
||||
task.worker_actual_count = target;
|
||||
mockWorkerDrainUntil.delete(task.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function publicMockTask(task: Task): Task {
|
||||
reconcileMockWorkers(task);
|
||||
const item = structuredClone(task);
|
||||
item.numeric_id = mockTaskAssetIDs.get(task.id);
|
||||
item.share_global_assets = task.share_global_assets ?? false;
|
||||
@@ -483,6 +510,10 @@ function mockFilterFindings(q: URLSearchParams): (typeof mockFindings)[number][]
|
||||
if (vulnclass) list = list.filter((finding) => finding.vulnclass === vulnclass);
|
||||
if (taskID === "__unassigned__") list = list.filter((finding) => !finding.task_id);
|
||||
else if (taskID) list = list.filter((finding) => finding.task_id === taskID);
|
||||
const fromTs = q.get("from") ? Date.parse(q.get("from") as string) : Number.NaN;
|
||||
const toTs = q.get("to") ? Date.parse(q.get("to") as string) : Number.NaN;
|
||||
if (Number.isFinite(fromTs)) list = list.filter((finding) => Date.parse(finding.ts) >= fromTs);
|
||||
if (Number.isFinite(toTs)) list = list.filter((finding) => Date.parse(finding.ts) <= toTs);
|
||||
return list;
|
||||
}
|
||||
|
||||
@@ -1323,6 +1354,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
company_ids: companyIDs,
|
||||
share_global_assets: b.share_global_assets === true,
|
||||
};
|
||||
reconcileMockWorkers(created);
|
||||
// Validate the attached preview schedule before mutating task state.
|
||||
const numericTaskID = nextMockTaskAssetID;
|
||||
if (b.schedule && typeof b.schedule === "object") {
|
||||
@@ -1527,8 +1559,10 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
const namePresent = has("name") && b.name !== null;
|
||||
const remarkPresent = has("remark") && b.remark !== null;
|
||||
const pinnedPresent = has("pinned") && b.pinned !== null;
|
||||
if (!namePresent && !remarkPresent && !pinnedPresent && !sharingPresent)
|
||||
throw new Error("至少需要提供 name、pinned、remark 或 share_global_assets");
|
||||
const workerCountPresent = has("worker_count") && b.worker_count !== null;
|
||||
const nextWorkerCount = workerCountPresent ? mockWorkerCount(b.worker_count) : task.worker_count;
|
||||
if (!namePresent && !remarkPresent && !pinnedPresent && !sharingPresent && !workerCountPresent)
|
||||
throw new Error("至少需要提供 name、pinned、remark、share_global_assets 或 worker_count");
|
||||
let nextName = task.name;
|
||||
let nextRemark = task.remark;
|
||||
let nextPinned = task.pinned;
|
||||
@@ -1550,8 +1584,9 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
task.remark = nextRemark;
|
||||
task.pinned = nextPinned;
|
||||
task.pinned_at = nextPinnedAt;
|
||||
task.worker_count = nextWorkerCount;
|
||||
sortMockTasks();
|
||||
return structuredClone(task);
|
||||
return publicMockTask(task);
|
||||
}
|
||||
if (seg[0] === "tasks" && seg.length === 2 && m === "DELETE") {
|
||||
const id = seg[1];
|
||||
@@ -2317,6 +2352,11 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (seg[0] === "exploration" && seg[1] === "findings" && seg.length === 3 && seg[2] !== "stats") {
|
||||
const f = mockFindings.find((x) => x.id === seg[2]);
|
||||
if (!f) return {};
|
||||
if (m === "DELETE") {
|
||||
const idx = mockFindings.findIndex((x) => x.id === seg[2]);
|
||||
if (idx >= 0) mockFindings.splice(idx, 1);
|
||||
return { deleted: idx >= 0, id: Number(seg[2]) || 0 };
|
||||
}
|
||||
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;
|
||||
@@ -2339,6 +2379,41 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
};
|
||||
}
|
||||
if (path === "/exploration/findings") {
|
||||
if (m === "DELETE") {
|
||||
const scope = (typeof b.scope === "string" ? b.scope : q.get("scope"))?.trim() ?? "";
|
||||
let targets: (typeof mockFindings)[number][] = [];
|
||||
if (scope === "all") {
|
||||
targets = [...mockFindings];
|
||||
} else if (scope === "selected") {
|
||||
const rawIds = Array.isArray(b.ids)
|
||||
? b.ids.map((v) => String(v))
|
||||
: (q.get("ids") ?? "")
|
||||
.split(",")
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
const idSet = new Set(rawIds);
|
||||
targets = mockFindings.filter((f) => idSet.has(f.id));
|
||||
} else if (scope === "filtered") {
|
||||
const params = new URLSearchParams(q);
|
||||
if (b.filters && typeof b.filters === "object") {
|
||||
for (const [k, v] of Object.entries(b.filters as Record<string, unknown>)) {
|
||||
if (typeof v === "string" && v) params.set(k, v);
|
||||
}
|
||||
}
|
||||
targets = mockApplyAssetScope(mockFilterFindings(params), params.get("asset_scope"));
|
||||
} else {
|
||||
throw new Error(`bad scope: ${scope}`);
|
||||
}
|
||||
const targetSet = new Set(targets.map((f) => f.id));
|
||||
let deleted = 0;
|
||||
for (let i = mockFindings.length - 1; i >= 0; i--) {
|
||||
if (targetSet.has(mockFindings[i].id)) {
|
||||
mockFindings.splice(i, 1);
|
||||
deleted++;
|
||||
}
|
||||
}
|
||||
return { deleted };
|
||||
}
|
||||
// finding_id=id:真后端用独立表行 id 作为状态/详情句柄,mock 里用自身 id 顶上。
|
||||
// report 仅详情接口返回,列表剥掉(与后端一致)。
|
||||
const withFid = (f: (typeof mockFindings)[number]) => ({
|
||||
@@ -2463,6 +2538,7 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
next.workers = next.worker_pools.reduce((sum, pool) => sum + Number(pool.workers), 0);
|
||||
}
|
||||
Object.assign(D.settings, next);
|
||||
for (const task of mockTasks) reconcileMockWorkers(task);
|
||||
return next;
|
||||
}
|
||||
if (path === "/settings/basic-auth" && m === "GET") return { enabled: false, username: "", password_set: false };
|
||||
|
||||
@@ -26,6 +26,8 @@ export interface Task {
|
||||
id: string;
|
||||
remark?: string;
|
||||
worker_count?: number; // 本任务 Worker 数;0/缺省=用全局默认
|
||||
worker_actual_count?: number; // 当前存活的 Worker pool loops,含缩容退出中的 loops
|
||||
worker_target_count?: number; // 当前期望的 Worker slots 数量
|
||||
name?: string; // 可选任务名称;空/缺省=未命名,展示时回退到描述
|
||||
category_id?: number;
|
||||
category_name?: string;
|
||||
@@ -1028,7 +1030,7 @@ export interface Settings {
|
||||
show_egress_ip?: boolean; // 在顶栏显示直连 / 全局代理出口 IP;默认关闭
|
||||
egress_probe_url?: string; // 自定义 IP 探测服务;空=默认公共回显服务
|
||||
python_interpreter?: string; // 自定义脚本工具的 python 解释器路径(空=运行时检测)
|
||||
workers?: number; // 并发工作 agent 数(默认3);对之后启动的任务生效
|
||||
workers?: number; // 并发工作 agent 数(默认3);热更新跟随全局配置的任务
|
||||
worker_pools: WorkerPool[];
|
||||
// 任务并发上限:同时「运行中」的任务数上限。关闭=不限;开启后新建任务超限则排队,有空位自动启动。
|
||||
task_concurrency_enabled?: boolean; // 默认 false
|
||||
|
||||
Reference in new issue
Block a user