diff --git a/docs/zh-CN/deep-assessments.md b/docs/zh-CN/deep-assessments.md index 707fcfd1..ff58aa01 100644 --- a/docs/zh-CN/deep-assessments.md +++ b/docs/zh-CN/deep-assessments.md @@ -126,6 +126,10 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills 点击「开始 / 继续」后自动规划并执行本测评的待办步骤;点击「暂停」后停止新派发,取消规划器与全部在执行的步骤,等待所管执行资源收尾后显示「已暂停」。自动重试、等待新进展和待恢复状态也可暂停;手动暂停后不会被后台恢复队列或服务重启重新启动。打开页面、查看详情和刷新均不会启动任务。 +已停止的测评提供独立的「继续测评」入口,保留已完成步骤、原 Pi 会话及证据;只有用户明确点击才会恢复。仍有结果不明或执行资源尚未确认停止的步骤时,先处理待核对项;仍有待答复问题时进入「待答复」,不派发工作。已完成的测评不能重新执行。 + +「确认已核对」是独立的核对操作,已停止、已完成的测评也可保存。核对后该步骤从「待核对」筛选中移出,历史记录和原始回执保留,任务保持停止或完成状态。确认窗口打开期间若任务有其他更新,页面会重新读取版本;若该步骤已进入另一轮执行,则要求重新查看回执,避免核对到新的执行。 + 1. 工具派发前提交调用意图,结果落库后才交还 Pi。 2. 已确认回执关联原生助手条目与 tool-call ID。若回执已提交而 Pi 记录未写入就退出,恢复时补回已确认结果。 3. 暂停与停止等待本地执行资源收尾,再从同任务、步骤、会话及工具的终态执行记录核对回执。取消信号本身不等于结果不明;确认已取消的调用保存为取消及错误回执,续跑时交回原 Pi 会话,不伪装为成功。旧版误标的记录在点击开始时同样自动核对。 @@ -147,7 +151,7 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills | `GET / POST /api/deep-assessments` | 查询列表(`archived=true` 查看归档)/ 创建草稿 | | `GET / DELETE /api/deep-assessments/:id` | 详情 / 删除非活动测评 | | `GET /api/deep-assessments/:id?step_limit=50&step_offset=0&runtime=true` | 分页详情与运行概览;`step_order=queue&step_status=needs_review` 定位待核对步骤 | -| `POST /api/deep-assessments/:id/control/:action` | start、pause、cancel、guidance、answer、retry、archive、restore,以及 intent-pause、intent-resume、intent-priority、intent-guidance | +| `POST /api/deep-assessments/:id/control/:action` | start、continue-stopped、pause、cancel、guidance、answer、retry、reconcile、archive、restore,以及 intent-pause、intent-resume、intent-priority、intent-guidance | | `GET / POST /api/deep-assessments/:id/assets` | 查看共享/关联资产图,或关联资产;`asset_id` 查询服务端点 | | `GET /api/deep-assessments/:id/intents?status=&offset=0` | 优先级队列和状态计数 | | `GET /api/deep-assessments/:id/facts?confidence=&offset=0` | 分页读取观察/推断事实 | @@ -160,7 +164,7 @@ Pi `SessionManager` 管理会话上下文、原生压缩、工具搜索、Skills | `GET /api/deep-assessments/:id/receipts?offset=0` | 工具回执 | | `GET /api/deep-assessments/:id/report` | 包含当前状态及缺口的阶段报告 | -控制请求携带 `revision`;结果不明的步骤重试另需 `reconciled:true`,资源清理未确认另需 `cleanup_confirmed:true`。 +控制请求携带 `revision`。核对使用 `reconcile`,传 `step_id` 和 `reconciled:true`;资源清理未确认另需 `cleanup_confirmed:true`。兼容旧客户端通过 `retry` 提交核对,但不会自动开始执行。`continue-stopped` 仅用于用户明确继续已停止测评,另检查执行权限。 单条意图操作另传 `step_id`;调整优先级传 `priority`(1–1000),定向补充传 `message`。响应的 `guidance_delivered` 表示是否已投递到当前 Pi 会话;未投递时已保存,后续继续生效。 diff --git a/internal/deepassessment/engine.go b/internal/deepassessment/engine.go index 3353dae7..75c6fbf3 100644 --- a/internal/deepassessment/engine.go +++ b/internal/deepassessment/engine.go @@ -32,6 +32,15 @@ func (e *Engine) Start(id, executor string, revision int64) error { } func (e *Engine) start(id, executor string, revision int64, automatic bool) error { + return e.startWithReopen(id, executor, revision, automatic, false) +} + +// Only an explicit user continuation may reopen a stopped assessment. +func (e *Engine) ContinueStopped(id, executor string, revision int64) error { + return e.startWithReopen(id, executor, revision, false, true) +} + +func (e *Engine) startWithReopen(id, executor string, revision int64, automatic, reopen bool) error { e.mu.Lock() defer e.mu.Unlock() if e.closed { @@ -47,7 +56,7 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro if err != nil { return err } - if current.Revision != revision || current.Archived || Active(current.Status) || current.Status == "completed" || current.Status == "cancelled" { + if current.Revision != revision || current.Archived || Active(current.Status) || current.Status == "completed" || current.Status == "cancelled" && !reopen || reopen && current.Status != "cancelled" { return ErrConflict } if automatic && current.Status != "recovering" && current.Status != "waiting_retry" && current.Status != "waiting_progress" { @@ -61,11 +70,17 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro if err != nil { return err } - err = e.Store.Change(id, "", "started", "开始/继续任务", func(t *Task) error { + kind, message := "started", "开始/继续任务" + if reopen { + kind = "reopened" + message = "用户继续已停止的测评,保留原进度与会话。" + } + waitingForAnswer := false + err = e.Store.Change(id, "", kind, message, func(t *Task) error { if t.Archived { return fmt.Errorf("请先恢复归档,再开始任务") } - if t.Revision != revision || Active(t.Status) || t.Status == "completed" || t.Status == "cancelled" { + if t.Revision != revision || Active(t.Status) || t.Status == "completed" || t.Status == "cancelled" && !reopen || reopen && t.Status != "cancelled" { return ErrConflict } if automatic && t.Status != "recovering" && t.Status != "waiting_retry" && t.Status != "waiting_progress" { @@ -77,6 +92,13 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro repairedStep := false for i := range t.Steps { step := &t.Steps[i] + if reopen && step.Status == "reconciled" { + repairedStep = true + step.Status = "pending" + if step.UserPaused { + step.Status = "paused" + } + } if step.Status == "uncertain" && resolved[step.ID] && !unknown[step.ID] { step.Status = "pending" if step.UserPaused { @@ -91,6 +113,14 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro } } if t.Question != "" { + if reopen { + t.Status = "waiting_input" + t.ExecutorID = executor + t.RestartPending = false + t.NextWake = nil + waitingForAnswer = true + return nil + } return fmt.Errorf("answer the pending question before continuing") } if t.Status != "waiting_retry" && t.Status != "recovering" { @@ -110,6 +140,9 @@ func (e *Engine) start(id, executor string, revision int64, automatic bool) erro if err != nil { return err } + if waitingForAnswer { + return nil + } ctx, cancel := context.WithCancel(context.Background()) e.active[id] = cancel e.wg.Add(1) diff --git a/internal/deepassessment/receipts.go b/internal/deepassessment/receipts.go index ee2bad7c..11e428e9 100644 --- a/internal/deepassessment/receipts.go +++ b/internal/deepassessment/receipts.go @@ -11,6 +11,28 @@ import ( ) func (s *Store) RetryStep(id, step string, revision int64, reconciled bool) error { + return s.recoverStep(id, step, revision, reconciled, false) +} + +// Reconciliation records the operator's acknowledgement. It is not a restart, +// including when the assessment has already been stopped or completed. +func (s *Store) ReconcileStep(id, step string, revision int64, confirmed bool) error { + current, err := s.Get(id) + if err != nil { + return err + } + if current.Revision != revision || current.Archived || Active(current.Status) { + return ErrConflict + } + if confirmed { + if _, err = s.ReconcileKnownCalls(id, step); err != nil { + return err + } + } + return s.recoverStep(id, step, revision, confirmed, true) +} + +func (s *Store) recoverStep(id, step string, revision int64, reconciled, acknowledgement bool) error { s.mu.Lock() defer s.mu.Unlock() tx, err := s.DB.Begin() @@ -26,13 +48,25 @@ func (s *Store) RetryStep(id, step string, revision int64, reconciled bool) erro if err = json.Unmarshal([]byte(raw), &t); err != nil { return err } - if t.Revision != revision || Active(t.Status) || t.Status == "completed" || t.Status == "cancelled" { + closed := t.Status == "completed" || t.Status == "cancelled" + if t.Archived || t.Revision != revision || Active(t.Status) || closed && !acknowledgement { return ErrConflict } st := t.Step(step) if st == nil { return fmt.Errorf("unknown step") } + if acknowledgement { + if !reconciled { + return fmt.Errorf("请明确确认已核对调用结果及执行资源状态") + } + if st.Status == "reconciled" { + return nil + } + if st.Status != "uncertain" && st.Status != "cleanup_unconfirmed" { + return ErrConflict + } + } if st.Status != "failed" && st.Status != "blocked" && st.Status != "interrupted" && st.Status != "uncertain" && st.Status != "cleanup_unconfirmed" { return ErrConflict } @@ -46,21 +80,26 @@ func (s *Store) RetryStep(id, step string, revision int64, reconciled bool) erro if st.UserPaused { st.Status = "paused" } - st.StalledSegments = 0 - t.Status = "paused" - if t.Question != "" { - t.Status = "waiting_input" + if closed { + st.Status = "reconciled" } - for _, pending := range t.Steps { - if pending.Status == "uncertain" || pending.Status == "cleanup_unconfirmed" { - t.Status = "needs_review" - break + st.StalledSegments = 0 + if !closed { + t.Status = "paused" + if t.Question != "" { + t.Status = "waiting_input" + } + for _, pending := range t.Steps { + if pending.Status == "uncertain" || pending.Status == "cleanup_unconfirmed" { + t.Status = "needs_review" + break + } } } // Acknowledging one receipt is not an instruction to restart the assessment. t.RestartPending = false t.NextWake = nil - if reconciled { + if reconciled && !closed { if t.Status == "needs_review" { t.Summary = "仍有步骤的执行结果待核对,请继续查看回执。" } else { @@ -77,7 +116,18 @@ func (s *Store) RetryStep(id, step string, revision int64, reconciled bool) erro if _, err = tx.Exec(`UPDATE deep_assessments SET status=?,payload=?,updated_at=? WHERE id=?`, t.Status, string(body), t.UpdatedAt, id); err != nil { return err } - if _, err = tx.Exec(`INSERT INTO deep_assessment_events(task_id,step_id,kind,message,created_at) VALUES(?,?,'retry','步骤已重新排队,保留原会话;等待手动开始。',?)`, id, step, t.UpdatedAt); err != nil { + kind, message := "retry", "步骤已重新排队,保留原会话;等待手动开始。" + if acknowledgement { + kind = "reconciled" + message = "已记录人工核对,原始回执与证据保留;未启动测评。" + } + if _, err = tx.Exec(`INSERT INTO deep_assessment_events(task_id,step_id,kind,message,created_at) VALUES(?,?,?,?,?)`, id, step, kind, message, t.UpdatedAt); err != nil { + return err + } + if err = syncGraph(tx, &t, step, kind, message, 0); err != nil { + return err + } + if _, err = tx.Exec(`UPDATE deep_assessment_nodes SET state='reconciled' WHERE task_id=? AND step_id=? AND kind='receipt' AND state IN ('running','uncertain') AND id IN (SELECT 'receipt:'||id FROM deep_assessment_calls WHERE task_id=? AND step_id=? AND status='reconciled')`, id, step, id, step); err != nil { return err } return tx.Commit() diff --git a/internal/deepassessment/reconcile_closed_test.go b/internal/deepassessment/reconcile_closed_test.go new file mode 100644 index 00000000..47dc8d20 --- /dev/null +++ b/internal/deepassessment/reconcile_closed_test.go @@ -0,0 +1,129 @@ +package deepassessment + +import ( + "context" + "sync/atomic" + "testing" + + "cyberstrike-ai/internal/agentruntime" +) + +func TestReconcileClosedAssessmentPreservesTerminalStateAndEvidence(t *testing.T) { + for _, status := range []string{"cancelled", "completed"} { + t.Run(status, func(t *testing.T) { + s, task := fixture(t) + s.Change(task.ID, "", "seed", "", func(v *Task) error { + v.Status = status + v.TokensUsed = 123 + v.Summary = "preserve final conclusions" + v.Steps = []Step{{ID: "one", Status: "uncertain", ConversationID: "original-session", Summary: "original progress"}, {ID: "two", Status: "cleanup_unconfirmed"}, {ID: "done", Status: "completed"}} + return nil + }) + call := agentruntime.ToolCall{ID: "original-call", Name: "fixture-read"} + s.BeginCall(task.ID, "one", call) + s.FinishCall(call, agentruntime.ToolResult{Content: "original uncertain receipt", IsError: true}, true) + before, _ := s.Get(task.ID) + if err := s.ReconcileStep(task.ID, "one", before.Revision, false); err == nil { + t.Fatal("confirmation missing") + } + if err := s.ReconcileStep(task.ID, "one", before.Revision-1, true); err != ErrConflict { + t.Fatal(err) + } + if err := s.RetryStep(task.ID, "one", before.Revision, true); err != ErrConflict { + t.Fatal("retry revived ended task", err) + } + if err := s.ReconcileStep(task.ID, "one", before.Revision, true); err != nil { + t.Fatal(err) + } + current, _ := s.Get(task.ID) + if current.Status != status || current.Step("one").Status != "reconciled" || current.Step("done").Status != "completed" || current.Step("one").ConversationID != "original-session" || current.TokensUsed != 123 || current.Summary != before.Summary { + t.Fatal(current) + } + list, err := s.List(task.OwnerID, "own", "", "", 20, 0) + if err != nil || len(list) != 1 || list[0].ReviewCount != 1 { + t.Fatal(list, err) + } + original, err := s.Node(task.ID, "receipt:original-call", 0) + if err != nil || original["node"].(Node).Body != "original uncertain receipt" || original["node"].(Node).State != "reconciled" { + t.Fatal(original, err) + } + if err = s.ReconcileStep(task.ID, "two", current.Revision, true); err != nil { + t.Fatal(err) + } + current, _ = s.Get(task.ID) + rev := current.Revision + if err = s.ReconcileStep(task.ID, "one", current.Revision, true); err != nil { + t.Fatal(err) + } + if err = s.Recover(); err != nil { + t.Fatal(err) + } + current, _ = s.Get(task.ID) + if current.Status != status || current.Revision != rev || current.RestartPending || current.NextWake != nil { + t.Fatal("acknowledgement started work or changed terminal state", current) + } + list, _ = s.List(task.OwnerID, "own", "", "", 20, 0) + if list[0].ReviewCount != 0 { + t.Fatal(list) + } + }) + } +} + +func TestOnlyExplicitContinueReopensStoppedAssessment(t *testing.T) { + s, task := fixture(t) + s.Change(task.ID, "", "seed", "", func(v *Task) error { + v.Status = "cancelled" + v.AutoResume = true + v.Steps = []Step{{ID: "done", Status: "completed", Summary: "verified result", ConversationID: "completed-session"}, {ID: "remaining", Status: "reconciled", ConversationID: "saved-session"}} + return nil + }) + var runs atomic.Int32 + e := NewEngine(s, fakeRuntime{plan: func(context.Context, *Task) (Proposal, error) { return Proposal{}, nil }, run: func(_ context.Context, _ *Task, st Step, _ func(string, string) error) (Outcome, error) { + runs.Add(1) + if st.ID != "remaining" || st.ConversationID != "saved-session" { + t.Error("replayed completed work or lost session", st) + } + return Outcome{Status: "completed", Summary: "done", ConversationID: st.ConversationID}, nil + }}) + t.Cleanup(e.Close) + current, _ := s.Get(task.ID) + if err := e.Start(task.ID, task.OwnerID, current.Revision); err != ErrConflict { + t.Fatal(err) + } + if err := e.start(task.ID, task.OwnerID, current.Revision, true); err != ErrConflict { + t.Fatal(err) + } + if err := s.Recover(); err != nil { + t.Fatal(err) + } + current, _ = s.Get(task.ID) + if current.Status != "cancelled" { + t.Fatal(current) + } + if err := e.ContinueStopped(task.ID, task.OwnerID, current.Revision); err != nil { + t.Fatal(err) + } + current = await(t, s, task.ID, func(v *Task) bool { return v.Status == "completed" }) + if runs.Load() != 1 || current.Step("done").Status != "completed" { + t.Fatal(runs.Load(), current) + } + if err := e.ContinueStopped(task.ID, task.OwnerID, current.Revision); err == nil { + t.Fatal("completed assessment reopened") + } +} + +func TestStoppedContinuationKeepsPendingQuestion(t *testing.T) { + s, task := fixture(t) + s.Change(task.ID, "", "seed", "", func(v *Task) error { v.Status = "cancelled"; v.Question = "Need fixture input"; return nil }) + e := NewEngine(s, fakeRuntime{}) + t.Cleanup(e.Close) + current, _ := s.Get(task.ID) + if err := e.ContinueStopped(task.ID, task.OwnerID, current.Revision); err != nil { + t.Fatal(err) + } + current, _ = s.Get(task.ID) + if current.Status != "waiting_input" || current.Question == "" || e.Live(task.ID).Active { + t.Fatal(current) + } +} diff --git a/internal/deepassessment/store.go b/internal/deepassessment/store.go index 4bc86114..99bafd45 100644 --- a/internal/deepassessment/store.go +++ b/internal/deepassessment/store.go @@ -125,7 +125,7 @@ func (s *Store) change(id, step, kind, message string, version *int64, fn func(* func (s *Store) List(user, scope, status, query string, limit, offset int, archived ...bool) ([]*Task, error) { showArchived := len(archived) > 0 && archived[0] - q := `SELECT json_remove(payload,'$.steps','$.guidance','$.scope','$.criteria','$.objective','$.strategy','$.question','$.metrics') FROM deep_assessments t WHERE COALESCE(json_extract(payload,'$.archived'),0)=?` + q := `SELECT json_set(json_remove(payload,'$.steps','$.guidance','$.scope','$.criteria','$.objective','$.strategy','$.question','$.metrics'),'$.review_count',(SELECT COUNT(*) FROM json_each(t.payload,'$.steps') st WHERE json_extract(st.value,'$.status') IN ('uncertain','cleanup_unconfirmed'))) FROM deep_assessments t WHERE COALESCE(json_extract(payload,'$.archived'),0)=?` args := []any{showArchived} if scope != database.RBACScopeAll { assignment := `EXISTS(SELECT 1 FROM rbac_resource_assignments r WHERE r.user_id=? AND r.resource_type='deep_assessment' AND r.resource_id=t.id)` diff --git a/internal/deepassessment/types.go b/internal/deepassessment/types.go index 7e55aec9..92574181 100644 --- a/internal/deepassessment/types.go +++ b/internal/deepassessment/types.go @@ -12,6 +12,8 @@ import ( ) type Task struct { + // Derived by list/detail projections; never used as an execution authority. + ReviewCount int `json:"review_count,omitempty"` Archived bool `json:"archived"` ArchivedAt *time.Time `json:"archived_at,omitempty"` PlannedGraphVersion int64 `json:"planned_graph_version"` diff --git a/internal/handler/deep_assessment.go b/internal/handler/deep_assessment.go index 4b1cff55..2c6c4a84 100644 --- a/internal/handler/deep_assessment.go +++ b/internal/handler/deep_assessment.go @@ -84,7 +84,8 @@ func deepAssessmentError(c *gin.Context, err error) { code = 404 } if errors.Is(err, deepassessment.ErrConflict) { - code = 409 + c.JSON(409, gin.H{"error": "测评状态已更新,请刷新后重试。", "code": "task_changed"}) + return } c.JSON(code, gin.H{"error": err.Error()}) } @@ -227,6 +228,14 @@ func (h *AgentHandler) ListDeepAssessments(c *gin.Context) { // Explicit paging keeps long-lived workspaces small without limiting stored work. func deepAssessmentView(c *gin.Context, t *deepassessment.Task) gin.H { + copy := *t + copy.ReviewCount = 0 + for _, step := range t.Steps { + if step.Status == "uncertain" || step.Status == "cleanup_unconfirmed" { + copy.ReviewCount++ + } + } + t = © limit, _ := strconv.Atoi(c.Query("step_limit")) offset, _ := strconv.Atoi(c.Query("step_offset")) if limit <= 0 { @@ -383,6 +392,19 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) { deepAssessmentError(c, err) return } + // Old clients used retry for the acknowledgement button. Keep those clicks + // compatible while treating them as review-only, even on stopped tasks. + if action == "retry" && (req.Reconciled || req.CleanupConfirmed) { + if step := t.Step(req.StepID); step != nil { + if step.Status == "uncertain" && req.Reconciled { + action = "reconcile" + } + if step.Status == "cleanup_unconfirmed" { + action = "reconcile" + req.Reconciled = req.Reconciled || req.CleanupConfirmed + } + } + } if t.Archived && action != "restore" { deepAssessmentError(c, fmt.Errorf("请先恢复归档,再操作测评")) return @@ -398,14 +420,22 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) { return } } - if action == "start" || action == "answer" || action == "guidance" { + if action == "start" || action == "continue-stopped" || action == "answer" || action == "guidance" { + if action == "continue-stopped" && !security.SessionHasPermission(c, "agent:execute") { + c.JSON(403, gin.H{"error": "缺少执行权限"}) + return + } t.ExecutorID = session.UserID if _, err = h.deepAssessmentRuntime.principal(t); err != nil { c.JSON(403, gin.H{"error": err.Error()}) return } } - if action == "retry" { + if action == "retry" || action == "reconcile" { + if action == "reconcile" && !req.Reconciled { + deepAssessmentError(c, fmt.Errorf("请确认已核对调用结果与执行资源状态")) + return + } if step := t.Step(req.StepID); step != nil && step.Status == "uncertain" && !req.Reconciled { deepAssessmentError(c, fmt.Errorf("请核对上次工具回执,并明确确认已处理结果不明的调用")) return @@ -415,7 +445,13 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) { deepAssessmentError(c, fmt.Errorf("请先确认上次执行资源已停止")) return } + } + if action == "reconcile" || t.Step(req.StepID) != nil && t.Step(req.StepID).Status == "cleanup_unconfirmed" { for _, running := range h.tasks.GetActiveTasks() { + step := t.Step(req.StepID) + if step == nil { + break + } if running.ConversationID == step.ConversationID { deepAssessmentError(c, fmt.Errorf("原执行仍在清理,请先在工具监控中确认停止")) return @@ -436,10 +472,14 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) { err = h.deepAssessments.SetArchived(id, *req.Revision, action == "archive") case "start": err = h.deepAssessments.Start(id, session.UserID, *req.Revision) + case "continue-stopped": + err = h.deepAssessments.ContinueStopped(id, session.UserID, *req.Revision) case "pause", "cancel": err = h.deepAssessments.Stop(id, *req.Revision, action == "cancel") case "retry": err = h.deepAssessments.Store.RetryStep(id, req.StepID, *req.Revision, req.Reconciled || req.CleanupConfirmed) + case "reconcile": + err = h.deepAssessments.Store.ReconcileStep(id, req.StepID, *req.Revision, req.Reconciled) case "budget": c.JSON(410, gin.H{"error": "深度测评已改为持续执行,不再设置任务预算"}) return @@ -485,6 +525,12 @@ func (h *AgentHandler) ControlDeepAssessment(c *gin.Context) { h.deepAssessmentRuntime.steer(id, req.Message) } response := deepAssessmentView(c, t) + if action == "continue-stopped" && t.Status == "waiting_input" { + response["start_error"] = "测评已恢复,待答复:" + t.Question + } + if req.StepID != "" { + response["step"] = t.Step(req.StepID) + } if action == "intent-guidance" { delivered, deliveryErr := h.deepAssessmentRuntime.steerStep(id, req.StepID) response["guidance_delivered"] = delivered diff --git a/internal/handler/deep_assessment_findings.go b/internal/handler/deep_assessment_findings.go index fb1d61ef..f6273fb4 100644 --- a/internal/handler/deep_assessment_findings.go +++ b/internal/handler/deep_assessment_findings.go @@ -80,5 +80,5 @@ func (h *AgentHandler) DeepAssessmentStep(c *gin.Context) { deepAssessmentError(c, sql.ErrNoRows) return } - c.JSON(200, gin.H{"step": step}) + c.JSON(200, gin.H{"step": step, "revision": task.Revision, "task_status": task.Status}) } diff --git a/internal/handler/deep_assessment_reconcile_test.go b/internal/handler/deep_assessment_reconcile_test.go new file mode 100644 index 00000000..644b7513 --- /dev/null +++ b/internal/handler/deep_assessment_reconcile_test.go @@ -0,0 +1,60 @@ +package handler + +import ( + "encoding/json" + "fmt" + "net/http/httptest" + "strings" + "testing" + + "cyberstrike-ai/internal/deepassessment" +) + +func TestDeepAssessmentStoppedReviewIsMetadataOnlyAndLegacyClickWorks(t *testing.T) { + h, task := deepAssessmentFixture(t) + h.deepAssessments.Store.Change(task.ID, "", "seed", "", func(v *deepassessment.Task) error { + v.Status = "cancelled" + v.Steps = []deepassessment.Step{{ID: "one", Status: "uncertain"}, {ID: "two", Status: "cleanup_unconfirmed"}} + return nil + }) + router := assessmentRouter(h, task.OwnerID) + router.GET("/api/deep-assessments/:id/steps/:stepId", h.DeepAssessmentStep) + post := func(action, step string) *httptest.ResponseRecorder { + current, _ := h.deepAssessments.Store.Get(task.ID) + w := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/deep-assessments/task/control/"+action+"?step_limit=50&step_order=queue&step_status=needs_review", strings.NewReader(fmt.Sprintf(`{"revision":%d,"step_id":%q,"reconciled":true,"cleanup_confirmed":true}`, current.Revision, step))) + req.Header.Set("Authorization", "Bearer fixture") + req.Header.Set("Content-Type", "application/json") + router.ServeHTTP(w, req) + return w + } + for index, action := range []string{"retry", "reconcile"} { + step := []string{"one", "two"}[index] + w := post(action, step) + if w.Code != 200 { + t.Fatal(w.Code, w.Body.String()) + } + var result struct { + Task deepassessment.Task `json:"task"` + StepTotal int `json:"step_total"` + } + json.Unmarshal(w.Body.Bytes(), &result) + if result.Task.Status != "cancelled" || result.StepTotal != 1-index || result.Task.ReviewCount != 1-index { + t.Fatal(w.Body.String()) + } + } + current, _ := h.deepAssessments.Store.Get(task.ID) + if h.deepAssessments.Live(task.ID).Active || current.Status != "cancelled" { + t.Fatal(current) + } + w := httptest.NewRecorder() + router.ServeHTTP(w, httptest.NewRequest("GET", "/api/deep-assessments/task/steps/one", nil)) + if !strings.Contains(w.Body.String(), `"revision":`) { + t.Fatal("preflight lacks current revision", w.Body.String()) + } + // A write-only session cannot use the explicit continuation endpoint to execute. + denied := post("continue-stopped", "") + if denied.Code != 403 { + t.Fatal(denied.Code, denied.Body.String()) + } +} diff --git a/scripts/deep-assessments-browser.test.cjs b/scripts/deep-assessments-browser.test.cjs index 038e8a1b..6f98ad4f 100644 --- a/scripts/deep-assessments-browser.test.cjs +++ b/scripts/deep-assessments-browser.test.cjs @@ -30,7 +30,7 @@ async function fixture(t) { if(url.pathname==='/api/deep-assessments'){ if(req.method==='POST'){const task={...sample('new'),...body};state.tasks.set(task.id,task);return send(201,{task});} const filtered=[...state.tasks.values()].filter(t=>!!t.archived===(url.searchParams.get('archived')==='true')).filter(t=>(!url.searchParams.get('q')||t.name.includes(url.searchParams.get('q')))&&(!url.searchParams.get('status')||t.status===url.searchParams.get('status'))); - const offset=Number(url.searchParams.get('offset')||0),limit=Number(url.searchParams.get('limit')||20);return send(200,{tasks:filtered.slice(offset,offset+limit),has_more:filtered.length>offset+limit}); + const offset=Number(url.searchParams.get('offset')||0),limit=Number(url.searchParams.get('limit')||20);return send(200,{tasks:filtered.slice(offset,offset+limit).map(t=>({...t,steps:undefined,review_count:(t.steps||[]).filter(s=>['uncertain','cleanup_unconfirmed'].includes(s.status)).length})),has_more:filtered.length>offset+limit}); } const match=url.pathname.match(/^\/api\/deep-assessments\/([^/]+)(?:\/(.*))?$/); if(!match)return send(404,{error:'unhandled route'}); @@ -43,7 +43,7 @@ async function fixture(t) { return send(200,{assets,nodes:assets.flatMap(a=>[{id:'domain:example.test',kind:'domain',title:'example.test',body:'',asset_ids:[a.id]},{id:'asset:'+a.id,kind:'service',title:a.host,body:JSON.stringify(a),asset_ids:[a.id]},{id:'endpoint:'+a.id,kind:'endpoint',title:'GET /fixture',body:'original endpoint',asset_ids:[a.id]}]),edges:assets.flatMap(a=>[{source:'domain:example.test',target:'asset:'+a.id,relation:'exposes'},{source:'asset:'+a.id,target:'endpoint:'+a.id,relation:'contains'}]),total:assets.length,next_offset:assets.length,has_more:false}); } if(match[2]==='facts'){const facts=(task.facts||[]).filter(f=>!url.searchParams.get('confidence')||f.confidence===url.searchParams.get('confidence'));return send(200,{facts,next_offset:facts.length,has_more:false});} - if(match[2]?.startsWith('steps/'))return send(200,{step:task.steps.find(s=>s.id===match[2].slice(6))}); + if(match[2]?.startsWith('steps/'))return send(200,{step:task.steps.find(s=>s.id===match[2].slice(6)),revision:task.revision,task_status:task.status}); if(match[2]==='graph'){const summary=url.searchParams.get('view')==='summary';const nodes=summary?graph.nodes.filter(n=>!['receipt','observation'].includes(n.kind)):graph.nodes;const ids=new Set(nodes.map(n=>n.id));return send(200,{...graph,nodes,edges:graph.edges.filter(e=>ids.has(e.source)&&ids.has(e.target)),primary_count:nodes.filter(n=>!n.boundary).length-1,details_hidden:graph.nodes.length-nodes.length,boundary_total:graph.boundary_total||0});} if(match[2]==='graph/node'){const node=graph.nodes.find(n=>n.id===url.searchParams.get('node_id'));if(!node)return send(404,{error:'missing node'});const refs=graph.edges.flatMap(e=>e.target===node.id?[{direction:'upstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.source)}]:e.source===node.id?[{direction:'downstream',relation:e.relation,node:graph.nodes.find(n=>n.id===e.target)}]:[]).filter(r=>r.node);return send(200,{node,next_offset:node.body.length,has_more:false,relations:refs,relations_next_offset:refs.length,relations_has_more:false});} if(match[2]==='events')return send(200,{events:[]}); @@ -55,21 +55,21 @@ async function fixture(t) { if(!task.known_cancellation)return send(400,{error:'仍有结果不明的工具调用,请先查看待核对步骤和回执'}); task.steps.forEach(s=>{if(s.status==='uncertain')s.status='pending';}); } - const action=match[2].split('/')[1];if(action==='start')task.status='running';if(action==='pause')task.status='paused';if(action==='archive'){task.archived=true;if(!['draft','completed','cancelled'].includes(task.status))task.status='paused';}if(action==='restore')task.archived=false;if(action==='guidance')task.summary=body.message;if(action==='budget')Object.assign(task,body);task.revision++; + const action=match[2].split('/')[1];if(action==='start'||action==='continue-stopped'){task.status='running';task.steps.forEach(s=>{if(s.status==='reconciled')s.status='pending';});}if(action==='pause')task.status='paused';if(action==='archive'){task.archived=true;if(!['draft','completed','cancelled'].includes(task.status))task.status='paused';}if(action==='restore')task.archived=false;if(action==='guidance')task.summary=body.message;if(action==='budget')Object.assign(task,body);task.revision++; if(action==='intent-pause'){const st=task.steps.find(s=>s.id===body.step_id);st.status='paused';st.user_paused=true;} if(action==='intent-resume'){const st=task.steps.find(s=>s.id===body.step_id);st.status='pending';st.user_paused=false;} if(action==='intent-priority')task.steps.find(s=>s.id===body.step_id).priority=body.priority; if(action==='intent-guidance'){const st=task.steps.find(s=>s.id===body.step_id);(st.guidance||=[]).push(body.message);} - if(action==='retry'){ + if(action==='retry'||action==='reconcile'){ const step=task.steps.find(s=>s.id===body.step_id);if(!step||!body.reconciled)return send(400,{error:'review required'}); - step.status='pending';task.status=task.steps.some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status))?'needs_review':'paused'; + const closed=['cancelled','completed'].includes(task.status);step.status=closed?'reconciled':'pending';if(!closed)task.status=task.steps.some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status))?'needs_review':'paused'; } } else if(req.method==='DELETE') state.tasks.delete(task.id); const counts={};for(const step of task.steps||[])counts[step.status]=(counts[step.status]||0)+1;counts.needs_review=(counts.uncertain||0)+(counts.cleanup_unconfirmed||0); const queue=url.searchParams.get('step_order')==='queue',filter=url.searchParams.get('step_status'); const steps=(task.steps||[]).filter(s=>!queue||!filter||s.status===filter||filter==='needs_review'&&['uncertain','cleanup_unconfirmed'].includes(s.status)); const stepOffset=Number(url.searchParams.get('step_offset')||0),stepLimit=Number(url.searchParams.get('step_limit')||steps.length); - return send(200,{runtime:{live:{active:task.status==='running',planning:false,workers:counts.running||0},counts,intents:(task.steps||[]).filter(s=>s.status==='running'),tools:[],recent:[],facts:0,findings:0,findings_visible:true,asset_names:{},...task.runtime},guidance_delivered:match[2]==='control/intent-guidance'&&task.status==='running'&&task.steps.find(s=>s.id===body?.step_id)?.status==='running',task:{...task,steps:steps.slice(stepOffset,stepOffset+stepLimit)},intent_counts:counts,step_total:steps.length,step_has_more:stepOffset+stepLimits.status==='running'),tools:[],recent:[],facts:0,findings:0,findings_visible:true,asset_names:{},...task.runtime},guidance_delivered:match[2]==='control/intent-guidance'&&task.status==='running'&&task.steps.find(s=>s.id===body?.step_id)?.status==='running',step:body?.step_id?task.steps.find(s=>s.id===body.step_id):undefined,task:{...task,review_count:counts.needs_review,steps:steps.slice(stepOffset,stepOffset+stepLimit)},intent_counts:counts,step_total:steps.length,step_has_more:stepOffset+stepLimitserver.listen(0,'127.0.0.1',resolve)); const executablePath=process.env.CHROME_PATH||(process.platform==='darwin'?'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome':undefined); @@ -498,16 +498,16 @@ test('unknown results remain reviewable without automatically starting the asses assert.ok(state.requests.some(r=>r.path.endsWith('/receipts')&&r.query.step_id==='old-unknown')); await page.locator('#da-recovery-notice [data-da-action="review"]').click();await page.locator('.da-step[data-step="old-unknown"]').waitFor(); page.removeAllListeners('dialog');page.once('dialog',d=>d.dismiss()); - await page.locator('.da-step[data-step="old-unknown"] [data-da-action="retry"]').click(); + await page.locator('.da-step[data-step="old-unknown"] [data-da-action="reconcile"]').click(); assert.equal(state.requests.filter(r=>r.method==='POST').length,0); page.on('dialog',d=>d.accept()); - await page.locator('.da-step[data-step="old-unknown"] [data-da-action="retry"]').click(); + await page.locator('.da-step[data-step="old-unknown"] [data-da-action="reconcile"]').click(); await page.waitForFunction(()=>document.querySelectorAll('.da-step').length===1); assert.equal(task.status,'needs_review');assert.equal(await page.locator('#da-controls [data-da-action="start"]').isEnabled(),true); await page.setViewportSize({width:390,height:844}); assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)); if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'review-mobile.png'),fullPage:true}); - await page.locator('.da-step[data-step="cleanup"] [data-da-action="retry"]').click(); + await page.locator('.da-step[data-step="cleanup"] [data-da-action="reconcile"]').click(); await page.waitForFunction(()=>document.querySelector('#da-controls [data-da-action="start"]')?.disabled===false); assert.equal(task.status,'paused');assert.equal(await page.locator('#da-recovery-notice').isVisible(),false); assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')).length,0); @@ -597,3 +597,28 @@ test('main graph exposes cross-page references and drills into original executio assert.ok(state.requests.some(r=>r.path.endsWith('/graph')&&r.query.scope==='receipt:one'&&r.query.view==='full')); assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.deepEqual(state.errors,[]); }); + +test('stopped assessments can acknowledge reviews without restarting and explicitly continue later',async t=>{ + const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='cancelled';task.steps=[{id:'one',title:'待核对样例一',status:'uncertain',conversation_id:'original-one',attempts:2},{id:'two',title:'待核对样例二',status:'cleanup_unconfirmed',conversation_id:'original-two',attempts:1}]; + await page.evaluate(()=>DeepAssessments.refresh());const row=page.locator('.da-list-item[data-id="t0"]'); + assert.equal(await row.getByRole('button',{name:'继续测评',exact:true}).isEnabled(),true);assert.equal(await row.locator('[data-da-action="row-pause"]').isEnabled(),false);assert.equal(await row.locator('[data-da-action="row-archive"]').isEnabled(),false); + await row.getByRole('button',{name:'处理待核对',exact:true}).click();await page.locator('.da-step[data-step="one"]').waitFor(); + page.removeAllListeners('dialog');page.on('dialog',async dialog=>{task.revision++;await dialog.accept();}); + await page.locator('.da-step[data-step="one"] [data-da-action="reconcile"]').click();await page.locator('.da-step[data-step="one"]').waitFor({state:'detached'}); + assert.equal(task.status,'cancelled');assert.equal(task.steps[0].status,'reconciled');assert.equal(await page.locator('.da-step').count(),1); + await page.locator('.da-step[data-step="two"] [data-da-action="reconcile"]').click();await page.waitForFunction(()=>document.querySelectorAll('.da-step').length===0); + assert.equal(task.status,'cancelled');assert.equal(await page.locator('#da-recovery-notice').isVisible(),false);assert.match(await page.locator('#da-body').innerText(),/没有待核对步骤/); + assert.equal(state.requests.filter(r=>r.path.endsWith('/control/start')||r.path.endsWith('/control/continue-stopped')).length,0); + await page.reload();await page.locator('#da-controls [data-da-action="continue-stopped"]').waitFor();assert.equal(await page.locator('.da-step').count(),0); + if(process.env.CSAI_SCREENSHOT_DIR)await page.screenshot({path:path.join(process.env.CSAI_SCREENSHOT_DIR,'stopped-review-cleared.png'),fullPage:true}); + await page.locator('#da-controls [data-da-action="continue-stopped"]').click();await page.waitForFunction(()=>document.querySelector('#da-controls [data-da-action="pause"]')?.disabled===false); + assert.equal(task.status,'running');assert.equal(state.requests.filter(r=>r.path.endsWith('/control/continue-stopped')).length,1);assert.deepEqual(state.errors,[]); +}); + +test('review preflight refuses to acknowledge a newer execution attempt',async t=>{ + const {page,state}=await fixture(t),task=state.tasks.get('t0');task.status='needs_review';task.steps=[{id:'one',title:'原始待核对步骤',status:'uncertain',attempts:1,conversation_id:'original-session'}]; + await page.evaluate(()=>DeepAssessments.refresh());await page.locator('.da-list-item[data-id="t0"] [data-da-action="review"]').click();await page.locator('.da-step[data-step="one"]').waitFor(); + page.removeAllListeners('dialog');page.on('dialog',async dialog=>{task.steps[0].attempts=2;task.revision++;await dialog.accept();}); + await page.locator('[data-da-action="reconcile"]').click();await page.waitForFunction(()=>document.querySelector('#da-detail-notice').textContent.includes('新的执行')); + assert.equal(state.requests.filter(r=>r.method==='POST').length,0);assert.equal(task.steps[0].status,'uncertain');assert.deepEqual(state.errors,[]); +}); diff --git a/web/static/css/deep-assessments.css b/web/static/css/deep-assessments.css index 7b24187c..321728ab 100644 --- a/web/static/css/deep-assessments.css +++ b/web/static/css/deep-assessments.css @@ -361,3 +361,5 @@ body.da-drawer-open { overflow: hidden; } #da-workspace { position:relative; } #da-overview-updates { position:absolute; z-index:4; right:28px; bottom:62px; border-color:var(--accent-color); color:var(--accent-color); box-shadow:0 3px 12px #0002; } #da-overview-updates[hidden] { display:none; } + +.da-review-count { display:block; margin-top:4px; color:#b45309; font-size:11px; } diff --git a/web/static/i18n/en-US.json b/web/static/i18n/en-US.json index dd073990..c45a99cc 100644 --- a/web/static/i18n/en-US.json +++ b/web/static/i18n/en-US.json @@ -5591,7 +5591,9 @@ "retry_scheduled": "Model retry scheduled", "review_gap": "Acceptance gaps remain", "shutdown": "Saving progress and shutting down", - "retry": "Step requeued" + "retry": "Step requeued", + "reconciled": "Review acknowledged", + "reopened": "Stopped assessment continued" }, "native_model": "Model processing", "native_tool": "Processing tool call", @@ -5600,7 +5602,13 @@ "native_idle": "Waiting for next turn", "lastNative": "Last activity" }, - "liveUpdates": "Updates available — view latest" + "liveUpdates": "Updates available — view latest", + "continueStopped": "Continue assessment", + "continueStoppedHint": "Continue the stopped assessment from saved progress; keep completed steps and evidence", + "closedReviewHint": "This assessment has ended. Acknowledgement only updates its history and does not start work. Use Continue assessment to reopen a stopped assessment.", + "reviewSaved": "Review recorded; pending-review list updated", + "conflict": "The assessment changed. Refresh and try again.", + "stepChanged": "This step executed again during review. Check its latest receipts before confirming." }, "assessmentFindingLinks": { "source": "Source assessment", diff --git a/web/static/i18n/ru-RU.json b/web/static/i18n/ru-RU.json index e56aee38..8d93928d 100644 --- a/web/static/i18n/ru-RU.json +++ b/web/static/i18n/ru-RU.json @@ -5604,7 +5604,9 @@ "retry_scheduled": "Повтор модели запланирован", "review_gap": "Есть пробелы приёмки", "shutdown": "Сохранение и завершение", - "retry": "Шаг возвращён в очередь" + "retry": "Шаг возвращён в очередь", + "reconciled": "Проверка подтверждена", + "reopened": "Остановленная оценка продолжена" }, "native_model": "Обработка моделью", "native_tool": "Выполнение инструмента", @@ -5613,7 +5615,13 @@ "native_idle": "Ожидание следующего хода", "lastNative": "Последняя активность" }, - "liveUpdates": "Есть обновления — показать последние" + "liveUpdates": "Есть обновления — показать последние", + "continueStopped": "Продолжить оценку", + "continueStoppedHint": "Продолжить остановленную оценку с сохранённого прогресса, сохранив завершённые шаги и доказательства", + "closedReviewHint": "Оценка завершена. Подтверждение обновляет только историю и не запускает работу. Для остановленной оценки используйте «Продолжить оценку».", + "reviewSaved": "Проверка сохранена; список обновлён", + "conflict": "Состояние оценки изменилось. Обновите страницу и повторите.", + "stepChanged": "Во время проверки шаг выполнялся снова. Проверьте последние результаты перед подтверждением." }, "assessmentFindingLinks": { "source": "Исходная оценка", diff --git a/web/static/i18n/zh-CN.json b/web/static/i18n/zh-CN.json index 9f633c30..708d4909 100644 --- a/web/static/i18n/zh-CN.json +++ b/web/static/i18n/zh-CN.json @@ -5531,7 +5531,9 @@ "retry_scheduled": "稍后重试模型", "review_gap": "验收仍有缺口", "shutdown": "保存进度并关闭", - "retry": "步骤已重新排队" + "retry": "步骤已重新排队", + "reconciled": "已确认核对", + "reopened": "继续已停止的测评" }, "native_model": "模型处理中", "native_tool": "工具处理中", @@ -5544,7 +5546,13 @@ "via_archive": "经归档", "via_details": "经执行记录" }, - "liveUpdates": "有更新,查看最新" + "liveUpdates": "有更新,查看最新", + "continueStopped": "继续测评", + "continueStoppedHint": "从原进度继续已停止的测评,保留已完成步骤和证据", + "closedReviewHint": "测评已结束。核对仅更新历史记录,不会启动测评;已停止的测评可通过“继续测评”恢复。", + "reviewSaved": "已记录核对,待核对列表已更新", + "conflict": "测评状态已更新,请刷新后重试。", + "stepChanged": "此步骤在核对期间发生了新的执行,请重新查看最新回执后确认。" }, "assessmentFindingLinks": { "source": "来源深度测评", diff --git a/web/static/js/assessment-workbench.js b/web/static/js/assessment-workbench.js index 99526822..4b7aa52e 100644 --- a/web/static/js/assessment-workbench.js +++ b/web/static/js/assessment-workbench.js @@ -3,7 +3,7 @@ 'use strict'; const labels={native_model:'模型处理中',native_tool:'工具处理中',native_compacting:'Pi 正在压缩上下文',native_retrying:'Pi 正在重试模型请求',native_idle:'等待下一轮',lastNative:'最近活动',live:'运行态势',planning:'规划中',reviewing:'独立验收中',executing:'执行中',scheduling:'正在调度',draining:'正在停止并收尾',waiting:'等待新进展',retrying:'等待模型恢复',nextWake:'下次唤醒',recent:'最近进展',noRecent:'暂无新进展记录',active:'当前意图',noActive:'当前没有在执行的意图',tools:'工具活动',noTools:'等待模型或下一次工具调用',facts:'事实',findings:'关联漏洞',queue:'意图队列',openStep:'查看此意图',conversation:'执行会话',pause:'暂停此意图',resume:'继续此意图',priority:'意图优先级',urgent:'优先',high:'较高',normal:'普通',low:'较低',guidance:'给此意图补充方向',targetHint:'只发送给此意图;意图暂停时保存,继续后生效。',send:'提交给此意图',lastDirection:'最近补充',manualPause:'此意图已手动暂停',brief:'目标与测评要求',route:'最近规划路线',summary:'当前结论 / 缺口',output:'已有输出',linkedAssets:'关联资产',elapsed:'已持续',min:'分钟',sec:'秒',emptyReview:'无待核对步骤'}; const L=k=>{const path='deepAssessments.workbench.'+k,v=window.t?.(path);return v&&v!==path?v:labels[k]||k;}; - const eventLabels={started:'开始/继续测评',step_started:'意图开始执行',planning:'更新计划',plan_updated:'计划已更新',checkpoint:'已保存进展',step_result:'意图执行结果',settled:'调度已结束',stop_requested:'暂停/停止请求',intent_pause:'暂停此意图',intent_resume:'意图已恢复排队',intent_priority:'优先级已调整',intent_guidance:'收到定向补充',waiting_progress:'等待新进展',waiting_retry:'等待模型恢复',waiting_input:'等待答复',blocked:'执行受阻',guidance:'收到补充方向',retry_scheduled:'稍后重试模型',review_gap:'验收仍有缺口',shutdown:'保存进度并关闭',retry:'步骤已重新排队'}; + const eventLabels={reconciled:'已确认核对',reopened:'继续已停止的测评',started:'开始/继续测评',step_started:'意图开始执行',planning:'更新计划',plan_updated:'计划已更新',checkpoint:'已保存进展',step_result:'意图执行结果',settled:'调度已结束',stop_requested:'暂停/停止请求',intent_pause:'暂停此意图',intent_resume:'意图已恢复排队',intent_priority:'优先级已调整',intent_guidance:'收到定向补充',waiting_progress:'等待新进展',waiting_retry:'等待模型恢复',waiting_input:'等待答复',blocked:'执行受阻',guidance:'收到补充方向',retry_scheduled:'稍后重试模型',review_gap:'验收仍有缺口',shutdown:'保存进度并关闭',retry:'步骤已重新排队'}; const eventLabel=kind=>{const key='deepAssessments.workbench.events.'+kind,v=window.t?.(key);return v&&v!==key?v:eventLabels[kind]||L('recent');}; const esc=v=>String(v??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''})[c]); const button=(action,label,attrs='')=>``; diff --git a/web/static/js/deep-assessments.js b/web/static/js/deep-assessments.js index 6fc095e4..b163000b 100644 --- a/web/static/js/deep-assessments.js +++ b/web/static/js/deep-assessments.js @@ -2,7 +2,7 @@ (function () { 'use strict'; const S = { renderTab:'',renderStatus:'',renderWasBusy:false,renderSignature:'', guidanceDelivered:false,runtime:null,graphView:'summary',relations:[],linksOffset:0,linksMore:false,stepDrafts:Object.create(null), readerExpanded: false, noticeTimer: null, detailVisible: false, detailsOpen: false, listTasks: [], rowBusy: new Set(), extra: null, intentAsset: '', intentStatus: '', intentCounts: {}, routeKey: '', focusStepId: '', focusedStep: null, originFindingId: '', originFinding: null, findings: [], findingOffset: 0, findingMore: false, findingTotal: 0, id: '', task: null, tab: 'graph', graph: null, graphScope: '', graphOffset: 0, graphNode: null, nodeOffset: 0, nodeMore: false, nodeRequest: 0, stepOffset: 0, stepTotal: 0, stepMore: false, page: 0, more: false, busy: false, epoch: 0, timer: null, mounted: false, drawerEpoch: 0, events: [], receipts: [], receiptOffset: 0, receiptMore: false }; - const labels = { liveUpdates:'有更新,查看最新', mainGraph:'主链路',fullGraph:'执行记录',graphRefs:'跨页引用',graphHidden:'已收起执行记录',graphOverflow:'还有跨页关联,可在节点详情中继续查看',upstream:'上游来源',downstream:'下游产出',moreRelations:'继续查看关联',openBranch:'定位关联分支',guidanceDelivered:'已发送给此意图',guidanceQueued:'已保存,将在此意图继续时生效', review:'处理待核对', reviewTitle:'未派发新步骤,有工具结果待确认', reviewHint:'点击“开始 / 继续”会先核对已保存的执行回执,已确认结束的步骤可直接续跑;仍有结果不明的调用时,保持停止并提示核对。', reviewStepHint:'确认只解除本步骤的待核对状态,不会自动执行;原有进度和证据保留。', reviewAcknowledge:'确认已核对', reviewDone:'没有待核对步骤。当前执行状态见页面顶部。', viewReceipts:'查看回执', notRunning:'当前未在执行,无需暂停', autoResumeState:'服务重启后自动续跑', enabled:'已开启', disabled:'已关闭', autoResumeHint:'打开页面不会启动任务;自动续跑只针对重启前的执行,草稿、手动暂停和待核对任务不会自动开始。', readerExpand:'展开阅读', readerBack:'返回图', resizeDetails:'调整节点详情宽度', graphHelp:'图例与说明', backToList:'返回测评列表', details:'详情', actions:'操作', archive:'归档', restore:'恢复到列表', currentTasks:'当前任务', archivedTasks:'已归档', archiveFilter:'归档状态', restoreHint:'恢复只回到列表,不会自动执行。', archiveHint:'归档保留进度与证据;执行中的任务请先暂停。', showDetails:'显示节点详情', hideDetails:'收起节点详情', scopeOptional: "补充限制与排除项(选填)", criteriaOptional: "验收条件(选填)", scopeHint: "仅补充目标中未说明的限制;留空沿用目标。", scopeExample: "例如:排除支付接口;不修改生产数据;不做压力测试。", criteriaHint: "说明什么结果算完成;留空沿用目标。", criteriaExample: "例如:报告列明已测范围、未测部分及原因;确认的漏洞附复现步骤和原始证据。", assets: '资产图', facts: '事实', priority: '优先级', linkedAssets: '目标资产', intentSources: '来源节点', findings: '关联漏洞', noFindings: '暂未登记漏洞。', openFinding: '在漏洞管理查看', allFindings: '在漏洞管理查看本次测评', reproduction: '复现步骤', findingEvidence: '复现证据', sourceStep: '来源步骤', allSteps: '显示全部步骤与回执', sourceFinding: '关联漏洞', graph: '探索图', continuous: '持续执行', mode: '运行模式', elapsed: '已运行', graphHint: '摘要用于续接;原始观察和执行回执可随时展开。', graphVisible: '当前页节点', graphFolded: '已折叠节点', graphHome: '全图概览', graphExpand: '展开关联节点', graphLayout: '整理布局', graphFit: '适应画布', graphSelect: '点击节点查看原始内容与来源。', graphMore: '继续读取原文', status: '状态', updatedAt: '更新时间', loading: '正在读取测评…', contextUsage:'上下文 / 窗口', toolDefinitions:'工具定义', title: '深度测评', subtitle: '围绕一个目标持续探索,保存证据与进度,跨会话继续执行。', create: '新建测评', refresh: '刷新', search: '搜索测评名称', all: '全部状态', empty: '暂无测评,先创建一个目标。', select: '选择测评,查看探索进度与证据。', previous: '上一页', next: '下一页', name: '测评名称', objective: '目标', scope: '补充限制与排除项', criteria: '验收条件', model: '模型渠道', project: '关联项目', role: '角色', default: '系统默认', none: '不关联', tokens: '累计 Token', rounds: '规划轮次', concurrency: '并行步骤', autoResume: '服务重启后自动恢复结果明确的步骤', save: '保存草稿', close: '关闭', start: '开始 / 继续', pause: '暂停', cancel: '停止', delete: '删除', report: '下载报告', overview: '概览', plan: '意图队列', evidence: '证据回执', activity: '运行记录', quality: '上下文与用量', guidance: '补充线索或调整方向', send: '提交方向', answer: '答复并继续', retry: '恢复此步骤', conversation: '查看执行会话', unknown: '请先核对回执,确认上次操作结果及执行资源状态。', reconcile: '我已核对调用结果并确认执行资源已停止,解除本步骤的待核对状态。任务仍需手动开始。', confirmStop: '停止后将保留已有结果,结束本次测评。', confirmDelete: '删除本条测评?关联执行会话仍保留。', strategy: '最近规划路线', summary: '当前结论 / 缺口', question: '待补充信息', dependencies: '前置步骤', segments: '执行分段', evidenceIDs: '证据引用', noSteps: '开始后由规划器逐步生成探索方向。', noRecords: '暂无记录', calls: '工具调用', compactions: '上下文压缩', activeTools: '当前可见工具', session: '会话', tokenNote: '累计用量包含 Pi 压缩,不作为任务自动结束条件。', recoveryNote: '结果不明的调用会暂停等待核对,已完成步骤不会自动重做。', saved: '已保存', updated: '已更新', retryNote: '恢复会保留原 Pi 会话及历史证据。' }; + const labels = { continueStopped:'继续测评',continueStoppedHint:'从原进度继续已停止的测评,保留已完成步骤和证据',closedReviewHint:'测评已结束。核对仅更新历史记录,不会启动测评;已停止的测评可通过“继续测评”恢复。',reviewSaved:'已记录核对,待核对列表已更新',conflict:'测评状态已更新,请刷新后重试。',stepChanged:'此步骤在核对期间发生了新的执行,请重新查看最新回执后确认。', liveUpdates:'有更新,查看最新', mainGraph:'主链路',fullGraph:'执行记录',graphRefs:'跨页引用',graphHidden:'已收起执行记录',graphOverflow:'还有跨页关联,可在节点详情中继续查看',upstream:'上游来源',downstream:'下游产出',moreRelations:'继续查看关联',openBranch:'定位关联分支',guidanceDelivered:'已发送给此意图',guidanceQueued:'已保存,将在此意图继续时生效', review:'处理待核对', reviewTitle:'未派发新步骤,有工具结果待确认', reviewHint:'点击“开始 / 继续”会先核对已保存的执行回执,已确认结束的步骤可直接续跑;仍有结果不明的调用时,保持停止并提示核对。', reviewStepHint:'确认只解除本步骤的待核对状态,不会自动执行;原有进度和证据保留。', reviewAcknowledge:'确认已核对', reviewDone:'没有待核对步骤。当前执行状态见页面顶部。', viewReceipts:'查看回执', notRunning:'当前未在执行,无需暂停', autoResumeState:'服务重启后自动续跑', enabled:'已开启', disabled:'已关闭', autoResumeHint:'打开页面不会启动任务;自动续跑只针对重启前的执行,草稿、手动暂停和待核对任务不会自动开始。', readerExpand:'展开阅读', readerBack:'返回图', resizeDetails:'调整节点详情宽度', graphHelp:'图例与说明', backToList:'返回测评列表', details:'详情', actions:'操作', archive:'归档', restore:'恢复到列表', currentTasks:'当前任务', archivedTasks:'已归档', archiveFilter:'归档状态', restoreHint:'恢复只回到列表,不会自动执行。', archiveHint:'归档保留进度与证据;执行中的任务请先暂停。', showDetails:'显示节点详情', hideDetails:'收起节点详情', scopeOptional: "补充限制与排除项(选填)", criteriaOptional: "验收条件(选填)", scopeHint: "仅补充目标中未说明的限制;留空沿用目标。", scopeExample: "例如:排除支付接口;不修改生产数据;不做压力测试。", criteriaHint: "说明什么结果算完成;留空沿用目标。", criteriaExample: "例如:报告列明已测范围、未测部分及原因;确认的漏洞附复现步骤和原始证据。", assets: '资产图', facts: '事实', priority: '优先级', linkedAssets: '目标资产', intentSources: '来源节点', findings: '关联漏洞', noFindings: '暂未登记漏洞。', openFinding: '在漏洞管理查看', allFindings: '在漏洞管理查看本次测评', reproduction: '复现步骤', findingEvidence: '复现证据', sourceStep: '来源步骤', allSteps: '显示全部步骤与回执', sourceFinding: '关联漏洞', graph: '探索图', continuous: '持续执行', mode: '运行模式', elapsed: '已运行', graphHint: '摘要用于续接;原始观察和执行回执可随时展开。', graphVisible: '当前页节点', graphFolded: '已折叠节点', graphHome: '全图概览', graphExpand: '展开关联节点', graphLayout: '整理布局', graphFit: '适应画布', graphSelect: '点击节点查看原始内容与来源。', graphMore: '继续读取原文', status: '状态', updatedAt: '更新时间', loading: '正在读取测评…', contextUsage:'上下文 / 窗口', toolDefinitions:'工具定义', title: '深度测评', subtitle: '围绕一个目标持续探索,保存证据与进度,跨会话继续执行。', create: '新建测评', refresh: '刷新', search: '搜索测评名称', all: '全部状态', empty: '暂无测评,先创建一个目标。', select: '选择测评,查看探索进度与证据。', previous: '上一页', next: '下一页', name: '测评名称', objective: '目标', scope: '补充限制与排除项', criteria: '验收条件', model: '模型渠道', project: '关联项目', role: '角色', default: '系统默认', none: '不关联', tokens: '累计 Token', rounds: '规划轮次', concurrency: '并行步骤', autoResume: '服务重启后自动恢复结果明确的步骤', save: '保存草稿', close: '关闭', start: '开始 / 继续', pause: '暂停', cancel: '停止', delete: '删除', report: '下载报告', overview: '概览', plan: '意图队列', evidence: '证据回执', activity: '运行记录', quality: '上下文与用量', guidance: '补充线索或调整方向', send: '提交方向', answer: '答复并继续', retry: '恢复此步骤', conversation: '查看执行会话', unknown: '请先核对回执,确认上次操作结果及执行资源状态。', reconcile: '我已核对调用结果并确认执行资源已停止,解除本步骤的待核对状态。任务仍需手动开始。', confirmStop: '停止后将保留已有结果,结束本次测评。', confirmDelete: '删除本条测评?关联执行会话仍保留。', strategy: '最近规划路线', summary: '当前结论 / 缺口', question: '待补充信息', dependencies: '前置步骤', segments: '执行分段', evidenceIDs: '证据引用', noSteps: '开始后由规划器逐步生成探索方向。', noRecords: '暂无记录', calls: '工具调用', compactions: '上下文压缩', activeTools: '当前可见工具', session: '会话', tokenNote: '累计用量包含 Pi 压缩,不作为任务自动结束条件。', recoveryNote: '结果不明的调用会暂停等待核对,已完成步骤不会自动重做。', saved: '已保存', updated: '已更新', retryNote: '恢复会保留原 Pi 会话及历史证据。' }; const states = { archived: '已归档', draft: '草稿', running: '执行中', pending: '待执行', completed: '已完成', blocked: '受阻', failed: '失败', paused: '已暂停', pausing: '暂停中', cancelling: '停止中', cancelled: '已停止', recovering: '待恢复', waiting_retry: '等待模型恢复', waiting_input: '待答复', needs_review: '待核对', uncertain: '结果不明', waiting_progress: '等待新进展', interrupted: '已中断', cleanup_unconfirmed: '待确认资源停止', retired: '已撤下', reconciled: '已核对', yielded: '分段完成' }; const tr = (key, fallback) => { const v = typeof window.t === 'function' ? window.t('deepAssessments.' + key) : ''; return v && v !== 'deepAssessments.' + key ? v : fallback; }; const L = key => tr(key, labels[key] || key); @@ -160,7 +160,7 @@ async function api(path, options = {}) { const fetcher = typeof window.apiFetch === 'function' ? window.apiFetch : fetch; const response = await fetcher('/api/deep-assessments' + path, { ...options, headers: { 'Content-Type': 'application/json', ...(options.headers || {}) } }); - if (!response.ok) { let value; try { value = await response.json(); } catch {} throw new Error(value?.error || 'HTTP ' + response.status); } + if (!response.ok) { let value; try { value = await response.json(); } catch {} throw new Error(value?.code==='task_changed'||value?.error==='task changed; refresh and retry'?L('conflict'):value?.error || 'HTTP ' + response.status); } return response; } async function json(path, options) { return (await api(path, options)).json(); } @@ -246,18 +246,19 @@ $('da-filter').addEventListener('change', () => { S.page = 0; writeListRoute(); void refresh(); }); } const canExecute = () => typeof window.hasPermission !== 'function' || window.hasPermission('agent:execute'); - const needsReview = task => ['needs_review','uncertain','cleanup_unconfirmed'].includes(task.status)||(task.steps||[]).some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status)); + const needsReview = task => ['needs_review','uncertain','cleanup_unconfirmed'].includes(task.status)||Number(task.review_count)>0||(task.steps||[]).some(s=>['uncertain','cleanup_unconfirmed'].includes(s.status)); const canStart = task => !task.archived && !terminal(task) && !active(task) && !task.question && task.status!=='waiting_input' && canExecute(); + const canContinueStopped=task=>task.status==='cancelled'&&!task.archived&&canExecute(); const canPause = task => !task.archived && ['running','recovering','waiting_retry','waiting_progress'].includes(task.status); const canArchive = task => !needsReview(task) && !task.archived && !active(task) && !['recovering','needs_review','uncertain','cleanup_unconfirmed'].includes(task.status); function renderList() { const list=$('da-list'),scroll=list.scrollTop; list.innerHTML=S.listTasks.map(task=>{ const busy=S.rowBusy.has(task.id),id='data-id="'+esc(task.id)+'"'; - const controls=(can('write')?button('row-start',L('start'),id+(!canStart(task)||busy?' disabled':''))+button('row-pause',L('pause'),id+(!canPause(task)||busy?' disabled title="'+esc(L('notRunning'))+'"':'')):'') + const controls=(can('write')?(task.status==='cancelled'?button('row-continue-stopped',L('continueStopped'),id+(!canContinueStopped(task)||busy?' disabled':'')+' title="'+esc(L('continueStoppedHint'))+'"'):button('row-start',L('start'),id+(!canStart(task)||busy?' disabled':'')))+button('row-pause',L('pause'),id+(!canPause(task)||busy?' disabled title="'+esc(L('notRunning'))+'"':'')):'') +button('details',L('details'),id) +(can('write') ? button(task.archived?'row-restore':'row-archive',L(task.archived?'restore':'archive'),id+((!task.archived&&!canArchive(task))||busy?' disabled':'')+' title="'+esc(L(task.archived?'restoreHint':needsReview(task)?'reviewHint':'archiveHint'))+'"') : ''); - return `
${needsReview(task)?``:badge(task.status)}${task.archived?badge('archived'):''}${esc(L('rounds'))}${task.rounds||0}${esc(L('tokens'))}${Number(task.tokens_used||0).toLocaleString()}
${controls}
`; + return `
${needsReview(task)?``:badge(task.status)}${task.archived?badge('archived'):''}${esc(L('rounds'))}${task.rounds||0}${esc(L('tokens'))}${Number(task.tokens_used||0).toLocaleString()}
${controls}
`; }).join('')||`

${esc(L('empty'))}

`; list.scrollTop=scroll;$('da-page').textContent=String(S.page+1); $('da-list-view').querySelector('[data-da-action="previous"]').disabled=S.page===0; @@ -282,9 +283,9 @@ if (!task) { $('da-overview-updates').hidden=true;$('da-recovery-notice').hidden=true; $('da-task-meta').textContent=''; $('da-title').textContent = L('title'); $('da-controls').innerHTML = ''; $('da-tabs').innerHTML = ''; $('da-body').textContent = L(S.id ? 'loading' : 'select'); $('da-guidance-form').hidden = true; $('da-guidance-panel').hidden = true; return; } $('da-title').innerHTML = `

${esc(task.name)} ${badge(task.status)} ${task.archived?badge('archived'):''}

`; $('da-task-meta').textContent=[L('model')+' '+(task.model||L('default')),L('role')+' '+(task.role||L('default')),L('rounds')+' '+(task.rounds||0),L('tokens')+' '+Number(task.tokens_used||0).toLocaleString()].join(' · '); - $('da-controls').innerHTML = `${can('write') && !terminal(task) && !task.archived ? button('start',L('start'),!canStart(task)?'disabled':'')+button('pause',L('pause'),!canPause(task)?'disabled':'')+button('cancel', L('cancel')) : ''}${can('write') ? button(task.archived?'restore':'archive',L(task.archived?'restore':'archive'),!task.archived && !canArchive(task)?'disabled title="'+esc(L(needsReview(task)?'reviewHint':'archiveHint'))+'"':'') : ''}${button('report', L('report'))}${can('delete') && !active(task) ? button('delete', L('delete')) : ''}`; + $('da-controls').innerHTML = `${can('write')&&task.status==='cancelled'?button('continue-stopped',L('continueStopped'),!canContinueStopped(task)?'disabled':''):''}${can('write') && !terminal(task) && !task.archived ? button('start',L('start'),!canStart(task)?'disabled':'')+button('pause',L('pause'),!canPause(task)?'disabled':'')+button('cancel', L('cancel')) : ''}${can('write') ? button(task.archived?'restore':'archive',L(task.archived?'restore':'archive'),!task.archived && !canArchive(task)?'disabled title="'+esc(L(needsReview(task)?'reviewHint':'archiveHint'))+'"':'') : ''}${button('report', L('report'))}${can('delete') && !active(task) ? button('delete', L('delete')) : ''}`; const recovery=$('da-recovery-notice');recovery.hidden=!needsReview(task); - recovery.innerHTML=needsReview(task)?`
${esc(L('reviewTitle'))}

${esc(L('reviewHint'))}

${button('review',L('review'))}`:''; + recovery.innerHTML=needsReview(task)?`
${esc(L('reviewTitle'))}

${esc(L(terminal(task)?'closedReviewHint':'reviewHint'))}

${button('review',L('review'))}`:''; $('da-tabs').innerHTML = ['overview', ...(window.AssessmentExplorationViews?.canAssets() ? ['assets'] : []), 'graph', 'plan', 'facts', ...(canFindings() ? ['findings'] : []), 'evidence', 'activity', 'quality'].map(tab => ``).join(''); const body = $('da-body'), scroller = $('da-workspace').querySelector('.da-detail-scroll'), scroll = scroller.scrollTop; const opened = new Set([...body.querySelectorAll('details[open]')].map(el => el.dataset.step)); @@ -302,8 +303,8 @@ } else if (S.tab === 'assets' || S.tab === 'facts') { window.AssessmentExplorationViews?.render(body, S.tab, S.extra, can('write') && !task.archived); } else if (S.tab === 'plan') { - body.innerHTML = sourceBanner() + (S.focusedStep ? [S.focusedStep] : task.steps || []).map(step => `
${badge(step.status)} ${esc(step.title)}${esc(step.id)}${window.AssessmentWorkbench?.controls(step,task,can('write'),S.stepDrafts[step.id])||''}
${esc(step.instruction)}

${esc(L('priority'))}: ${step.priority || 100} · ${esc(L('linkedAssets'))}: ${(step.asset_ids || []).map(id=>window.AssessmentExplorationViews?.canAssets()?button('intent-asset',id,`data-asset="${esc(id)}"`):esc(id)).join(' ') || '—'}

${esc(L('intentSources'))}: ${esc((step.source_ids || []).join(', ') || '—')}

${esc(L('dependencies'))}: ${esc((step.depends_on || []).join(', ') || '—')} · ${esc(L('segments'))}: ${step.attempts || 0}

${esc(step.summary)}

${esc(L('evidenceIDs'))}: ${esc((step.evidence || []).join(', ') || '—')}

${['uncertain','cleanup_unconfirmed'].includes(step.status)?`

${esc(L('reviewStepHint'))}

`:''}
${button('fact-proof',L('viewReceipts'),`data-step="${esc(step.id)}"`)}${step.conversation_id ? button('conversation', L('conversation'), `data-conversation="${esc(step.conversation_id)}"`) : ''}${!task.archived && !active(task) && can('write') && ['failed', 'blocked', 'interrupted', 'uncertain', 'cleanup_unconfirmed'].includes(step.status) ? button('retry', L(['uncertain','cleanup_unconfirmed'].includes(step.status)?'reviewAcknowledge':'retry'), `data-step="${esc(step.id)}"`) : ''}
`).join('') || `

${esc(L(S.intentStatus==='needs_review'?'reviewDone':'noSteps'))}

`; - if (!S.focusStepId) body.insertAdjacentHTML('afterbegin', `
${S.intentAsset?button('clear-intent-asset',L('allSteps')):''}
`); + body.innerHTML = sourceBanner() + (S.focusedStep ? [S.focusedStep] : task.steps || []).map(step => `
${badge(step.status)} ${esc(step.title)}${esc(step.id)}${window.AssessmentWorkbench?.controls(step,task,can('write'),S.stepDrafts[step.id])||''}
${esc(step.instruction)}

${esc(L('priority'))}: ${step.priority || 100} · ${esc(L('linkedAssets'))}: ${(step.asset_ids || []).map(id=>window.AssessmentExplorationViews?.canAssets()?button('intent-asset',id,`data-asset="${esc(id)}"`):esc(id)).join(' ') || '—'}

${esc(L('intentSources'))}: ${esc((step.source_ids || []).join(', ') || '—')}

${esc(L('dependencies'))}: ${esc((step.depends_on || []).join(', ') || '—')} · ${esc(L('segments'))}: ${step.attempts || 0}

${esc(step.summary)}

${esc(L('evidenceIDs'))}: ${esc((step.evidence || []).join(', ') || '—')}

${['uncertain','cleanup_unconfirmed'].includes(step.status)?`

${esc(L('reviewStepHint'))}

`:''}
${button('fact-proof',L('viewReceipts'),`data-step="${esc(step.id)}"`)}${step.conversation_id ? button('conversation', L('conversation'), `data-conversation="${esc(step.conversation_id)}"`) : ''}${!task.archived && !active(task) && can('write') && (['uncertain','cleanup_unconfirmed'].includes(step.status)||!terminal(task)&&['failed','blocked','interrupted'].includes(step.status)) ? button(['uncertain','cleanup_unconfirmed'].includes(step.status)?'reconcile':'retry', L(['uncertain','cleanup_unconfirmed'].includes(step.status)?'reviewAcknowledge':'retry'), `data-step="${esc(step.id)}"`) : ''}
`).join('') || `

${esc(L(S.intentStatus==='needs_review'?'reviewDone':'noSteps'))}

`; + if (!S.focusStepId) body.insertAdjacentHTML('afterbegin', `
${S.intentAsset?button('clear-intent-asset',L('allSteps')):''}
`); if (!S.focusStepId) body.innerHTML += `
${S.stepOffset ? button('step-previous', L('previous')) : ''}${(task.steps || []).length} / ${S.stepTotal}${S.stepMore ? button('step-next', L('next')) : ''}
`; } else if (S.tab === 'findings') { body.innerHTML = `
${button('all-findings', L('allFindings'))}${S.findingTotal}
` + (S.findings.map(v => `

${esc(v.title)}

${esc(v.severity)} · ${esc(v.status)}

${esc(L('sourceStep'))}:${esc(v.assessment_step_title || v.assessment_step_id)}

${button('open-finding', L('openFinding'), `data-vulnerability="${esc(v.id)}"`)}${button('finding-evidence', L('findingEvidence'), `data-vulnerability="${esc(v.id)}" data-step="${esc(v.assessment_step_id)}"`)}
`).join('') || `

${esc(L('noFindings'))}

`) + `
${S.findingOffset ? button('previous-findings', L('previous')) : ''}${S.findingMore ? button('next-findings', L('next')) : ''}
`; @@ -389,13 +390,28 @@ renderGraphNode(); } catch (error) { if (request === S.nodeRequest && S.id === task) notice(error.message, true); } } - async function mutate(action, values = {}) { + async function mutate(action, values = {}, expectedStep=null) { if (S.busy || !S.task || !can('write')) return false; S.busy = true; ++S.epoch; renderTask(); try { - const current=action.startsWith('intent-')?await json('/'+encodeURIComponent(S.id)+'?step_limit=1'):null; - const data = await json('/' + encodeURIComponent(S.id) + '/control/' + action + '?runtime=true&step_limit=50&step_offset=' + S.stepOffset, { method: 'POST', body: JSON.stringify({ revision: current?.task.revision??S.task.revision, ...values }) }); - S.guidanceDelivered=!!data.guidance_delivered;S.task = data.task; S.stepTotal = data.step_total ?? data.task.steps?.length ?? 0; S.stepMore = !!data.step_has_more; notice(data.start_error || L('updated'), !!data.start_error); return !data.start_error; + let revision=S.task.revision; + if(expectedStep){ + const fresh=await json('/'+encodeURIComponent(S.id)+'/steps/'+encodeURIComponent(values.step_id)); + if((fresh.step.attempts||0)!==expectedStep.attempts||(fresh.step.conversation_id||'')!==expectedStep.conversation)throw new Error(L('stepChanged')); + revision=fresh.revision??revision; + if(action==='reconcile'&&!['uncertain','cleanup_unconfirmed'].includes(fresh.step.status)){ + if(['running','pausing'].includes(fresh.step.status))throw new Error(L('stepChanged')); + notice(L('reviewSaved'));return true; + } + }else if(action.startsWith('intent-')||action==='continue-stopped'){revision=(await json('/'+encodeURIComponent(S.id)+'?step_limit=1')).task.revision;} + const query=new URLSearchParams({step_limit:50,step_offset:S.stepOffset}); + if(S.tab==='plan'){query.set('step_order','queue');query.set('step_status',S.intentStatus);query.set('step_asset',S.intentAsset);} + const data = await json('/' + encodeURIComponent(S.id) + '/control/' + action + '?'+query, { method: 'POST', body: JSON.stringify({ revision, ...values }) }); + if(data.step&&S.focusStepId===data.step.id)S.focusedStep=data.step; + S.intentCounts=data.intent_counts||S.intentCounts; + if(action==='reconcile'&&S.tab==='plan'&&S.intentStatus==='needs_review'){S.focusStepId='';S.focusedStep=null;writeRoute();} + + S.guidanceDelivered=!!data.guidance_delivered;S.task = data.task; S.stepTotal = data.step_total ?? data.task.steps?.length ?? 0; S.stepMore = !!data.step_has_more; notice(data.start_error || L(action==='reconcile'?'reviewSaved':'updated'), !!data.start_error);if(action==='continue-stopped'&&data.task.status==='waiting_input')$('da-guidance-panel').open=true; return !data.start_error; } catch (error) { notice(error.message, true); return false; } finally { S.busy = false; renderTask(); void refresh(); } } @@ -462,11 +478,11 @@ if (name === 'graph-next' || name === 'graph-previous') { S.graphOffset = Math.max(0, S.graphOffset + (name === 'graph-next' ? 80 : -80)); return await refresh(); } if (name === 'graph-more' && S.graphNode) return await selectGraphNode(S.graphNode.id, true); if (name.startsWith('row-')) return await rowControl(data.id,name.slice(4)); - if (['start','pause','archive','restore'].includes(name)) return await mutate(name); + if (['start','pause','archive','restore','continue-stopped'].includes(name)) return await mutate(name); if (name === 'cancel') { if (window.confirm(L('confirmStop'))) return await mutate('cancel'); return; } if (name === 'conversation') { closeDrawer('da-form-drawer'); hideWorkspace(); if (typeof window.switchPage === 'function') window.switchPage('chat'); if (typeof window.loadConversation === 'function') await window.loadConversation(data.conversation); return; } - if (name === 'retry') { const step = (S.focusedStep?.id === data.step ? S.focusedStep : S.task.steps.find(s => s.id === data.step)); const uncertain = ['uncertain', 'cleanup_unconfirmed'].includes(step?.status); if (uncertain && !window.confirm(L('unknown') + '\n\n' + L('reconcile'))) return; return await mutate('retry', { step_id: data.step, reconciled: uncertain, cleanup_confirmed: uncertain }); } + if (name === 'retry'||name==='reconcile') { const step = (S.focusedStep?.id === data.step ? S.focusedStep : S.task.steps.find(s => s.id === data.step));if(!step)return; const uncertain = ['uncertain', 'cleanup_unconfirmed'].includes(step.status);const expected={attempts:step.attempts||0,conversation:step.conversation_id||''}; if (uncertain && !window.confirm(L('unknown') + '\n\n' + (terminal(S.task)?L('closedReviewHint'):L('reconcile')))) return; return await mutate(uncertain?'reconcile':'retry', { step_id: data.step, reconciled: uncertain, cleanup_confirmed: uncertain },expected); } if (name === 'report') { const response = await api('/' + encodeURIComponent(S.id) + '/report'); const url = URL.createObjectURL(await response.blob()); const a = document.createElement('a'); a.href = url; a.download = 'assessment-' + S.id + '.md'; a.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); return; } if (name === 'delete' && can('delete') && window.confirm(L('confirmDelete'))) { S.busy = true; ++S.epoch; try { await api('/' + encodeURIComponent(S.id), { method: 'DELETE' }); S.id = ''; S.task = null;writeListRoute(true);hideWorkspace(); } finally { S.busy = false; } return await refresh(); } if (name === 'more-receipts' || name === 'previous-receipts') { S.receiptOffset = Math.max(0, S.receiptOffset + (name === 'more-receipts' ? 50 : -50)); return await refresh(); } diff --git a/web/templates/index.html b/web/templates/index.html index 129793cd..3bdc41bb 100644 --- a/web/templates/index.html +++ b/web/templates/index.html @@ -50,7 +50,7 @@ - + @@ -7141,11 +7141,11 @@ - + - +