mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-12-04 20:41:51 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7bf75f535 |
No files matched your search
@@ -95,6 +95,7 @@ const mainAgentDefaultTmpl = `你是一个授权渗透测试系统的"主 agent"
|
||||
**当任务目标已全部达成时**(graph_overview 里 goals 均为 met):下发前先判断这条意图背后是否隐含一个"新的、要达成的结果"。若隐含,用一句话把你猜测的目标复述给人,并**反问是否要登记为正式目标**——人要 → 用 set_goals 登记(任务随后进入常规规划、规划者会自主往下推进);人不要 / 只是想临时探一下 → 只 add_intent 下发这一条,worker 执行完任务即回到已完成状态(不会自主继续)。若这条意图明显只是一次性查证、不隐含新目标,直接 add_intent 即可,不必每次都问。
|
||||
- 人想"对某条正在运行的意图(work)实时纠偏(别再走 X、聚焦 Y)" → 用 steer_work(不打断、不丢已有进展,worker 下一步动作前生效);先用 get_worker_output 看它在干嘛。方向整个错了则改用 add_intent 另下新意图。
|
||||
- 人想"新增一个要达成的最终目标" → 用 set_goals 增补目标。系统会把该目标写入任务图并**自动把已完成/暂停的任务拉回运行态继续跑**(规划者随后会据此重新判断是否达成),无需人工再点恢复。
|
||||
- 人想"恢复已暂停的任务,或重新打开已结束但仍有未完成目标/待执行(open)意图的任务" → 用 resume_task 原地将当前任务拉回运行态继续跑(保留已有探索图、发现与 frontier),不必新建重复任务。
|
||||
- 人想"增/改测试约束(允许/禁止某类操作,如『仅测当前端口』『禁止爆破』『只做被动侦察』)" → 用 set_constraints 登记(type=allow 允许 / type=deny 禁止)。约束会在下一轮规划时注入 planner/worker 的提示词以框定探索边界;也可在总览「约束管理」里增删改。
|
||||
3. 用人话简洁回复,说明你做了什么。
|
||||
|
||||
|
||||
@@ -15,11 +15,12 @@ package agent
|
||||
const autoDefaultTmpl = `你是 **Auto**,这个渗透测试平台的「操作助手」。你不亲自渗透,而是**用工具操作平台**、按用户指令把事情办好。
|
||||
|
||||
你能做的(取决于给你开放了哪些工具):
|
||||
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、add_task_hint 给任务注入提示。
|
||||
1. **任务操作**:list_tasks 看全局、spawn_task 起子任务、get_task_graph / list_task_findings 读某任务的进展与漏洞、get_task_worker_trace 看某个 work 的执行过程、pause_task 暂停、resume_task 恢复暂停任务或原地重新打开已结束且仍有未完成目标/待执行意图的任务、add_task_hint 给任务注入提示、set_task_goals 给任务增补最终目标(自动拉回运行态)、add_task_intent 给任务直投高优先级探索意图(自动拉回运行态)。
|
||||
2. **平台管理**:create_skill / update_skill 建改技能;create_custom_tool / update_custom_tool 建改自定义工具(command/script/http);create_mcp / update_mcp 建改 MCP 服务器。
|
||||
|
||||
原则:
|
||||
- 先看清现状(list_tasks / get_task_graph 等)再动手;一步到位、少空转。
|
||||
- **原地继续优先于新建任务**:当用户要求继续、重开或补充已暂停/已结束的已有任务时,优先在原任务上操作(仍有 open 目标或 open 意图 → 用 resume_task 原地恢复;需要新增最终目标 → 用 set_task_goals;需要立刻测具体方向 → 用 add_task_intent),保留已有探索图与发现,不要用 spawn_task 新建重复任务。
|
||||
- 涉及漏洞资产或拓扑时,优先使用用户引用快照中的 asset_topology.zone/zone_reason;三层区域含义固定为 internet(互联网入口)、boundary(公开暴露服务/应用/端点)、internal(私有地址及其业务资产)。不要仅凭 kind 改写区域,也不要把没有真实关系证据的跨区连接说成已验证通路。
|
||||
- 建/改 skill、工具、MCP 时,把用户意图翻译成正确的结构化参数(kind/exec/schema 等),字段拿不准就按最小可用填。
|
||||
- 用人话简洁汇报你做了什么、结果如何;只根据工具真实返回作答,不臆造。
|
||||
|
||||
@@ -221,6 +221,8 @@ func (t *ToolSet) ListWorkerTracesTool() actool.CoreTool { return t.listWorker
|
||||
func (t *ToolSet) SearchWorkerTracesTool() actool.CoreTool { return t.searchAllWorkerTraces() }
|
||||
func (t *ToolSet) NodeDetailTool() actool.CoreTool { return t.nodeDetail() }
|
||||
func (t *ToolSet) AddHintTool() actool.CoreTool { return t.addHint() }
|
||||
func (t *ToolSet) AddIntentTool() actool.CoreTool { return t.addIntent() }
|
||||
func (t *ToolSet) SetGoalsTool() actool.CoreTool { return t.setGoals() }
|
||||
|
||||
// SetEnrich wires the async enrichment engine (DNS/HTTP auto-completion).
|
||||
func (t *ToolSet) SetEnrich(e EnrichTrigger) { t.enrich = e }
|
||||
|
||||
@@ -80,9 +80,6 @@ func normalizeArchivedFindingVersions(raw json.RawMessage) (json.RawMessage, err
|
||||
row[key] = 0
|
||||
}
|
||||
}
|
||||
if row["remark"] == nil {
|
||||
row["remark"] = ""
|
||||
}
|
||||
}
|
||||
return json.Marshal(rows)
|
||||
}
|
||||
+7
-52
@@ -10,7 +10,6 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// DBFinding is a row in the standalone findings table. It persists across task
|
||||
@@ -35,7 +34,6 @@ type DBFinding struct {
|
||||
Worker string
|
||||
AssetIDs []int64
|
||||
Status string
|
||||
Remark string // 人工备注
|
||||
Report string // 详细报告(Markdown);仅 GetFinding 填充,列表查询不带
|
||||
ReportConversationID *int64 `json:"report_conversation_id,omitempty"`
|
||||
CreatedAt time.Time
|
||||
@@ -82,9 +80,6 @@ func ValidSeverity(s string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// MaxFindingRemarkRunes is the maximum rune count allowed for a finding remark.
|
||||
const MaxFindingRemarkRunes = 2000
|
||||
|
||||
// AddFinding inserts a finding into the standalone findings table. taskID and
|
||||
// nodeID may be 0 (stored as NULL). name may be "" (frontend falls back to
|
||||
// vulnclass). Returns the new finding id.
|
||||
@@ -112,7 +107,7 @@ func (d *DB) AddFinding(taskID, nodeID int64, vulnclass, name, severity, summary
|
||||
// findingSelectCols is the column list (with task_description join) every finding
|
||||
// list query selects, so scanFinding stays in sync across callers.
|
||||
const findingSelectCols = `f.id, f.task_id, f.node_id, f.vulnclass, COALESCE(f.name, ''), f.severity, f.summary,
|
||||
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), COALESCE(f.remark, ''), f.created_at,
|
||||
f.evidence, f.worker, f.asset_ids, COALESCE(f.status, 'pending'), f.created_at,
|
||||
COALESCE(t.description, '') AS task_description, f.evidence_version, f.report_evidence_version,
|
||||
(SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=f.id)`
|
||||
|
||||
@@ -127,7 +122,7 @@ func scanFindings(rows interface {
|
||||
f := &DBFinding{}
|
||||
var aidsJSON string
|
||||
if err := rows.Scan(&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt, &f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount); err != nil {
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt, &f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(aidsJSON), &f.AssetIDs)
|
||||
@@ -254,9 +249,8 @@ func (f FindingFilter) where() (string, []any) {
|
||||
f.vulnclass ILIKE %s ESCAPE '\' OR
|
||||
f.summary ILIKE %s ESCAPE '\' OR
|
||||
f.evidence ILIKE %s ESCAPE '\' OR
|
||||
COALESCE(f.remark, '') ILIKE %s ESCAPE '\' OR
|
||||
COALESCE(f.report, '') ILIKE %s ESCAPE '\'
|
||||
)`, placeholder, placeholder, placeholder, placeholder, placeholder, placeholder))
|
||||
)`, placeholder, placeholder, placeholder, placeholder, placeholder))
|
||||
}
|
||||
if len(conds) == 0 {
|
||||
return "", args
|
||||
@@ -544,7 +538,7 @@ func (d *DB) ListFindingsForExport(f FindingFilter, ids []int64) ([]*DBFinding,
|
||||
f := &DBFinding{}
|
||||
var aidsJSON string
|
||||
if err := rows.Scan(&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt,
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt,
|
||||
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -711,7 +705,7 @@ func (d *DB) GetFinding(id int64) (*DBFinding, error) {
|
||||
LEFT JOIN tasks t ON f.task_id = t.id
|
||||
WHERE f.id = $1`, id).Scan(
|
||||
&f.ID, &f.TaskID, &f.NodeID, &f.VulnClass, &f.Name, &f.Severity,
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.Remark, &f.CreatedAt,
|
||||
&f.Summary, &f.Evidence, &f.Worker, &aidsJSON, &f.Status, &f.CreatedAt,
|
||||
&f.TaskDescription, &f.EvidenceVersion, &f.ReportEvidenceVersion, &f.TrafficCount, &f.Report, &reportConv)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
@@ -993,43 +987,6 @@ func (d *DB) SetFindingVulnClass(id int64, vulnclass string) (int64, error) {
|
||||
return d.setFindingCol(id, "vulnclass", "vulnclass", vulnclass)
|
||||
}
|
||||
|
||||
// SetFindingSummary updates one finding's summary (+ node payload sync).
|
||||
func (d *DB) SetFindingSummary(id int64, summary string) (int64, error) {
|
||||
return d.setFindingCol(id, "summary", "summary", summary)
|
||||
}
|
||||
|
||||
// SetFindingEvidence updates one finding's evidence text on the standalone findings row.
|
||||
func (d *DB) SetFindingEvidence(id int64, evidence string) (int64, error) {
|
||||
res, err := d.Exec(`UPDATE findings SET evidence=$1 WHERE id=$2`, evidence, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// SetFindingReport updates one finding's Markdown report and aligns report_evidence_version
|
||||
// with the current evidence_version so manual edits clear any stale-report warning.
|
||||
func (d *DB) SetFindingReport(id int64, report string) (int64, error) {
|
||||
res, err := d.Exec(`UPDATE findings SET report=$1, report_evidence_version=evidence_version WHERE id=$2`, report, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// SetFindingRemark updates one finding's manual remark. Returns rows affected.
|
||||
func (d *DB) SetFindingRemark(id int64, remark string) (int64, error) {
|
||||
remark = strings.TrimSpace(remark)
|
||||
if utf8.RuneCountInString(remark) > MaxFindingRemarkRunes {
|
||||
return 0, fmt.Errorf("备注最多 %d 个字符", MaxFindingRemarkRunes)
|
||||
}
|
||||
res, err := d.Exec(`UPDATE findings SET remark=$1 WHERE id=$2`, remark, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return res.RowsAffected()
|
||||
}
|
||||
|
||||
// FindingMeta is the standalone-row data (id, triage state, anchored assets) the
|
||||
// per-task view grafts onto its exploration-node findings.
|
||||
type FindingMeta struct {
|
||||
@@ -1037,8 +994,6 @@ type FindingMeta struct {
|
||||
|
||||
ID int64
|
||||
Status string
|
||||
Remark string
|
||||
Evidence string
|
||||
AssetIDs []int64
|
||||
}
|
||||
|
||||
@@ -1057,7 +1012,7 @@ func (d *DB) FindingMetaByNodeID(taskID int64) (map[int64]FindingMeta, error) {
|
||||
if taskID <= 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := d.Query(`SELECT node_id, id, COALESCE(status,'pending'), COALESCE(remark,''), COALESCE(evidence,''), asset_ids, (SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=findings.id) FROM findings
|
||||
rows, err := d.Query(`SELECT node_id, id, COALESCE(status,'pending'), asset_ids, (SELECT count(*) FROM finding_traffic_bindings b WHERE b.finding_id=findings.id) FROM findings
|
||||
WHERE task_id=$1 AND node_id IS NOT NULL`, taskID)
|
||||
if err != nil {
|
||||
return out, err
|
||||
@@ -1067,7 +1022,7 @@ func (d *DB) FindingMetaByNodeID(taskID int64) (map[int64]FindingMeta, error) {
|
||||
var nid int64
|
||||
var m FindingMeta
|
||||
var aidsJSON string
|
||||
if err := rows.Scan(&nid, &m.ID, &m.Status, &m.Remark, &m.Evidence, &aidsJSON, &m.TrafficCount); err != nil {
|
||||
if err := rows.Scan(&nid, &m.ID, &m.Status, &aidsJSON, &m.TrafficCount); err != nil {
|
||||
return out, err
|
||||
}
|
||||
_ = json.Unmarshal([]byte(aidsJSON), &m.AssetIDs)
|
||||
|
||||
@@ -644,97 +644,3 @@ func TestDeleteFindings(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindingRemarkAndManualEdit(t *testing.T) {
|
||||
d, err := Open(testDSN(t))
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
defer d.Close()
|
||||
|
||||
vc := fmt.Sprintf("__test_finding_remark_%d__", time.Now().UnixNano())
|
||||
tk, err := d.CreateTask("remark test", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateTask: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = d.Exec(`DELETE FROM findings WHERE vulnclass=$1`, vc)
|
||||
_ = d.DeleteTask(tk.ID)
|
||||
})
|
||||
|
||||
es := d.Exploration(tk.ExplorationID)
|
||||
nodeID, err := es.AddNode(KindFinding, map[string]any{
|
||||
"vulnclass": vc,
|
||||
"name": "old title",
|
||||
"severity": SeverityMedium,
|
||||
"summary": "old summary",
|
||||
"evidence": "old proof",
|
||||
}, 5, "confirmed", "tester", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("AddNode: %v", err)
|
||||
}
|
||||
fid, err := d.AddFinding(tk.ID, nodeID, vc, "old title", SeverityMedium, "old summary", "old proof", "tester", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("AddFinding: %v", err)
|
||||
}
|
||||
|
||||
if n, err := d.SetFindingRemark(fid, " 已人工复核,需要内网 Cookie "); err != nil || n != 1 {
|
||||
t.Fatalf("SetFindingRemark: n=%d err=%v", n, err)
|
||||
}
|
||||
if n, err := d.SetFindingSummary(fid, "updated summary"); err != nil || n != 1 {
|
||||
t.Fatalf("SetFindingSummary: n=%d err=%v", n, err)
|
||||
}
|
||||
if n, err := d.SetFindingEvidence(fid, "GET /admin HTTP/1.1"); err != nil || n != 1 {
|
||||
t.Fatalf("SetFindingEvidence: n=%d err=%v", n, err)
|
||||
}
|
||||
if n, err := d.SetFindingReport(fid, "## 手工报告\n已确认"); err != nil || n != 1 {
|
||||
t.Fatalf("SetFindingReport: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
got, err := d.GetFinding(fid)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetFinding: got=%+v err=%v", got, err)
|
||||
}
|
||||
if got.Remark != "已人工复核,需要内网 Cookie" || got.Summary != "updated summary" || got.Evidence != "GET /admin HTTP/1.1" || got.Report != "## 手工报告\n已确认" {
|
||||
t.Fatalf("unexpected updated finding: %+v", got)
|
||||
}
|
||||
|
||||
// Search must match remark.
|
||||
matches, total, err := d.ListFindingsPage(FindingFilter{VulnClass: vc, Query: "内网 Cookie"}, 1, 20)
|
||||
if err != nil || total != 1 || len(matches) != 1 || matches[0].ID != fid || matches[0].Remark != got.Remark {
|
||||
t.Fatalf("search by remark failed: matches=%+v total=%d err=%v", matches, total, err)
|
||||
}
|
||||
|
||||
// Per-task metadata must expose remark and updated evidence.
|
||||
meta, err := d.FindingMetaByNodeID(tk.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("FindingMetaByNodeID: %v", err)
|
||||
}
|
||||
if m := meta[nodeID]; m.Remark != got.Remark || m.Evidence != "GET /admin HTTP/1.1" {
|
||||
t.Fatalf("FindingMetaByNodeID mismatch: %+v", m)
|
||||
}
|
||||
|
||||
// Over-limit remark must be rejected without modifying stored value.
|
||||
tooLong := strings.Repeat("备", MaxFindingRemarkRunes+1)
|
||||
if _, err := d.SetFindingRemark(fid, tooLong); err == nil {
|
||||
t.Fatal("expected over-limit remark to fail")
|
||||
}
|
||||
afterErr, _ := d.GetFinding(fid)
|
||||
if afterErr.Remark != got.Remark {
|
||||
t.Fatalf("remark mutated on error: %q", afterErr.Remark)
|
||||
}
|
||||
|
||||
// Clearing remark to empty string must succeed.
|
||||
if n, err := d.SetFindingRemark(fid, " "); err != nil || n != 1 {
|
||||
t.Fatalf("clear remark: n=%d err=%v", n, err)
|
||||
}
|
||||
cleared, _ := d.GetFinding(fid)
|
||||
if cleared.Remark != "" {
|
||||
t.Fatalf("expected empty remark, got %q", cleared.Remark)
|
||||
}
|
||||
|
||||
// Unknown IDs return 0 affected rows.
|
||||
if n, err := d.SetFindingRemark(-1, "x"); err != nil || n != 0 {
|
||||
t.Fatalf("SetFindingRemark(-1): n=%d err=%v", n, err)
|
||||
}
|
||||
}
|
||||
@@ -1181,15 +1181,12 @@ CREATE TABLE IF NOT EXISTS findings (
|
||||
-- 漏洞详细报告(Markdown);默认空,仅详情页读取/展示,不进列表接口以免 payload 膨胀。
|
||||
report TEXT NOT NULL DEFAULT '',
|
||||
report_conversation_id BIGINT REFERENCES conversations(id) ON DELETE SET NULL,
|
||||
-- 人工备注;默认空,供漏洞详情页与列表记录复核/排查备忘。
|
||||
remark TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE findings ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'pending';
|
||||
ALTER TABLE findings ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE findings ADD COLUMN IF NOT EXISTS report_conversation_id BIGINT REFERENCES conversations(id) ON DELETE SET NULL;
|
||||
ALTER TABLE findings ADD COLUMN IF NOT EXISTS remark TEXT NOT NULL DEFAULT '';
|
||||
CREATE INDEX IF NOT EXISTS idx_findings_task ON findings(task_id, created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_findings_time ON findings(created_at DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_findings_status ON findings(status, created_at DESC);
|
||||
|
||||
+1
-8
@@ -79,9 +79,6 @@ func FindingsMarkdown(fs []*db.DBFinding, generatedAt time.Time) string {
|
||||
if s := strings.TrimSpace(f.Summary); s != "" {
|
||||
fmt.Fprintf(&b, "%s\n\n", s)
|
||||
}
|
||||
if rm := strings.TrimSpace(f.Remark); rm != "" {
|
||||
fmt.Fprintf(&b, "**备注:**\n\n%s\n\n", rm)
|
||||
}
|
||||
if e := strings.TrimSpace(f.Evidence); e != "" {
|
||||
fmt.Fprintf(&b, "**证据:**\n\n```\n%s\n```\n\n", e)
|
||||
}
|
||||
@@ -113,9 +110,6 @@ func SingleFindingMarkdown(f *db.DBFinding, generatedAt time.Time) string {
|
||||
if s := strings.TrimSpace(f.Summary); s != "" {
|
||||
fmt.Fprintf(&b, "## 概述\n\n%s\n\n", s)
|
||||
}
|
||||
if rm := strings.TrimSpace(f.Remark); rm != "" {
|
||||
fmt.Fprintf(&b, "## 备注\n\n%s\n\n", rm)
|
||||
}
|
||||
if e := strings.TrimSpace(f.Evidence); e != "" {
|
||||
fmt.Fprintf(&b, "## 证据\n\n```\n%s\n```\n\n", e)
|
||||
}
|
||||
@@ -161,7 +155,7 @@ func FindingsCSV(fs []*db.DBFinding) []byte {
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("\xEF\xBB\xBF") // UTF-8 BOM
|
||||
w := csv.NewWriter(&buf)
|
||||
_ = w.Write([]string{"ID", "名称", "类别", "严重等级", "状态", "所属任务", "发现时间", "概述", "备注", "流量证据数量", "流量证据ID"})
|
||||
_ = w.Write([]string{"ID", "名称", "类别", "严重等级", "状态", "所属任务", "发现时间", "概述", "流量证据数量", "流量证据ID"})
|
||||
for _, f := range items {
|
||||
id := fmt.Sprintf("%d", f.ID)
|
||||
if f.ExportCaseID > 0 {
|
||||
@@ -176,7 +170,6 @@ func FindingsCSV(fs []*db.DBFinding) []byte {
|
||||
f.TaskDescription,
|
||||
f.CreatedAt.Format("2006-01-02 15:04:05"),
|
||||
strings.TrimSpace(f.Summary),
|
||||
strings.TrimSpace(f.Remark),
|
||||
fmt.Sprint(len(f.TrafficBindings)), findingTrafficIDs(f),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -364,7 +364,6 @@ type FindingDTO struct {
|
||||
Status string `json:"status"` // pending | in_progress | confirmed | resolved | fixed | false_positive | ignored | duplicate | risk_accepted
|
||||
Summary string `json:"summary"`
|
||||
Evidence string `json:"evidence"`
|
||||
Remark string `json:"remark,omitempty"` // 人工备注
|
||||
Report string `json:"report,omitempty"` // 详细报告(Markdown);仅详情接口返回,列表为空
|
||||
ReportConversationID *int64 `json:"report_conversation_id,omitempty"`
|
||||
|
||||
@@ -465,8 +464,6 @@ func findingDTOsForOwner(taskID, description string, in []*db.Node, meta map[int
|
||||
if m, ok := meta[n.ID]; ok {
|
||||
d.FindingID = i64s(m.ID)
|
||||
d.Status = m.Status
|
||||
d.Remark = m.Remark
|
||||
d.Evidence = m.Evidence
|
||||
d.TrafficCount = m.TrafficCount
|
||||
d.Assets = findingAssetDTOs(m.AssetIDs, assets)
|
||||
}
|
||||
@@ -505,7 +502,6 @@ func findingFromDB(f *db.DBFinding, assets map[int64]*db.Asset) FindingDTO {
|
||||
Status: status,
|
||||
Summary: f.Summary,
|
||||
Evidence: f.Evidence,
|
||||
Remark: f.Remark,
|
||||
Report: f.Report,
|
||||
ReportConversationID: f.ReportConversationID,
|
||||
TS: rfc3339(f.CreatedAt),
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Autumn-27/artex/db"
|
||||
"github.com/Autumn-27/artex/report"
|
||||
)
|
||||
|
||||
func TestReportExportsIncludeFindingRemark(t *testing.T) {
|
||||
now := time.Date(2026, 11, 27, 10, 0, 0, 0, time.UTC)
|
||||
f := &db.DBFinding{
|
||||
ID: 42,
|
||||
Name: "后台越权导出",
|
||||
VulnClass: "IDOR",
|
||||
Severity: db.SeverityHigh,
|
||||
Status: db.FindingConfirmed,
|
||||
Summary: "普通用户可导出管理员报表",
|
||||
Remark: "已与业务确认,本周五前修复",
|
||||
Evidence: "GET /api/export?id=1 HTTP/1.1",
|
||||
CreatedAt: now,
|
||||
}
|
||||
|
||||
combined := report.FindingsMarkdown([]*db.DBFinding{f}, now)
|
||||
if !strings.Contains(combined, "**备注:**\n\n已与业务确认,本周五前修复") {
|
||||
t.Fatalf("combined markdown missing remark:\n%s", combined)
|
||||
}
|
||||
single := report.SingleFindingMarkdown(f, now)
|
||||
if !strings.Contains(single, "## 备注\n\n已与业务确认,本周五前修复") {
|
||||
t.Fatalf("single markdown missing remark:\n%s", single)
|
||||
}
|
||||
csvOut := string(report.FindingsCSV([]*db.DBFinding{f}))
|
||||
if !strings.Contains(csvOut, "备注") || !strings.Contains(csvOut, "已与业务确认,本周五前修复") {
|
||||
t.Fatalf("csv missing remark:\n%s", csvOut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatchFindingManualEditAndRemark(t *testing.T) {
|
||||
dsn, _, err := db.DSN()
|
||||
if err != nil {
|
||||
t.Skip("test postgres not configured")
|
||||
}
|
||||
pg, err := db.Open(dsn)
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) — skipping", err)
|
||||
}
|
||||
t.Cleanup(func() { pg.Close() })
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
s := &Server{
|
||||
ctx: ctx,
|
||||
m: &Manager{pg: pg, dir: t.TempDir(), tasks: map[string]*Task{}},
|
||||
}
|
||||
|
||||
vc := fmt.Sprintf("__test_patch_finding_%d__", time.Now().UnixNano())
|
||||
fid, err := pg.AddFinding(0, 0, vc, "原始标题", db.SeverityMedium, "原始摘要", "原始证据", "worker", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("AddFinding: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = pg.Exec(`DELETE FROM findings WHERE id=$1`, fid) })
|
||||
|
||||
patch := func(id string, payload string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPatch, "/api/exploration/findings/"+id, bytes.NewBufferString(payload))
|
||||
req.SetPathValue("id", id)
|
||||
rec := httptest.NewRecorder()
|
||||
s.patchFinding(rec, req)
|
||||
return rec
|
||||
}
|
||||
idStr := fmt.Sprintf("%d", fid)
|
||||
|
||||
// Empty payload must return 400.
|
||||
if w := patch(idStr, `{}`); w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("empty patch: want 400 got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
|
||||
// Over-limit remark must return 400 and must NOT partially mutate name.
|
||||
tooLong := strings.Repeat("注", db.MaxFindingRemarkRunes+1)
|
||||
badBody, _ := json.Marshal(map[string]string{"name": "不应生效", "remark": tooLong})
|
||||
if w := patch(idStr, string(badBody)); w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("over-limit remark: want 400 got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
before, _ := pg.GetFinding(fid)
|
||||
if before.Name != "原始标题" || before.Remark != "" {
|
||||
t.Fatalf("validation failure mutated row: %+v", before)
|
||||
}
|
||||
|
||||
// Edit all fields at once.
|
||||
fullBody, _ := json.Marshal(map[string]string{
|
||||
"name": "手工修改后的标题",
|
||||
"vulnclass": vc + "_edited",
|
||||
"severity": db.SeverityCritical,
|
||||
"status": db.FindingConfirmed,
|
||||
"summary": "手工修改后的摘要",
|
||||
"evidence": " indented evidence line\nline 2",
|
||||
"report": "## 手工报告\n\n细节说明",
|
||||
"remark": " 需要复核支付接口权限 ",
|
||||
})
|
||||
w := patch(idStr, string(fullBody))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("full patch: want 200 got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
var dto FindingDTO
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &dto); err != nil {
|
||||
t.Fatalf("decode dto: %v", err)
|
||||
}
|
||||
if dto.Name != "手工修改后的标题" || dto.VulnClass != vc+"_edited" || dto.Severity != db.SeverityCritical ||
|
||||
dto.Status != db.FindingConfirmed || dto.Summary != "手工修改后的摘要" ||
|
||||
dto.Evidence != " indented evidence line\nline 2" || dto.Report != "## 手工报告\n\n细节说明" ||
|
||||
dto.Remark != "需要复核支付接口权限" {
|
||||
t.Fatalf("unexpected patched dto: %+v", dto)
|
||||
}
|
||||
|
||||
// Clearing remark to empty string persists cleanly.
|
||||
w = patch(idStr, `{"remark":" "}`)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("clear remark: want 200 got %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
var cleared FindingDTO
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &cleared); err != nil {
|
||||
t.Fatalf("decode cleared dto: %v", err)
|
||||
}
|
||||
if cleared.Remark != "" || cleared.Name != "手工修改后的标题" {
|
||||
t.Fatalf("unexpected cleared dto: %+v", cleared)
|
||||
}
|
||||
}
|
||||
@@ -140,8 +140,8 @@ func (s *Server) mcpTools() []mcpTool {
|
||||
},
|
||||
{
|
||||
Name: "resume_task", Scope: db.APIScopeTaskControl,
|
||||
Description: "恢复已暂停的任务。并发已满时任务会进入排队(status=queued)。",
|
||||
Schema: objSchema(map[string]any{"task_id": strParam("要恢复的任务 id")}, "task_id"),
|
||||
Description: "恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务。并发已满时任务会进入排队(status=queued)。",
|
||||
Schema: objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id")}, "task_id"),
|
||||
Run: func(_ context.Context, token *db.APIToken, in json.RawMessage) (actool.Result, error) {
|
||||
return s.mcpControlTask(token, in, "resume")
|
||||
},
|
||||
@@ -524,7 +524,15 @@ func (s *Server) mcpControlTask(token *db.APIToken, in json.RawMessage, action s
|
||||
if t == nil {
|
||||
return failure, nil
|
||||
}
|
||||
out, err := s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
|
||||
var (
|
||||
out taskControlResult
|
||||
err error
|
||||
)
|
||||
if action == "resume" {
|
||||
out, err = s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
|
||||
} else {
|
||||
out, err = s.applyTaskControlWithCause(t, action, agent.AbortPausedByOrchestrator)
|
||||
}
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
|
||||
+158
-11
@@ -69,9 +69,12 @@ func (s *Server) orchestrationTools() []actool.CoreTool {
|
||||
s.toolListLLMProfiles(),
|
||||
s.toolSpawnTask(),
|
||||
s.toolPauseTask(),
|
||||
s.toolResumeTask(),
|
||||
s.toolGetTaskGraph(),
|
||||
s.toolListTaskFindings(),
|
||||
s.toolAddHint(),
|
||||
s.toolSetTaskGoals(),
|
||||
s.toolAddTaskIntent(),
|
||||
s.toolGetWorkerTrace(),
|
||||
s.toolListWorkerTraces(),
|
||||
s.toolSearchWorkerTraces(),
|
||||
@@ -147,6 +150,20 @@ func wrTool(name, desc string, schema map[string]any, run func(context.Context,
|
||||
// delegateToTask resolves the `task_id` in the input, builds a ToolSet bound to
|
||||
// that task's store, strips task_id, and calls the chosen per-task tool — so the
|
||||
// cross-task read reuses the exact in-task logic against another task.
|
||||
func (s *Server) lookupTask(raw string) (*Task, bool) {
|
||||
trimmed := strings.TrimSpace(raw)
|
||||
if trimmed == "" {
|
||||
return nil, false
|
||||
}
|
||||
if t, ok := s.m.Task(trimmed); ok {
|
||||
return t, true
|
||||
}
|
||||
if id, ok := canonicalTaskID(trimmed); ok {
|
||||
return s.m.Task(id)
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick func(*agent.ToolSet) actool.CoreTool) (actool.Result, error) {
|
||||
var head struct {
|
||||
TaskID string `json:"task_id"`
|
||||
@@ -155,20 +172,31 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu
|
||||
if strings.TrimSpace(head.TaskID) == "" {
|
||||
return actool.Errorf("task_id 为必填"), nil
|
||||
}
|
||||
t, ok := s.m.Task(head.TaskID)
|
||||
t, ok := s.lookupTask(head.TaskID)
|
||||
if !ok {
|
||||
return actool.Errorf("task 不存在: " + head.TaskID), nil
|
||||
}
|
||||
if s.engine != nil {
|
||||
if !s.engine.beginTaskOperation(t.ID) {
|
||||
return actool.Errorf("任务正在删除,无法操作: " + t.ID), nil
|
||||
}
|
||||
defer s.engine.decInflight(t.ID)
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
_ = json.Unmarshal(in, &m)
|
||||
delete(m, "task_id")
|
||||
inner, _ := json.Marshal(m)
|
||||
tsx := agent.NewToolSet(t.Store, "orchestrator")
|
||||
if taskIDInt, err := strconv.ParseInt(t.ID, 10, 64); err == nil && taskIDInt > 0 {
|
||||
tsx.SetTaskID(taskIDInt)
|
||||
}
|
||||
if s.m.Assets() != nil {
|
||||
tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies())
|
||||
}
|
||||
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
|
||||
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
|
||||
tsx.SetNotify(t.Notify) // 通用唤醒(无专用回调的写操作走它;读工具为 no-op)
|
||||
tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_task_goals / add_task_intent → 把已完成/暂停的任务拉回 running
|
||||
tsx.SetNotifyGoal(t.NotifyGoal) // set_task_goals → 记一条「人新增了 N 个目标:…」触发并唤醒 planner
|
||||
tsx.SetNotifyHint(t.NotifyHint) // add_hint → 记一条「人新增了 N 条战略提示:…」触发并唤醒 planner
|
||||
return pick(tsx).Call(ctx, inner, nil)
|
||||
}
|
||||
|
||||
@@ -379,6 +407,39 @@ func (s *Server) toolPauseTask() actool.CoreTool {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolResumeTask() actool.CoreTool {
|
||||
return wrTool("resume_task",
|
||||
"恢复已暂停的任务,或原地重新打开已结束(done/failed/timeout)且仍有未完成目标或待执行(open)意图的任务继续运行(保留已有探索图、发现与 frontier,不新建重复任务)。当用户要求继续/重开已有任务时,优先使用本工具(或 set_task_goals / add_task_intent),不要用 spawn_task 另起重复任务。",
|
||||
objSchema(map[string]any{"task_id": strParam("要恢复/重新打开的任务 id;在任务内主 Agent 对话中可省略(默认当前任务)")}),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
var a struct {
|
||||
TaskID string `json:"task_id"`
|
||||
}
|
||||
_ = json.Unmarshal(in, &a)
|
||||
rawID := strings.TrimSpace(a.TaskID)
|
||||
if info := agent.RunInfoFrom(ctx); info.TaskID > 0 {
|
||||
curID := strconv.FormatInt(info.TaskID, 10)
|
||||
if rawID == "" {
|
||||
rawID = curID
|
||||
} else if canon, ok := canonicalTaskID(rawID); !ok || canon != curID {
|
||||
return actool.Errorf(fmt.Sprintf("当前在任务 #%s 上下文中,只能恢复当前任务", curID)), nil
|
||||
}
|
||||
}
|
||||
if rawID == "" {
|
||||
return actool.Errorf("task_id 为必填"), nil
|
||||
}
|
||||
t, ok := s.lookupTask(rawID)
|
||||
if !ok {
|
||||
return actool.Errorf("task 不存在: " + rawID), nil
|
||||
}
|
||||
res, err := s.resumeOrReopenTask(t, agent.AbortPausedByOrchestrator)
|
||||
if err != nil {
|
||||
return actool.Errorf(err.Error()), nil
|
||||
}
|
||||
return jsonResult(map[string]any{"task_id": t.ID, "status": res.Status, "queued": res.Queued})
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolGetTaskGraph() actool.CoreTool {
|
||||
return roTool("get_task_graph", "读指定任务的探索图总览(同 graph_overview:资产计数/frontier/发现/覆盖等),用 task_id 指定任务。",
|
||||
objSchema(map[string]any{"task_id": strParam("任务 id")}, "task_id"),
|
||||
@@ -410,6 +471,38 @@ func (s *Server) toolAddHint() actool.CoreTool {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolSetTaskGoals() actool.CoreTool {
|
||||
return wrTool("set_task_goals",
|
||||
"给指定任务新增探索目标(goal),写入任务图并自动把已完成/暂停的任务拉回运行态继续规划执行(保留已有图谱与发现,无需另起新任务)。\n"+
|
||||
"★优先批量:多个目标放进 goals 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 goals 直接给顶层 text。",
|
||||
objSchema(map[string]any{
|
||||
"task_id": strParam("任务 id"),
|
||||
"goals": map[string]any{"type": "array", "description": "【优先用这个】要新增的目标数组,按顺序处理。每个元素:text(必填,一个独立可验证的最终目标)+ vulnclass(可选)。", "items": objSchema(map[string]any{"text": strParam("一个独立可验证的最终目标"), "vulnclass": strParam("可选:对应漏洞类,如 SQLi/IDOR")}, "text")},
|
||||
"text": strParam("[单条] 一个独立可验证的最终目标"),
|
||||
"vulnclass": strParam("[单条] 对应漏洞类(若明确),如 SQLi/IDOR;业务逻辑目标可留空"),
|
||||
}, "task_id"),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
return s.delegateToTask(ctx, in, (*agent.ToolSet).SetGoalsTool)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolAddTaskIntent() actool.CoreTool {
|
||||
return wrTool("add_task_intent",
|
||||
"给指定任务直接下发探索意图(intent)写入 frontier,并自动把已完成/暂停的任务拉回运行态让 worker 领取执行(保留已有图谱与发现,无需另起新任务)。\n"+
|
||||
"★优先批量:多个方向放进 intents 数组一次提交(返回 ids 与之等长同序,失败项 id=0,详情见 errors);单条则省略 intents 直接给顶层 summary。",
|
||||
objSchema(map[string]any{
|
||||
"task_id": strParam("任务 id"),
|
||||
"intents": map[string]any{"type": "array", "description": "【优先用这个】要新增的探索方向数组,每个元素字段同顶层(summary/asset_ids/parent_ids/priority)。", "items": objSchema(map[string]any{"summary": strParam("探索方向摘要"), "asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}}, "priority": map[string]any{"type": "integer"}}, "summary")},
|
||||
"summary": strParam("[单条] 一句话描述这个探索方向:做什么+为什么"),
|
||||
"asset_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "目标资产 id(可选,0/1/多个)"},
|
||||
"parent_ids": map[string]any{"type": "array", "items": map[string]any{"type": "integer"}, "description": "上游锚点 fact/finding 节点 id(可选,0/1/多个;顶层全新方向请留空)"},
|
||||
"priority": map[string]any{"type": "integer", "description": "优先级 0-10,默认 5;直投紧急意图建议 8-10"},
|
||||
}, "task_id"),
|
||||
func(ctx context.Context, in json.RawMessage) (actool.Result, error) {
|
||||
return s.delegateToTask(ctx, in, (*agent.ToolSet).AddIntentTool)
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) toolGetWorkerTrace() actool.CoreTool {
|
||||
return roTool("get_task_worker_trace",
|
||||
"看指定任务里某个 work(意图)的执行过程:get_task_worker_trace(task_id, intent_id) 看步骤摘要;再带 step_ids=[...] 取那几步完整内容(一次最多 5 个,多传只返回前 5 个)。",
|
||||
@@ -521,17 +614,24 @@ func (s *Server) deriveTaskStatus(t *Task) string {
|
||||
// orchestrationToolSeeds seeds the cross-task tools into the tools table so they
|
||||
// are bindable per-agent (default: bound to nobody — opt-in for orchestration
|
||||
// agents). First-insert only, like the traffic seeds.
|
||||
func defaultOrchestrationToolBindings(name string) json.RawMessage {
|
||||
switch {
|
||||
case name == "resume_task":
|
||||
return json.RawMessage(`["auto","mainagent"]`)
|
||||
case name == "bind_finding_traffic" || strings.Contains(name, "finding_case") || name == "search_finding_duplicates" || name == "get_finding_record" || name == "merge_finding_records" || name == "suggest_finding_merge":
|
||||
return json.RawMessage(`["reporter"]`)
|
||||
default:
|
||||
return json.RawMessage(`["auto"]`)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) seedOrchestrationTools() {
|
||||
// task-op + platform tools default-bind to the built-in Auto agent (它天生用来
|
||||
// 操作平台)。SeedTool 首插入生效;老库已 seed 的行由 seedAutoDefaultBindings 补绑。
|
||||
autoAgents, _ := json.Marshal([]string{"auto"})
|
||||
for _, t := range s.orchestrationTools() {
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
bindings := autoAgents
|
||||
if t.Name() == "bind_finding_traffic" || strings.Contains(t.Name(), "finding_case") || t.Name() == "search_finding_duplicates" || t.Name() == "get_finding_record" || t.Name() == "merge_finding_records" || t.Name() == "suggest_finding_merge" {
|
||||
bindings = json.RawMessage(`["reporter"]`)
|
||||
}
|
||||
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, bindings)
|
||||
_ = s.m.PG().SeedTool(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name()))
|
||||
}
|
||||
for _, t := range s.platformTools() {
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
@@ -539,6 +639,7 @@ func (s *Server) seedOrchestrationTools() {
|
||||
}
|
||||
s.refreshBuiltinToolSchemas()
|
||||
s.seedAutoDefaultBindings()
|
||||
s.seedTaskReopenBindings()
|
||||
s.seedPlannerDefaultBindings()
|
||||
s.seedPlannerListAssetsBinding()
|
||||
s.seedCompanyScopeRebind()
|
||||
@@ -547,7 +648,8 @@ func (s *Server) seedOrchestrationTools() {
|
||||
s.seedAutoReportFindingBinding()
|
||||
s.unbindGoalMetDefault()
|
||||
s.reseedGoalsPrompt() // goals 提示词加入「抽操作约束」步 → 旧库追加一版新默认(一次性)
|
||||
s.reseedMainAgentPrompt() // mainagent 提示词加入「目标达成后 add_intent 反问是否建目标」(一次性)
|
||||
s.reseedAutoPrompt() // auto 提示词加入 resume_task/set_task_goals/add_task_intent 与原地继续原则(一次性)
|
||||
s.reseedMainAgentPrompt() // mainagent 提示词加入 resume_task 引导(一次性)
|
||||
s.reseedPlannerPrompt() // planner 提示词:重写「0 意图」正当理由 + 加量化验收核对(一次性)
|
||||
s.reseedWorkerPrompt() // worker 提示词:加否定结论证据门槛(一次性)
|
||||
s.seedReporterAgent() // 预置「报告撰写」agent + 工具绑定 + finding 触发器(一次性)
|
||||
@@ -629,7 +731,7 @@ func (s *Server) migrateReporterWorkflow() {
|
||||
// reaches an old DB otherwise. Preserves each tool's agent binding + enabled flag.
|
||||
// Bump the flag whenever these tools' schemas/descriptions change in code.
|
||||
func (s *Server) refreshBuiltinToolSchemas() {
|
||||
const flag = "tool_schema_refresh_v8_finding_case_tools"
|
||||
const flag = "tool_schema_refresh_v9_task_reopen_tools"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
@@ -714,7 +816,7 @@ func (s *Server) reseedGoalsPrompt() {
|
||||
// 保留在历史里,用户若自定义过可从版本记录找回。settings flag 守卫 → 只做一次。全新库无需处理
|
||||
// (SeedPromptIfEmpty 已 seed 最新默认)。与 reseedGoalsPrompt 完全同构。
|
||||
func (s *Server) reseedMainAgentPrompt() {
|
||||
const flag = "mainagent_prompt_goalless_intent_v1"
|
||||
const flag = "mainagent_prompt_task_reopen_v2"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
@@ -738,6 +840,32 @@ func (s *Server) reseedMainAgentPrompt() {
|
||||
log.Printf("[prompts] mainagent 提示词已追加新默认版本(加入目标达成后反问建目标,一次性)")
|
||||
}
|
||||
|
||||
// reseedAutoPrompt 把 auto 提示词刷成【当前代码默认】——加入 resume_task /
|
||||
// set_task_goals / add_task_intent 以及「原地继续优先于新建任务」原则。
|
||||
func (s *Server) reseedAutoPrompt() {
|
||||
const flag = "auto_prompt_task_reopen_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
defer func() { _ = s.m.pg.SetSetting(flag, "true") }()
|
||||
a, err := s.m.pg.GetAgentByKey("auto")
|
||||
if err != nil || a == nil {
|
||||
return
|
||||
}
|
||||
tmpl := agent.BuiltinPromptSeeds()["auto"]
|
||||
if tmpl == "" {
|
||||
return
|
||||
}
|
||||
if cur, err := s.m.pg.CurrentPrompt(a.ID); err == nil && cur == tmpl {
|
||||
return
|
||||
}
|
||||
if _, err := s.m.pg.ResetPromptToDefault(a.ID, tmpl); err != nil {
|
||||
log.Printf("[prompts] auto 提示词重刷为新默认失败: %v", err)
|
||||
return
|
||||
}
|
||||
log.Printf("[prompts] auto 提示词已追加新默认版本(加入 resume_task/set_task_goals/add_task_intent,一次性)")
|
||||
}
|
||||
|
||||
// reseedPlannerPrompt 把 planner 提示词刷成【当前代码默认】——默认正文做了精简重构,并把「克制」降级为
|
||||
// 仅去重、新增「深度优先于覆盖度」「硬底线:目标未达成且无在跑意图必须产出」、给否定结论复核加上界。
|
||||
// 每次默认有实质变更就 bump 下面的 flag(当前 v2)让存量旧库再刷一次。SeedPromptIfEmpty 首插入only,旧库已有版本收不到,故用版本管理
|
||||
@@ -1033,3 +1161,22 @@ func (s *Server) seedAutoDefaultBindings() {
|
||||
}
|
||||
_ = s.m.pg.SetSetting(flag, "true")
|
||||
}
|
||||
|
||||
// seedTaskReopenBindings adds the task reopen/steering orchestration tools to
|
||||
// existing DBs ONCE (guarded by a settings flag), without re-adding unrelated
|
||||
// tools a user may have deliberately unbound.
|
||||
func (s *Server) seedTaskReopenBindings() {
|
||||
const flag = "task_reopen_bindings_v1"
|
||||
if v, _, _ := s.m.pg.GetSetting(flag); v == "true" {
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.AddAgentToToolBinding("auto", []string{"resume_task", "set_task_goals", "add_task_intent"}); err != nil {
|
||||
log.Printf("[auto] 任务重开/操舵工具默认绑定失败: %v", err)
|
||||
return
|
||||
}
|
||||
if err := s.m.pg.AddAgentToToolBinding("mainagent", []string{"resume_task"}); err != nil {
|
||||
log.Printf("[mainagent] resume_task 默认绑定失败: %v", err)
|
||||
return
|
||||
}
|
||||
_ = s.m.pg.SetSetting(flag, "true")
|
||||
}
|
||||
+32
-91
@@ -18,7 +18,6 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
@@ -911,6 +910,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("PATCH /api/tasks/{id}/constraints/{cid}", s.editConstraint) // 约束管理:修改约束
|
||||
mux.HandleFunc("DELETE /api/tasks/{id}/constraints/{cid}", s.deleteConstraint) // 约束管理:删除约束
|
||||
mux.HandleFunc("POST /api/tasks/{id}/control", s.control)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/resume", s.resumeTask)
|
||||
mux.HandleFunc("PUT /api/tasks/{id}/llm", s.updateTaskLLMProfiles)
|
||||
mux.HandleFunc("GET /api/tasks/{id}/llm/resolution", s.taskLLMResolutionHandler)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/intents/{iid}/control", s.controlIntent)
|
||||
@@ -1390,6 +1390,22 @@ func (s *Server) control(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, result)
|
||||
}
|
||||
|
||||
// resumeTask resumes a paused task or reopens a terminal task (done/failed/timeout)
|
||||
// in place when it still has open goals or open intents.
|
||||
func (s *Server) resumeTask(w http.ResponseWriter, r *http.Request) {
|
||||
t, ok := s.lookupTask(r.PathValue("id"))
|
||||
if !ok {
|
||||
writeErr(w, 404, "task not found")
|
||||
return
|
||||
}
|
||||
result, err := s.resumeOrReopenTask(t, agent.AbortPausedByUser)
|
||||
if err != nil {
|
||||
writeErr(w, 409, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, result)
|
||||
}
|
||||
|
||||
// controlIntent pauses, resumes, or cancels one local worker intent. A running
|
||||
// worker is always stopped before state mutation/cleanup, preventing tool output
|
||||
// that arrives after the user action from recreating deleted blackboard records.
|
||||
@@ -2621,10 +2637,10 @@ func (s *Server) findingLineage(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"nodes": taskNodeDTOs(nodes), "edges": edgeDTOs(edges)})
|
||||
}
|
||||
|
||||
// patchFinding partially updates a finding: any subset of {status, severity, name, vulnclass,
|
||||
// summary, evidence, report, remark}. The id is the standalone findings-table id (DTO finding_id).
|
||||
// Core text fields are mirrored onto the originating exploration node so the per-task view stays
|
||||
// in sync. Returns the updated finding DTO.
|
||||
// patchFinding partially updates a finding: any subset of {status, severity}.
|
||||
// The id is the standalone findings-table id (DTO finding_id). Severity edits are
|
||||
// mirrored onto the originating exploration node so the per-task view stays in
|
||||
// sync. Returns the updated finding DTO.
|
||||
func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
|
||||
id := int64(atoiDefault(r.PathValue("id"), 0))
|
||||
if id <= 0 {
|
||||
@@ -2636,38 +2652,20 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
|
||||
Severity *string `json:"severity"`
|
||||
Name *string `json:"name"`
|
||||
VulnClass *string `json:"vulnclass"`
|
||||
Summary *string `json:"summary"`
|
||||
Evidence *string `json:"evidence"`
|
||||
Report *string `json:"report"`
|
||||
Remark *string `json:"remark"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
writeErr(w, 400, "bad json: "+err.Error())
|
||||
return
|
||||
}
|
||||
if body.Status == nil && body.Severity == nil && body.Name == nil && body.VulnClass == nil &&
|
||||
body.Summary == nil && body.Evidence == nil && body.Report == nil && body.Remark == nil {
|
||||
writeErr(w, 400, "nothing to update: provide status/severity/name/vulnclass/summary/evidence/report/remark")
|
||||
if body.Status == nil && body.Severity == nil && body.Name == nil && body.VulnClass == nil {
|
||||
writeErr(w, 400, "nothing to update: provide status/severity/name/vulnclass")
|
||||
return
|
||||
}
|
||||
// Validate all fields before mutating so invalid input never leaves partial writes.
|
||||
if body.Status != nil && !db.ValidFindingStatus(*body.Status) {
|
||||
writeErr(w, 400, "bad status: "+*body.Status)
|
||||
return
|
||||
}
|
||||
if body.Severity != nil && !db.ValidSeverity(*body.Severity) {
|
||||
writeErr(w, 400, "bad severity: "+*body.Severity)
|
||||
return
|
||||
}
|
||||
var remark string
|
||||
if body.Remark != nil {
|
||||
remark = strings.TrimSpace(*body.Remark)
|
||||
if utf8.RuneCountInString(remark) > db.MaxFindingRemarkRunes {
|
||||
writeErr(w, 400, fmt.Sprintf("备注最多 %d 个字符", db.MaxFindingRemarkRunes))
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.Status != nil {
|
||||
if !db.ValidFindingStatus(*body.Status) {
|
||||
writeErr(w, 400, "bad status: "+*body.Status)
|
||||
return
|
||||
}
|
||||
// 走带通知的版本:状态更新与「状态变更推送事件」在同一事务里落库,
|
||||
// 避免出现状态已改而推送事件丢失的窗口。事件登记失败不影响状态更新,
|
||||
// 所以只记日志、不向调用方报错。
|
||||
@@ -2685,6 +2683,10 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
if body.Severity != nil {
|
||||
if !db.ValidSeverity(*body.Severity) {
|
||||
writeErr(w, 400, "bad severity: "+*body.Severity)
|
||||
return
|
||||
}
|
||||
n, err := s.m.pg.SetFindingSeverity(id, *body.Severity)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
@@ -2717,58 +2719,6 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.Summary != nil {
|
||||
n, err := s.m.pg.SetFindingSummary(id, strings.TrimSpace(*body.Summary))
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeErr(w, 404, "finding not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.Evidence != nil {
|
||||
ev := *body.Evidence
|
||||
if strings.TrimSpace(ev) == "" {
|
||||
ev = ""
|
||||
}
|
||||
n, err := s.m.pg.SetFindingEvidence(id, ev)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeErr(w, 404, "finding not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.Report != nil {
|
||||
rep := *body.Report
|
||||
if strings.TrimSpace(rep) == "" {
|
||||
rep = ""
|
||||
}
|
||||
n, err := s.m.pg.SetFindingReport(id, rep)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeErr(w, 404, "finding not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if body.Remark != nil {
|
||||
n, err := s.m.pg.SetFindingRemark(id, remark)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeErr(w, 404, "finding not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
f, err := s.m.pg.GetFinding(id)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
@@ -2778,16 +2728,7 @@ func (s *Server) patchFinding(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, 404, "finding not found")
|
||||
return
|
||||
}
|
||||
dto := findingFromDB(f, s.resolveAssetIDs(f.AssetIDs))
|
||||
cid, err := s.m.pg.FindingCaseID(f.ID)
|
||||
if err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
if cid > 0 {
|
||||
dto.CaseID = i64s(cid)
|
||||
}
|
||||
writeJSON(w, 200, dto)
|
||||
writeJSON(w, 200, findingFromDB(f, s.resolveAssetIDs(f.AssetIDs)))
|
||||
}
|
||||
|
||||
// deleteFinding removes a finding (findings row + originating exploration node).
|
||||
|
||||
+15
-2
@@ -840,9 +840,22 @@ func (s *Server) pgResetTool(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
return
|
||||
}
|
||||
// orchestration/platform tools (auto agent) — default-bind to "auto".
|
||||
// orchestration tools use per-tool default bindings (auto / auto+mainagent / reporter).
|
||||
for _, t := range s.orchestrationTools() {
|
||||
if t.Name() != key {
|
||||
continue
|
||||
}
|
||||
schema, _ := json.Marshal(t.InputSchema())
|
||||
if err := pg.UpsertToolForce(t.Name(), t.Description(), schema, defaultOrchestrationToolBindings(t.Name())); err != nil {
|
||||
writeErr(w, 500, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"ok": true})
|
||||
return
|
||||
}
|
||||
// platform tools (auto agent) — default-bind to "auto".
|
||||
autoAgents, _ := json.Marshal([]string{"auto"})
|
||||
for _, t := range append(s.orchestrationTools(), s.platformTools()...) {
|
||||
for _, t := range s.platformTools() {
|
||||
if t.Name() != key {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -193,6 +193,88 @@ func (s *Server) applyTaskControlWithCause(t *Task, action string, pauseCause er
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// resumeOrReopenTask resumes a paused task or reopens a terminal
|
||||
// (done/failed/timeout) task in place when it still has open goals or open
|
||||
// intents to execute. Unlike applyTaskControl("resume"), which stays strictly
|
||||
// paused-only for schedule/proxy/batch control callers, this is the explicit
|
||||
// operator/agent reopen path (POST /api/tasks/{id}/resume and resume_task).
|
||||
func (s *Server) resumeOrReopenTask(t *Task, cause error) (taskControlResult, error) {
|
||||
if t == nil {
|
||||
return taskControlResult{}, fmt.Errorf("task not found")
|
||||
}
|
||||
out := taskControlResult{ID: t.ID}
|
||||
lifecycle := t.lifecycleSnapshot()
|
||||
if !isTerminalStatus(lifecycle.Status) {
|
||||
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
|
||||
return s.applyTaskControlWithCause(t, "resume", cause)
|
||||
}
|
||||
if lifecycle.Queued {
|
||||
return out, fmt.Errorf("任务当前已在排队等待运行,无需恢复")
|
||||
}
|
||||
if s.engine.Started(t.ID) {
|
||||
return out, fmt.Errorf("任务当前正在运行,无需恢复")
|
||||
}
|
||||
mode := s.resumeAdmissionMode(t)
|
||||
queued, err := s.admitTask(t, mode)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Queued = queued
|
||||
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
|
||||
return out, nil
|
||||
}
|
||||
|
||||
if !s.engine.beginTaskOperation(t.ID) {
|
||||
return out, fmt.Errorf("任务正在删除,无法恢复")
|
||||
}
|
||||
defer s.engine.decInflight(t.ID)
|
||||
|
||||
current, exists := s.m.Task(t.ID)
|
||||
if !exists || current != t || s.engine.IsDeleting(t.ID) {
|
||||
return out, fmt.Errorf("任务正在删除,无法恢复")
|
||||
}
|
||||
lifecycle = t.lifecycleSnapshot()
|
||||
if !isTerminalStatus(lifecycle.Status) {
|
||||
if lifecycle.Paused || s.engine.IsPaused(t.ID) {
|
||||
return s.applyTaskControlWithCause(t, "resume", cause)
|
||||
}
|
||||
out.Queued = lifecycle.Queued
|
||||
out.Status = s.deriveTaskStatus(t)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
hasOpenGoal, err := t.Store.HasOpenGoal()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
hasActiveIntent, err := t.Store.HasActiveIntent()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
mode := "resume"
|
||||
if !hasOpenGoal && !hasActiveIntent {
|
||||
goals, gErr := t.Store.ListByKind(db.KindGoal, 1)
|
||||
if gErr == nil && len(goals) == 0 && lifecycle.FirstRunAt == 0 {
|
||||
mode = "bootstrap"
|
||||
} else {
|
||||
return out, fmt.Errorf("任务所有目标均已达成且没有待执行(open)的意图,无法直接恢复;请先通过 set_goals/set_task_goals 新增目标,或通过 add_intent/add_task_intent 下发新意图(系统会自动将任务拉回运行态)")
|
||||
}
|
||||
}
|
||||
queued, err := s.admitTask(t, mode)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.Queued = queued
|
||||
out.Status = map[bool]string{true: "queued", false: "running"}[queued]
|
||||
summary := "任务已重新打开,继续执行剩余探索任务"
|
||||
if queued {
|
||||
summary = "任务已重新打开并进入排队,等待运行槽位"
|
||||
}
|
||||
s.engine.emitActivity(t, db.Activity{Worker: "system", Kind: "text", Summary: summary})
|
||||
log.Printf("[task] #%s 已重新打开继续运行 (from=%s status=%s)", t.ID, lifecycle.Status, out.Status)
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// intentSummaryOf 取意图 payload 里的 summary,供删除通知在意图节点消失(真删除)前留档。
|
||||
func intentSummaryOf(n *db.Node) string {
|
||||
if n == nil {
|
||||
|
||||
@@ -0,0 +1,438 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Autumn-27/artex/agent"
|
||||
"github.com/Autumn-27/artex/db"
|
||||
actool "github.com/Autumn-27/norma/tool"
|
||||
)
|
||||
|
||||
func toolResultText(res actool.Result) string {
|
||||
var parts []string
|
||||
for _, b := range res.Content {
|
||||
if b.Text != "" {
|
||||
parts = append(parts, b.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
|
||||
func TestResumeTaskToolReopensDoneTaskWithOpenIntents(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("reopen done task", "finish open intents", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "initial goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
intentID, err := task.Store.AddIntent(map[string]any{"summary": "test /admin endpoint"}, 8, nil, "planner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("resume_task failed: %s", toolResultText(res))
|
||||
}
|
||||
var out struct {
|
||||
TaskID string `json:"task_id"`
|
||||
Status string `json:"status"`
|
||||
Queued bool `json:"queued"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(toolResultText(res)), &out); err != nil {
|
||||
t.Fatalf("unmarshal result %q: %v", toolResultText(res), err)
|
||||
}
|
||||
if out.TaskID != task.ID || out.Status != "running" || out.Queued {
|
||||
t.Fatalf("resume_task result = %+v, want task_id=%s status=running queued=false", out, task.ID)
|
||||
}
|
||||
if got := m.TaskStatus(task.ID); got != "running" {
|
||||
t.Fatalf("in-memory task status = %q, want running", got)
|
||||
}
|
||||
stored, err := m.pg.GetTask(mustTaskID(t, task.ID))
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("GetTask: %v", err)
|
||||
}
|
||||
if stored.Status != "running" || stored.Paused || stored.CompletedAt != nil {
|
||||
t.Fatalf("stored task = %+v, want status=running paused=false completed_at=nil", stored)
|
||||
}
|
||||
// Existing open intent must still be present in place.
|
||||
node, err := task.Store.GetNode(intentID)
|
||||
if err != nil || node == nil || node.State != "open" {
|
||||
t.Fatalf("open intent after reopen = %+v err=%v, want state=open", node, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeTaskToolRefusesDoneTaskWithNoOpenWork(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("done no work", "all goals met", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "finished goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
in, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
res, err := s.toolResumeTask().Call(context.Background(), in, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !res.IsError {
|
||||
t.Fatalf("expected error for done task with no open goals/intents, got: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(task.ID); got != "done" {
|
||||
t.Fatalf("status changed to %q on refused reopen, want done", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeTaskToolInMainAgentContextDefaultsAndScopesTaskID(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
task1, err := m.CreateTask("task1", "goal1", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task1.ID, DeleteTaskOptions{}) }()
|
||||
task2, err := m.CreateTask("task2", "goal2", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task2.ID, DeleteTaskOptions{}) }()
|
||||
|
||||
if _, err := task1.Store.AddIntent(map[string]any{"summary": "open work 1"}, 5, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := task2.Store.AddIntent(map[string]any{"summary": "open work 2"}, 5, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task1.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task2.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
ctx := agent.WithRunInfo(context.Background(), agent.RunInfo{TaskID: mustTaskID(t, task1.ID)})
|
||||
|
||||
// Cross-task call from task1 context must be refused.
|
||||
crossIn, _ := json.Marshal(map[string]any{"task_id": task2.ID})
|
||||
crossRes, err := s.toolResumeTask().Call(ctx, crossIn, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !crossRes.IsError {
|
||||
t.Fatalf("expected cross-task resume refusal, got: %s", toolResultText(crossRes))
|
||||
}
|
||||
if m.TaskStatus(task2.ID) != "done" {
|
||||
t.Fatalf("task2 status = %q, want done", m.TaskStatus(task2.ID))
|
||||
}
|
||||
|
||||
// Empty task_id in task1 context defaults to task1 and reopens it.
|
||||
selfRes, err := s.toolResumeTask().Call(ctx, json.RawMessage(`{}`), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if selfRes.IsError {
|
||||
t.Fatalf("in-task resume_task failed: %s", toolResultText(selfRes))
|
||||
}
|
||||
if m.TaskStatus(task1.ID) != "running" {
|
||||
t.Fatalf("task1 status = %q, want running", m.TaskStatus(task1.ID))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTaskGoalsAndAddTaskIntentReviveDoneAndPausedTasks(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
s := newAdmissionTestServer(m, nil)
|
||||
|
||||
// 1. set_task_goals on a done task (no open goals/intents) writes an open goal and revives it.
|
||||
doneTask, err := m.CreateTask("done for set_task_goals", "old goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(doneTask.ID, DeleteTaskOptions{}) }()
|
||||
gID, err := doneTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := doneTask.Store.SetNodeState(gID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(doneTask.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inGoals, _ := json.Marshal(map[string]any{
|
||||
"task_id": doneTask.ID,
|
||||
"text": "verify SSRF on /api/fetch",
|
||||
})
|
||||
res, err := s.toolSetTaskGoals().Call(context.Background(), inGoals, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("set_task_goals failed: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(doneTask.ID); got != "running" {
|
||||
t.Fatalf("doneTask status after set_task_goals = %q, want running", got)
|
||||
}
|
||||
hasOpenGoal, err := doneTask.Store.HasOpenGoal()
|
||||
if err != nil || !hasOpenGoal {
|
||||
t.Fatalf("doneTask HasOpenGoal = %v err=%v, want true", hasOpenGoal, err)
|
||||
}
|
||||
|
||||
// 2. set_task_goals on a paused task clears pause and revives it.
|
||||
if _, err := s.applyTaskControl(doneTask, "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !doneTask.lifecycleSnapshot().Paused {
|
||||
t.Fatal("expected task to be paused")
|
||||
}
|
||||
inGoals2, _ := json.Marshal(map[string]any{
|
||||
"task_id": doneTask.ID,
|
||||
"goals": []map[string]any{{"text": "check IDOR on /api/users/{id}", "vulnclass": "IDOR"}},
|
||||
})
|
||||
res, err = s.toolSetTaskGoals().Call(context.Background(), inGoals2, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("set_task_goals on paused task failed: %s", toolResultText(res))
|
||||
}
|
||||
if doneTask.lifecycleSnapshot().Paused || s.engine.IsPaused(doneTask.ID) {
|
||||
t.Fatalf("task still paused after set_task_goals: lifecycle=%+v enginePaused=%v", doneTask.lifecycleSnapshot(), s.engine.IsPaused(doneTask.ID))
|
||||
}
|
||||
|
||||
// 3. add_task_intent on a done task creates an open intent and revives it.
|
||||
intentTask, err := m.CreateTask("done for add_task_intent", "old goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(intentTask.ID, DeleteTaskOptions{}) }()
|
||||
gID2, err := intentTask.Store.AddGoal(map[string]any{"text": "old goal"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := intentTask.Store.SetNodeState(gID2, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(intentTask.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
inIntent, _ := json.Marshal(map[string]any{
|
||||
"task_id": intentTask.ID,
|
||||
"summary": "probe /internal/metrics directly",
|
||||
"priority": 9,
|
||||
})
|
||||
res, err = s.toolAddTaskIntent().Call(context.Background(), inIntent, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if res.IsError {
|
||||
t.Fatalf("add_task_intent failed: %s", toolResultText(res))
|
||||
}
|
||||
if got := m.TaskStatus(intentTask.ID); got != "running" {
|
||||
t.Fatalf("intentTask status after add_task_intent = %q, want running", got)
|
||||
}
|
||||
hasActive, err := intentTask.Store.HasActiveIntent()
|
||||
if err != nil || !hasActive {
|
||||
t.Fatalf("intentTask HasActiveIntent = %v err=%v, want true", hasActive, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPResumeTaskEndpoint(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
td := t.TempDir()
|
||||
s := New(ctx, m, td, td, td)
|
||||
planner, worker := new(agent.Planner), new(agent.Worker)
|
||||
s.engine.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
|
||||
return planner, worker
|
||||
})
|
||||
h := s.Handler()
|
||||
token, err := signJWT(s.jwtKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
postResume := func(id string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/tasks/"+id+"/resume", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// Missing task → 404.
|
||||
if rec := postResume("999999999"); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing task status = %d body=%s, want 404", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
task, err := m.CreateTask("http resume", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
goalID, err := task.Store.AddGoal(map[string]any{"text": "g"}, "system")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := task.Store.SetNodeState(goalID, "met"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Done task with no open goals/intents → 409.
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("done task with no work status = %d body=%s, want 409", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Add an open intent → POST /api/tasks/{id}/resume reopens to 200 running.
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "continue open work"}, 7, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := postResume(task.ID)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("reopen done task status = %d body=%s, want 200", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body taskControlResult
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body.ID != task.ID || body.Status != "running" || body.Paused {
|
||||
t.Fatalf("resume body = %+v, want id=%s status=running paused=false", body, task.ID)
|
||||
}
|
||||
|
||||
// Already running → 409.
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusConflict {
|
||||
t.Fatalf("already running status = %d body=%s, want 409", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Pause then resume → 200 running.
|
||||
if _, err := s.applyTaskControl(task, "pause"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec := postResume(task.ID); rec.Code != http.StatusOK {
|
||||
t.Fatalf("resume paused task status = %d body=%s, want 200", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoAndMainAgentToolResolutionIncludesReopenTools(t *testing.T) {
|
||||
m, err := NewManager(t.TempDir(), "")
|
||||
if err != nil {
|
||||
t.Skipf("postgres unavailable (%v) - skipping", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
td := t.TempDir()
|
||||
s := New(ctx, m, td, td, td)
|
||||
t.Cleanup(func() { agent.ToolResolve = nil })
|
||||
|
||||
// Verify auto gets resume_task, set_task_goals, add_task_intent via ToolResolve.
|
||||
hostTools, _ := s.hostTools()
|
||||
autoTools := names(agent.ToolResolve(context.Background(), "auto", append(actool.DefaultTools(), hostTools...)))
|
||||
for _, want := range []string{"resume_task", "set_task_goals", "add_task_intent", "pause_task", "add_task_hint"} {
|
||||
if _, ok := autoTools[want]; !ok {
|
||||
t.Errorf("auto missing bound tool %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify mainagent gets resume_task alongside set_goals and add_intent.
|
||||
ts := agent.NewToolSet(nil, "human")
|
||||
mainBase := append(ts.MainAgentTools(), hostTools...)
|
||||
mainTools := names(agent.ToolResolve(context.Background(), "mainagent", mainBase))
|
||||
for _, want := range []string{"resume_task", "set_goals", "add_intent", "add_hint"} {
|
||||
if _, ok := mainTools[want]; !ok {
|
||||
t.Errorf("mainagent missing bound tool %q", want)
|
||||
}
|
||||
}
|
||||
// Verify cross-task-only tools are NOT leaked into mainagent.
|
||||
for _, unwanted := range []string{"set_task_goals", "add_task_intent"} {
|
||||
if _, ok := mainTools[unwanted]; ok {
|
||||
t.Errorf("mainagent should not receive cross-task tool %q", unwanted)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify MCP resume_task can also reopen a done task with open intents.
|
||||
task, err := m.CreateTask("mcp reopen", "goal", nil, 0, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _, _ = m.DeleteTask(task.ID, DeleteTaskOptions{}) }()
|
||||
if _, err := task.Store.AddIntent(map[string]any{"summary": "remaining intent"}, 6, nil, "planner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := m.SetTaskStatus(task.ID, "done"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tok := &db.APIToken{ID: 1, Name: "test", Scopes: []string{db.APIScopeTaskControl}}
|
||||
mcpIn, _ := json.Marshal(map[string]any{"task_id": task.ID})
|
||||
mcpRes, err := s.mcpControlTask(tok, mcpIn, "resume")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mcpRes.IsError || !strings.Contains(toolResultText(mcpRes), `"running"`) {
|
||||
t.Fatalf("mcp resume_task on done task = %+v, want running", mcpRes)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
FolderOpenIcon,
|
||||
RotateCcwIcon,
|
||||
ShieldAlertIcon,
|
||||
StickyNoteIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -68,12 +67,11 @@ export const FINDING_STATUSES: FindingStatus[] = [
|
||||
|
||||
export const UNASSIGNED_TASK = "__unassigned__";
|
||||
|
||||
// 行内编辑缓冲:当前展开行的名称/类别/严重等级/备注。
|
||||
// 行内编辑缓冲:当前展开行的名称/类别/严重等级。
|
||||
export interface FindingEdit {
|
||||
name: string;
|
||||
vulnclass: string;
|
||||
severity: Severity;
|
||||
remark: string;
|
||||
}
|
||||
|
||||
export type FindingReport = { status: "loading" | "done" | "error"; text: string };
|
||||
@@ -289,15 +287,6 @@ export function FindingsTable({
|
||||
</span>
|
||||
)}
|
||||
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
|
||||
{f.remark ? (
|
||||
<span
|
||||
className="inline-flex min-w-0 items-center gap-1 truncate text-xs text-amber-700 dark:text-amber-400"
|
||||
title={f.remark}
|
||||
>
|
||||
<StickyNoteIcon className="size-3 shrink-0" />
|
||||
<span className="truncate">{f.remark}</span>
|
||||
</span>
|
||||
) : null}
|
||||
{matchedIds && !matchedIds.includes(Number(f.finding_id)) ? (
|
||||
<Badge variant="outline" className="w-fit">
|
||||
{ui("screen.7852ff0b787df8")}
|
||||
@@ -446,14 +435,6 @@ export function FindingsTable({
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex min-w-[14rem] flex-1 flex-col gap-1">
|
||||
<Label className="text-xs text-muted-foreground">{ui("findingDetail.remark")}</Label>
|
||||
<Input
|
||||
value={edit.remark}
|
||||
onChange={(e) => onEditChange((s) => (s ? { ...s, remark: e.target.value } : s))}
|
||||
placeholder={ui("findingDetail.remarkPlaceholder")}
|
||||
/>
|
||||
</div>
|
||||
<Button size="sm" disabled={saving} onClick={() => onSave(f)}>
|
||||
{saving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
|
||||
</Button>
|
||||
|
||||
@@ -1,282 +0,0 @@
|
||||
"use client";
|
||||
import * as React from "react";
|
||||
|
||||
import { Loader2Icon } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { taskError } from "@/i18n/task-runtime";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { useUITranslation } from "@/i18n/use-ui-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import { statusMeta } from "@/lib/status";
|
||||
import { type Finding, type FindingStatus, MAX_FINDING_REMARK_RUNES, type Severity } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
|
||||
const FINDING_STATUSES: FindingStatus[] = [
|
||||
"pending",
|
||||
"in_progress",
|
||||
"confirmed",
|
||||
"resolved",
|
||||
"fixed",
|
||||
"false_positive",
|
||||
"ignored",
|
||||
"duplicate",
|
||||
"risk_accepted",
|
||||
];
|
||||
|
||||
type FindingDraft = {
|
||||
name: string;
|
||||
vulnclass: string;
|
||||
severity: Severity;
|
||||
status: FindingStatus;
|
||||
summary: string;
|
||||
evidence: string;
|
||||
report: string;
|
||||
remark: string;
|
||||
};
|
||||
|
||||
function draftFromFinding(f: Finding): FindingDraft {
|
||||
return {
|
||||
name: f.name ?? "",
|
||||
vulnclass: f.vulnclass,
|
||||
severity: f.severity,
|
||||
status: f.status,
|
||||
summary: f.summary,
|
||||
evidence: f.evidence,
|
||||
report: f.report ?? "",
|
||||
remark: f.remark ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export function FindingEditDialog({
|
||||
finding,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
}: {
|
||||
finding: Finding;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSaved: (updated: Finding) => void;
|
||||
}) {
|
||||
const { ui, liveUI } = useUITranslation();
|
||||
const { t, liveT } = useLiveTranslation();
|
||||
const [draft, setDraft] = React.useState<FindingDraft>(() => draftFromFinding(finding));
|
||||
const [saving, setSaving] = React.useState(false);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (open) {
|
||||
setDraft(draftFromFinding(finding));
|
||||
}
|
||||
}, [open, finding]);
|
||||
|
||||
const trimmedRemark = draft.remark.trim();
|
||||
const remarkRunes = Array.from(trimmedRemark).length;
|
||||
const remarkTooLong = remarkRunes > MAX_FINDING_REMARK_RUNES;
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (saving || remarkTooLong) return;
|
||||
|
||||
const patchPayload: Parameters<typeof api.updateFinding>[1] = {};
|
||||
const nextName = draft.name.trim();
|
||||
const nextVulnClass = draft.vulnclass.trim();
|
||||
const nextSummary = draft.summary.trim();
|
||||
const nextEvidence = draft.evidence.trim() ? draft.evidence : "";
|
||||
const nextReport = draft.report.trim() ? draft.report : "";
|
||||
|
||||
if (nextName !== (finding.name ?? "").trim()) patchPayload.name = nextName;
|
||||
if (nextVulnClass !== finding.vulnclass.trim()) patchPayload.vulnclass = nextVulnClass;
|
||||
if (draft.severity !== finding.severity) patchPayload.severity = draft.severity;
|
||||
if (draft.status !== finding.status) patchPayload.status = draft.status;
|
||||
if (nextSummary !== finding.summary.trim()) patchPayload.summary = nextSummary;
|
||||
if (nextEvidence !== finding.evidence) patchPayload.evidence = nextEvidence;
|
||||
if (nextReport !== (finding.report ?? "")) patchPayload.report = nextReport;
|
||||
if (trimmedRemark !== (finding.remark ?? "").trim()) patchPayload.remark = trimmedRemark;
|
||||
|
||||
if (Object.keys(patchPayload).length === 0) {
|
||||
onOpenChange(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const updated = await api.updateFinding(finding.id, patchPayload);
|
||||
onSaved(updated);
|
||||
toast.success(liveUI("findingDetail.findingSaved"));
|
||||
onOpenChange(false);
|
||||
} catch (err) {
|
||||
toast.error(liveUI("screen.20e1b0f2590bc7", { v0: taskError(err, liveT) }));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={(next) => !saving && onOpenChange(next)}>
|
||||
<DialogContent className="flex max-h-[90dvh] flex-col gap-0 overflow-hidden p-0 sm:max-w-2xl">
|
||||
<DialogHeader className="border-b px-6 py-4">
|
||||
<DialogTitle>{ui("findingDetail.editTitle")}</DialogTitle>
|
||||
<DialogDescription>{ui("findingDetail.editDescription")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<form onSubmit={(e) => void handleSubmit(e)} className="flex min-h-0 flex-1 flex-col">
|
||||
<div className="flex flex-1 flex-col gap-4 overflow-y-auto px-6 py-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="finding-edit-name">{ui("findingDetail.nameLabel")}</Label>
|
||||
<Input
|
||||
id="finding-edit-name"
|
||||
autoFocus
|
||||
value={draft.name}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, name: e.target.value }))}
|
||||
placeholder={ui("screen.e4ca1c94d239bd")}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="finding-edit-vulnclass">{ui("screen.5600494fad709b")}</Label>
|
||||
<Input
|
||||
id="finding-edit-vulnclass"
|
||||
value={draft.vulnclass}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, vulnclass: e.target.value }))}
|
||||
placeholder={ui("screen.18f8e077cc27a6")}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{ui("screen.2e21284b7229e6")}</Label>
|
||||
<Select
|
||||
value={draft.severity}
|
||||
onValueChange={(v) => setDraft((cur) => ({ ...cur, severity: v as Severity }))}
|
||||
disabled={saving}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{SEVERITIES.map((sv) => (
|
||||
<SelectItem key={sv} value={sv}>
|
||||
{statusMeta("severity", sv, t).label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>{ui("screen.d5e74de3449e74")}</Label>
|
||||
<Select
|
||||
value={draft.status}
|
||||
onValueChange={(v) => setDraft((cur) => ({ ...cur, status: v as FindingStatus }))}
|
||||
disabled={saving}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{FINDING_STATUSES.map((st) => (
|
||||
<SelectItem key={st} value={st}>
|
||||
{statusMeta("finding", st, t).label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Label htmlFor="finding-edit-remark">{ui("findingDetail.remark")}</Label>
|
||||
<span
|
||||
className={cn("text-xs tabular-nums", remarkTooLong ? "text-destructive" : "text-muted-foreground")}
|
||||
>
|
||||
{remarkRunes} / {MAX_FINDING_REMARK_RUNES}
|
||||
</span>
|
||||
</div>
|
||||
<Textarea
|
||||
id="finding-edit-remark"
|
||||
rows={3}
|
||||
value={draft.remark}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, remark: e.target.value }))}
|
||||
placeholder={ui("findingDetail.remarkPlaceholder")}
|
||||
aria-invalid={remarkTooLong}
|
||||
disabled={saving}
|
||||
/>
|
||||
{remarkTooLong ? (
|
||||
<p role="alert" className="text-destructive text-xs">
|
||||
{ui("findingDetail.remarkTooLong", { max: MAX_FINDING_REMARK_RUNES })}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="finding-edit-summary">{ui("screen.21c04b2eeeb431")}</Label>
|
||||
<Textarea
|
||||
id="finding-edit-summary"
|
||||
rows={3}
|
||||
value={draft.summary}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, summary: e.target.value }))}
|
||||
placeholder={ui("findingDetail.summaryPlaceholder")}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="finding-edit-evidence">{ui("screen.c13ed981c63391")}</Label>
|
||||
<Textarea
|
||||
id="finding-edit-evidence"
|
||||
rows={4}
|
||||
className="font-mono text-xs"
|
||||
value={draft.evidence}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, evidence: e.target.value }))}
|
||||
placeholder={ui("findingDetail.evidencePlaceholder")}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="finding-edit-report">{ui("screen.566e5ab4ab0638")}</Label>
|
||||
<Textarea
|
||||
id="finding-edit-report"
|
||||
rows={6}
|
||||
className="font-mono text-xs"
|
||||
value={draft.report}
|
||||
onChange={(e) => setDraft((cur) => ({ ...cur, report: e.target.value }))}
|
||||
placeholder={ui("findingDetail.reportPlaceholder")}
|
||||
disabled={saving}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="mx-0 mb-0 border-t px-6 py-3">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>
|
||||
{ui("common.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={saving || remarkTooLong}>
|
||||
{saving ? <Loader2Icon data-icon="inline-start" className="animate-spin" /> : null}
|
||||
{saving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -4,16 +4,8 @@ import * as React from "react";
|
||||
import Link from "next/link";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ArrowUpRightIcon,
|
||||
BotIcon,
|
||||
FileTextIcon,
|
||||
Loader2Icon,
|
||||
PencilIcon,
|
||||
ShieldAlertIcon,
|
||||
StickyNoteIcon,
|
||||
} from "lucide-react";
|
||||
import { ArrowLeftIcon, ArrowUpRightIcon, BotIcon, FileTextIcon, Loader2Icon, ShieldAlertIcon } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { CopyButton } from "@/components/copy-button";
|
||||
@@ -31,16 +23,11 @@ import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger } from "@
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { taskError } from "@/i18n/task-runtime";
|
||||
import { useLiveTranslation } from "@/i18n/use-live-translation";
|
||||
import { type UITranslate, useUITranslation } from "@/i18n/use-ui-translation";
|
||||
import { api } from "@/lib/api";
|
||||
import { statusMeta } from "@/lib/status";
|
||||
import { type Finding, type FindingStatus, MAX_FINDING_REMARK_RUNES, type Severity } from "@/lib/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { Finding, FindingStatus, Severity } from "@/lib/types";
|
||||
|
||||
import { FindingEditDialog } from "./finding-edit-dialog";
|
||||
import { FindingLineageView } from "./lineage";
|
||||
|
||||
const SEVERITIES: Severity[] = ["critical", "high", "medium", "low"];
|
||||
@@ -79,7 +66,7 @@ function FieldRow({ label, children }: { label: string; children: React.ReactNod
|
||||
function FindingDetailInner() {
|
||||
const { ui, liveUI } = useUITranslation();
|
||||
|
||||
const { t, liveT } = useLiveTranslation();
|
||||
const { t } = useTranslation();
|
||||
const searchParams = useSearchParams();
|
||||
const id = searchParams.get("id") ?? "";
|
||||
const contextTaskId = searchParams.get("context_task") ?? "";
|
||||
@@ -90,10 +77,6 @@ function FindingDetailInner() {
|
||||
const [reportGenerating, setReportGenerating] = React.useState(false);
|
||||
const [autoChatOpen, setAutoChatOpen] = React.useState(false);
|
||||
const [reportChatOpen, setReportChatOpen] = React.useState(false);
|
||||
const [editOpen, setEditOpen] = React.useState(false);
|
||||
const [remarkEditing, setRemarkEditing] = React.useState(false);
|
||||
const [remarkDraft, setRemarkDraft] = React.useState("");
|
||||
const [remarkSaving, setRemarkSaving] = React.useState(false);
|
||||
const title = finding?.name || finding?.vulnclass || ui("screen.54b89f90127458");
|
||||
|
||||
const load = React.useCallback(() => {
|
||||
@@ -111,12 +94,6 @@ function FindingDetailInner() {
|
||||
load();
|
||||
}, [load]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!remarkEditing) {
|
||||
setRemarkDraft(finding?.remark ?? "");
|
||||
}
|
||||
}, [finding?.remark, remarkEditing]);
|
||||
|
||||
const changeSeverity = React.useCallback(
|
||||
async (next: Severity) => {
|
||||
if (!finding || finding.inherited || next === finding.severity) return;
|
||||
@@ -168,43 +145,6 @@ function FindingDetailInner() {
|
||||
}
|
||||
}, [finding, id, load, reportGenerating, liveUI]);
|
||||
|
||||
const trimmedRemarkDraft = remarkDraft.trim();
|
||||
const remarkRunes = Array.from(trimmedRemarkDraft).length;
|
||||
const remarkTooLong = remarkRunes > MAX_FINDING_REMARK_RUNES;
|
||||
|
||||
const startRemarkEdit = React.useCallback(() => {
|
||||
if (!finding || finding.inherited) return;
|
||||
setRemarkDraft(finding.remark ?? "");
|
||||
setRemarkEditing(true);
|
||||
}, [finding]);
|
||||
|
||||
const cancelRemarkEdit = React.useCallback(() => {
|
||||
if (remarkSaving) return;
|
||||
setRemarkDraft(finding?.remark ?? "");
|
||||
setRemarkEditing(false);
|
||||
}, [finding?.remark, remarkSaving]);
|
||||
|
||||
const saveRemark = React.useCallback(async () => {
|
||||
if (!finding || finding.inherited || remarkSaving || remarkTooLong) return;
|
||||
const next = remarkDraft.trim();
|
||||
if (next === (finding.remark ?? "").trim()) {
|
||||
setRemarkEditing(false);
|
||||
return;
|
||||
}
|
||||
setRemarkSaving(true);
|
||||
try {
|
||||
const updated = await api.updateFinding(id, { remark: next });
|
||||
setFinding(updated);
|
||||
setRemarkDraft(updated.remark ?? "");
|
||||
setRemarkEditing(false);
|
||||
toast.success(next ? liveUI("findingDetail.remarkSaved") : liveUI("findingDetail.remarkCleared"));
|
||||
} catch (e) {
|
||||
toast.error(liveUI("screen.20e1b0f2590bc7", { v0: taskError(e, liveT) }));
|
||||
} finally {
|
||||
setRemarkSaving(false);
|
||||
}
|
||||
}, [finding, id, liveT, liveUI, remarkDraft, remarkSaving, remarkTooLong]);
|
||||
|
||||
if (!finding) {
|
||||
return (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-10 text-center">
|
||||
@@ -275,17 +215,6 @@ function FindingDetailInner() {
|
||||
{ui("screen.552b1bc6b1d807")}
|
||||
</Button>
|
||||
) : null}
|
||||
{!finding.inherited ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setEditOpen(true)}
|
||||
title={ui("findingDetail.editTitle")}
|
||||
>
|
||||
<PencilIcon data-icon="inline-start" />
|
||||
{ui("findingDetail.editButton")}
|
||||
</Button>
|
||||
) : null}
|
||||
{finding.inherited && finding.source_task_id && (
|
||||
<Badge variant="outline">
|
||||
{ui("screen.88b75b1fbea969")}
|
||||
@@ -497,110 +426,6 @@ function FindingDetailInner() {
|
||||
</FieldRow>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="h-fit">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0">
|
||||
<CardTitle className="flex items-center gap-1.5 text-sm">
|
||||
<StickyNoteIcon className="size-4 text-muted-foreground" />
|
||||
{ui("findingDetail.remark")}
|
||||
</CardTitle>
|
||||
{!finding.inherited && !remarkEditing ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs"
|
||||
onClick={startRemarkEdit}
|
||||
>
|
||||
<PencilIcon data-icon="inline-start" className="size-3.5" />
|
||||
{finding.remark ? ui("findingDetail.editRemark") : ui("findingDetail.addRemark")}
|
||||
</Button>
|
||||
) : null}
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{remarkEditing && !finding.inherited ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<Textarea
|
||||
autoFocus
|
||||
rows={4}
|
||||
value={remarkDraft}
|
||||
disabled={remarkSaving}
|
||||
aria-label={ui("findingDetail.remark")}
|
||||
aria-invalid={remarkTooLong}
|
||||
placeholder={ui("findingDetail.remarkPlaceholder")}
|
||||
onChange={(e) => setRemarkDraft(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.nativeEvent.isComposing) return;
|
||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
void saveRemark();
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
cancelRemarkEdit();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-2 text-xs">
|
||||
<span className="text-muted-foreground">{ui("findingDetail.remarkHint")}</span>
|
||||
<span
|
||||
className={cn(
|
||||
"shrink-0 tabular-nums",
|
||||
remarkTooLong ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{remarkRunes} / {MAX_FINDING_REMARK_RUNES}
|
||||
</span>
|
||||
</div>
|
||||
{remarkTooLong ? (
|
||||
<p role="alert" className="text-xs text-destructive">
|
||||
{ui("findingDetail.remarkTooLong", { max: MAX_FINDING_REMARK_RUNES })}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={cancelRemarkEdit}
|
||||
disabled={remarkSaving}
|
||||
>
|
||||
{ui("common.cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={() => void saveRemark()}
|
||||
disabled={remarkSaving || remarkTooLong}
|
||||
>
|
||||
{remarkSaving ? <Loader2Icon data-icon="inline-start" className="animate-spin" /> : null}
|
||||
{remarkSaving ? ui("screen.ff509c9ba052a2") : ui("screen.a3030bf8f16dc6")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : finding.remark ? (
|
||||
finding.inherited ? (
|
||||
<p className="text-sm leading-relaxed whitespace-pre-wrap break-words">{finding.remark}</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={startRemarkEdit}
|
||||
className="w-full rounded-md text-left text-sm leading-relaxed whitespace-pre-wrap break-words hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{finding.remark}
|
||||
</button>
|
||||
)
|
||||
) : finding.inherited ? (
|
||||
<p className="text-xs text-muted-foreground">{ui("findingDetail.remarkEmptyReadOnly")}</p>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={startRemarkEdit}
|
||||
className="w-full rounded-md border border-dashed px-3 py-2.5 text-left text-xs text-muted-foreground transition-colors hover:border-primary/40 hover:bg-muted/40 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{ui("findingDetail.remarkEmpty")}
|
||||
</button>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
<FindingRetestPanel
|
||||
key={`retest:${id}`}
|
||||
findingId={id}
|
||||
@@ -629,17 +454,6 @@ function FindingDetailInner() {
|
||||
open={reportChatOpen}
|
||||
onOpenChange={setReportChatOpen}
|
||||
/>
|
||||
{!finding.inherited ? (
|
||||
<FindingEditDialog
|
||||
finding={finding}
|
||||
open={editOpen}
|
||||
onOpenChange={setEditOpen}
|
||||
onSaved={(updated) => {
|
||||
setFinding(updated);
|
||||
if (!remarkEditing) setRemarkDraft(updated.remark ?? "");
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -745,7 +745,7 @@ export default function FindingsPage() {
|
||||
setEdit(null);
|
||||
return;
|
||||
}
|
||||
setEdit({ name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity, remark: f.remark ?? "" });
|
||||
setEdit({ name: f.name ?? "", vulnclass: f.vulnclass, severity: f.severity });
|
||||
if (!f.finding_id || reports[key]) return;
|
||||
const fid = f.finding_id;
|
||||
setReports((r) => ({ ...r, [key]: { status: "loading", text: "" } }));
|
||||
@@ -767,18 +767,11 @@ export default function FindingsPage() {
|
||||
name: edit.name.trim(),
|
||||
vulnclass: edit.vulnclass.trim(),
|
||||
severity: edit.severity,
|
||||
remark: edit.remark.trim(),
|
||||
});
|
||||
setFindings((cur) =>
|
||||
cur.map((x) =>
|
||||
isSameFinding(x, f)
|
||||
? {
|
||||
...x,
|
||||
name: updated.name,
|
||||
vulnclass: updated.vulnclass,
|
||||
severity: updated.severity,
|
||||
remark: updated.remark,
|
||||
}
|
||||
? { ...x, name: updated.name, vulnclass: updated.vulnclass, severity: updated.severity }
|
||||
: x,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -3,14 +3,7 @@ import * as React from "react";
|
||||
|
||||
import Link from "next/link";
|
||||
|
||||
import {
|
||||
ArrowDownIcon,
|
||||
ArrowUpIcon,
|
||||
ArrowUpRightIcon,
|
||||
ChevronRightIcon,
|
||||
SearchIcon,
|
||||
StickyNoteIcon,
|
||||
} from "lucide-react";
|
||||
import { ArrowDownIcon, ArrowUpIcon, ArrowUpRightIcon, ChevronRightIcon, SearchIcon } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -87,15 +80,6 @@ function Row({
|
||||
)}
|
||||
</div>
|
||||
<span className="truncate text-xs text-muted-foreground">{f.summary}</span>
|
||||
{f.remark ? (
|
||||
<span
|
||||
className="inline-flex min-w-0 items-center gap-1 truncate text-xs text-amber-700 dark:text-amber-400"
|
||||
title={f.remark}
|
||||
>
|
||||
<StickyNoteIcon className="size-3 shrink-0" />
|
||||
<span className="truncate">{f.remark}</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</button>
|
||||
<Badge variant="outline">
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
export const findingMessages = {
|
||||
"findingDetail.remark": ["备注", "Notes"],
|
||||
"findingDetail.addRemark": ["添加备注", "Add notes"],
|
||||
"findingDetail.editRemark": ["编辑备注", "Edit notes"],
|
||||
"findingDetail.remarkEmpty": [
|
||||
"暂无备注,点击添加排查记录或复核备忘",
|
||||
"No notes yet. Click to add review notes or reminders.",
|
||||
],
|
||||
"findingDetail.remarkEmptyReadOnly": ["暂无备注", "No notes"],
|
||||
"findingDetail.remarkPlaceholder": [
|
||||
"记录排查结论、利用条件或复核备忘…",
|
||||
"Record triage notes, exploit conditions, or follow-up reminders…",
|
||||
],
|
||||
"findingDetail.remarkHint": [
|
||||
"Ctrl/⌘ + Enter 保存,Esc 取消;留空保存可清除备注",
|
||||
"Ctrl/⌘ + Enter to save, Esc to cancel; save empty to clear",
|
||||
],
|
||||
"findingDetail.remarkTooLong": ["备注最多 {{max}} 个字符", "Notes must be {{max}} characters or fewer"],
|
||||
"findingDetail.remarkSaved": ["备注已保存", "Notes saved"],
|
||||
"findingDetail.remarkCleared": ["备注已清除", "Notes cleared"],
|
||||
"findingDetail.editButton": ["编辑", "Edit"],
|
||||
"findingDetail.editTitle": ["编辑漏洞", "Edit finding"],
|
||||
"findingDetail.editDescription": [
|
||||
"手工修改当前漏洞的标题、分类、严重等级、状态、内容与备注。",
|
||||
"Manually update the finding title, category, severity, status, details, and notes.",
|
||||
],
|
||||
"findingDetail.nameLabel": ["漏洞标题", "Title"],
|
||||
"findingDetail.summaryPlaceholder": [
|
||||
"简要描述漏洞位置、成因与影响…",
|
||||
"Summarize the affected component, root cause, and impact…",
|
||||
],
|
||||
"findingDetail.evidencePlaceholder": [
|
||||
"粘贴关键请求、响应片段或复现 PoC…",
|
||||
"Paste key requests, response snippets, or PoC…",
|
||||
],
|
||||
"findingDetail.reportPlaceholder": ["支持 Markdown 格式的详细漏洞报告…", "Detailed Markdown vulnerability report…"],
|
||||
"findingDetail.findingSaved": ["漏洞信息已更新", "Finding updated"],
|
||||
} as const;
|
||||
@@ -1,6 +1,5 @@
|
||||
import { chatUIMessages } from "./chat-ui-messages";
|
||||
import { errorMessages } from "./error-messages";
|
||||
import { findingMessages } from "./finding-messages";
|
||||
import { inlineEditorMessages } from "./inline-editor-messages";
|
||||
import { notifyMessages } from "./notify-messages";
|
||||
import { overviewMessages } from "./overview-messages";
|
||||
@@ -17,7 +16,6 @@ export const messages = {
|
||||
...termsMessages,
|
||||
...taskMessages,
|
||||
...notifyMessages,
|
||||
...findingMessages,
|
||||
...inlineEditorMessages,
|
||||
...scheduleMessages,
|
||||
...chatUIMessages,
|
||||
|
||||
@@ -253,8 +253,8 @@ test("populated findings translate actions and headers while retaining original
|
||||
name: "Original title",
|
||||
vulnclass: "SQL Injection",
|
||||
summary: "原始 AI 发现内容",
|
||||
remark: "人工排查备注",
|
||||
ts: "2026-11-10T12:30:00Z",
|
||||
assets: [],
|
||||
};
|
||||
const props = {
|
||||
items: [finding],
|
||||
@@ -279,9 +279,9 @@ test("populated findings translate actions and headers while retaining original
|
||||
props[k] = noop;
|
||||
await i18n.changeLanguage("en");
|
||||
const english = visible(render(FindingsTable, props));
|
||||
for (const word of ["Finding name", "Retest", "Investigate", "Original title", "原始 AI 发现内容", "人工排查备注"])
|
||||
for (const word of ["Finding name", "Retest", "Investigate", "Original title", "原始 AI 发现内容"])
|
||||
assert.ok(english.includes(word), word);
|
||||
assert.doesNotMatch(english.replaceAll("原始 AI 发现内容", "").replaceAll("人工排查备注", ""), /[\p{Script=Han}]/u);
|
||||
assert.doesNotMatch(english.replaceAll("原始 AI 发现内容", ""), /[\p{Script=Han}]/u);
|
||||
await i18n.changeLanguage("zh-CN");
|
||||
assert.match(visible(render(FindingsTable, props)), /漏洞名称/);
|
||||
});
|
||||
|
||||
+2
-11
@@ -1004,19 +1004,10 @@ export const api = {
|
||||
findingLineage: (id: string) => get<{ nodes: TaskNode[]; edges: Edge[] }>(`/exploration/findings/${id}/lineage`),
|
||||
setFindingStatus: (id: string, status: FindingStatus) => patch<Finding>(`/exploration/findings/${id}`, { status }),
|
||||
setFindingSeverity: (id: string, severity: Severity) => patch<Finding>(`/exploration/findings/${id}`, { severity }),
|
||||
// 保存漏洞的可编辑字段(列表行内编辑与详情页编辑/备注共用),只传出现的字段。
|
||||
// 一次保存漏洞的名称/类别/严重等级(发现列表行内编辑用),只传出现的字段。
|
||||
updateFinding: (
|
||||
id: string,
|
||||
fields: {
|
||||
name?: string;
|
||||
vulnclass?: string;
|
||||
severity?: Severity;
|
||||
status?: FindingStatus;
|
||||
summary?: string;
|
||||
evidence?: string;
|
||||
report?: string;
|
||||
remark?: string;
|
||||
},
|
||||
fields: { name?: string; vulnclass?: string; severity?: Severity; status?: FindingStatus },
|
||||
) => patch<Finding>(`/exploration/findings/${id}`, fields),
|
||||
// 删除漏洞:移除 findings 记录 + 来源探索节点(从发现列表/任务发现 Tab/探索图一并消失)。
|
||||
deleteFinding: (id: string) => del<{ deleted: boolean; id: number }>(`/exploration/findings/${id}`),
|
||||
|
||||
@@ -102,7 +102,7 @@ test("filtering and sorting preserve the polling snapshot", () => {
|
||||
});
|
||||
|
||||
test("keywords match each searchable field as a trimmed, case-insensitive substring", () => {
|
||||
for (const field of ["name", "vulnclass", "summary", "evidence", "remark"]) {
|
||||
for (const field of ["name", "vulnclass", "summary", "evidence"]) {
|
||||
const match = finding("match", "high", rows[0].ts, { [field]: "prefix NeEdLe suffix" });
|
||||
assert.deepEqual(
|
||||
filterAndSortFindings([rows[0], match], "all", { field: "severity", direction: "desc" }, " nEEdle "),
|
||||
|
||||
@@ -17,7 +17,7 @@ export function filterAndSortFindings(
|
||||
(finding) =>
|
||||
(severity === "all" || finding.severity === severity) &&
|
||||
(!keyword ||
|
||||
[finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.remark].some((value) =>
|
||||
[finding.name, finding.vulnclass, finding.summary, finding.evidence].some((value) =>
|
||||
(value ?? "").toLowerCase().includes(keyword),
|
||||
)),
|
||||
)
|
||||
|
||||
@@ -520,11 +520,10 @@ function mockFilterFindings(q: URLSearchParams): (typeof mockFindings)[number][]
|
||||
function mockFindingMatchesQuery(finding: (typeof mockFindings)[number], query: string | null): boolean {
|
||||
const needle = query?.trim().toLowerCase();
|
||||
if (!needle) return true;
|
||||
return [finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.remark, finding.report].some(
|
||||
(value) =>
|
||||
String(value ?? "")
|
||||
.toLowerCase()
|
||||
.includes(needle),
|
||||
return [finding.name, finding.vulnclass, finding.summary, finding.evidence, finding.report].some((value) =>
|
||||
String(value ?? "")
|
||||
.toLowerCase()
|
||||
.includes(needle),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2361,12 +2360,8 @@ function route(m: string, path: string, seg: string[], q: URLSearchParams, b: Re
|
||||
if (m === "PATCH") {
|
||||
if (typeof b.status === "string") f.status = b.status as typeof f.status;
|
||||
if (typeof b.severity === "string") f.severity = b.severity as typeof f.severity;
|
||||
if (typeof b.name === "string") f.name = b.name.trim();
|
||||
if (typeof b.vulnclass === "string") f.vulnclass = b.vulnclass.trim();
|
||||
if (typeof b.summary === "string") f.summary = b.summary.trim();
|
||||
if (typeof b.evidence === "string") f.evidence = b.evidence.trim() ? b.evidence : "";
|
||||
if (typeof b.report === "string") f.report = b.report.trim() ? b.report : "";
|
||||
if (b.remark !== undefined) f.remark = mockRemark(b.remark);
|
||||
if (typeof b.name === "string") f.name = b.name;
|
||||
if (typeof b.vulnclass === "string") f.vulnclass = b.vulnclass;
|
||||
}
|
||||
const contextTaskId = q.get("context_task");
|
||||
const contextTask = contextTaskId ? mockTasks.find((item) => item.id === contextTaskId) : undefined;
|
||||
|
||||
@@ -6,7 +6,6 @@ export type EngineMode = "exploring" | "paused" | "stalled" | "idle";
|
||||
|
||||
// Keep these limits aligned with db.MaxTaskRemarkRunes and db.MaxTaskWorkerCount.
|
||||
export const MAX_TASK_REMARK_RUNES = 2000;
|
||||
export const MAX_FINDING_REMARK_RUNES = 2000;
|
||||
export const MAX_TASK_WORKER_COUNT = 50;
|
||||
|
||||
// Parse the optional worker-count input without silently changing invalid values.
|
||||
@@ -539,7 +538,6 @@ export interface Finding {
|
||||
status: FindingStatus;
|
||||
summary: string;
|
||||
evidence: string;
|
||||
remark?: string; // 人工备注
|
||||
report?: string; // 详细报告(Markdown);仅详情接口返回,列表为空
|
||||
report_conversation_id?: number;
|
||||
intent_id?: string;
|
||||
|
||||
Reference in new issue
Block a user