From 6e0a6854fb8d57b9cddc9b0cb2ec12fc54615a5c Mon Sep 17 00:00:00 2001 From: Sycun <165354365+Sycun@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:22:47 +0800 Subject: [PATCH] fix(chat): preserve draft replies when plans are unfinished --- internal/agentfinalizer/decision.go | 12 +++ internal/handler/batch_queue_executor.go | 2 +- internal/handler/finalization_helpers.go | 33 ++++++- .../finalization_unfinished_plan_test.go | 87 +++++++++++++++++++ internal/handler/multi_agent.go | 2 +- internal/handler/single_agent.go | 2 +- internal/multiagent/pi_integration_test.go | 43 ++++++++- internal/multiagent/pi_plan_tools.go | 29 ++++--- internal/multiagent/pi_runner.go | 3 +- internal/multiagent/runtime_types.go | 7 ++ 10 files changed, 202 insertions(+), 18 deletions(-) create mode 100644 internal/handler/finalization_unfinished_plan_test.go diff --git a/internal/agentfinalizer/decision.go b/internal/agentfinalizer/decision.go index b420fd2d..398be461 100644 --- a/internal/agentfinalizer/decision.go +++ b/internal/agentfinalizer/decision.go @@ -44,6 +44,8 @@ type Decision struct { ConversationID string `json:"conversationId,omitempty"` AssistantMessageID string `json:"messageId,omitempty"` CandidateResponseLen int `json:"candidateResponseLen,omitempty"` + + UnfinishedPlanSteps []multiagent.PlanStep `json:"unfinishedPlanSteps,omitempty"` } type Input struct { @@ -75,6 +77,9 @@ func FromRunResult(db *database.DB, result *multiagent.RunResult, in Input) Deci } d := Decide(db, in) if result != nil { + if d.CompletionReason == multiagent.ReasonUnfinishedPlan { + d.UnfinishedPlanSteps = result.UnfinishedPlanSteps + } result.Finalized = d.Finalized result.Status = d.Status result.CompletionReason = d.CompletionReason @@ -122,6 +127,10 @@ func Decide(db *database.DB, in Input) Decision { if d.CompletionReason == ReasonVerified { d.CompletionReason = status } + if d.CompletionReason == multiagent.ReasonUnfinishedPlan && isEmptyCandidate(text) { + d.FinalText = "" + d.CandidateResponseLen = 0 + } d.MissingChecks = append(d.MissingChecks, "agent run status is "+status) return d } @@ -183,6 +192,9 @@ func ResponsePayload(d Decision, extra map[string]interface{}) map[string]interf if d.AgentMode != "" { out["agentMode"] = d.AgentMode } + if len(d.UnfinishedPlanSteps) > 0 { + out["unfinishedPlanSteps"] = d.UnfinishedPlanSteps + } for k, v := range extra { out[k] = v } diff --git a/internal/handler/batch_queue_executor.go b/internal/handler/batch_queue_executor.go index b017b6d4..9dd0f49b 100644 --- a/internal/handler/batch_queue_executor.go +++ b/internal/handler/batch_queue_executor.go @@ -382,7 +382,7 @@ func (h *AgentHandler) executeOneBatchSubTask(queueID string, queue *BatchTaskQu if !decision.Finalizable { resText = finalizationBlockedMessage(decision) finishStatus = decision.Status - sendEvent("finalization_check", resText, decision) + sendEvent("finalization_check", finalizationCheckMessage(decision), decision) } sendEvent("response", resText, finalizationResponsePayload(decision, map[string]interface{}{ "conversationId": conversationID, diff --git a/internal/handler/finalization_helpers.go b/internal/handler/finalization_helpers.go index 9ce8450d..ddd92de3 100644 --- a/internal/handler/finalization_helpers.go +++ b/internal/handler/finalization_helpers.go @@ -156,9 +156,36 @@ func finalizationCheckMessage(d agentfinalizer.Decision) string { if d.Finalizable { return "已交付本轮回复。" } + if d.CompletionReason == multiagent.ReasonUnfinishedPlan { + return unfinishedPlanNotice(d.UnfinishedPlanSteps) + } return finalizationBlockedMessage(d) } +func unfinishedPlanNotice(steps []multiagent.PlanStep) string { + if len(steps) == 0 { + return "本轮任务未完成,计划中仍有待执行或进行中的步骤。" + } + var notice strings.Builder + fmt.Fprintf(¬ice, "本轮任务未完成,还有 %d 个计划步骤未结束。\n", len(steps)) + escapeTitle := strings.NewReplacer( + "\\", "\\\\", "`", "\\`", "*", "\\*", "_", "\\_", "~", "\\~", + "[", "\\[", "]", "\\]", "<", "\\<", ">", "\\>", "&", "\\&", + ) + for _, step := range steps { + status := "待执行" + if step.Status == "in_progress" { + status = "进行中" + } + title := strings.Join(strings.Fields(step.Subject), " ") + if title == "" { + title = "步骤 #" + step.ID + } + fmt.Fprintf(¬ice, "\n- %s · %s", status, escapeTitle.Replace(title)) + } + return notice.String() +} + func finalizationBlockedMessage(d agentfinalizer.Decision) string { if d.CompletionReason == "workflow_rejected" && strings.TrimSpace(d.FinalText) != "" { return d.FinalText @@ -168,7 +195,11 @@ func finalizationBlockedMessage(d agentfinalizer.Decision) string { case agentfinalizer.ReasonPendingToolsCancelled: notice = "收尾时取消了仍在运行的工具,任务未完成。" case multiagent.ReasonUnfinishedPlan: - notice = "本轮计划仍有标记为「待执行」或「进行中」的步骤,最终回复暂未交付。请核对计划中的步骤状态。" + notice = unfinishedPlanNotice(d.UnfinishedPlanSteps) + if text := strings.TrimSpace(d.FinalText); text != "" { + return notice + "\n\n**本轮已生成的内容(阶段性结果)**\n\n" + text + } + return notice case multiagent.ReasonModelOutputTruncated: notice = "模型输出达到长度上限,本轮回复未完成。" default: diff --git a/internal/handler/finalization_unfinished_plan_test.go b/internal/handler/finalization_unfinished_plan_test.go new file mode 100644 index 00000000..e7f591d9 --- /dev/null +++ b/internal/handler/finalization_unfinished_plan_test.go @@ -0,0 +1,87 @@ +package handler + +import ( + "path/filepath" + "strings" + "testing" + + "cyberstrike-ai/internal/agentfinalizer" + "cyberstrike-ai/internal/database" + "cyberstrike-ai/internal/multiagent" + + "go.uber.org/zap" +) + +func TestUnfinishedPlanPreservesDraftAndStepDetails(t *testing.T) { + db, err := database.NewDB(filepath.Join(t.TempDir(), "chat.db"), zap.NewNop()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Close() }) + conversation, err := db.CreateConversation("Draft notes", database.ConversationCreateMeta{}) + if err != nil { + t.Fatal(err) + } + message, err := db.AddMessage(conversation.ID, "assistant", "处理中...", nil) + if err != nil { + t.Fatal(err) + } + const draft = "这是已整理的 **笔记初稿**。" + result := &multiagent.RunResult{ + Response: draft, + RuntimeStatus: agentfinalizer.StatusBlocked, + RuntimeCompletionReason: multiagent.ReasonUnfinishedPlan, + UnfinishedPlanSteps: []multiagent.PlanStep{ + {ID: "1", Subject: "复核数字", Status: "in_progress"}, + {ID: "2", Subject: "校对[标题]\n和摘要", Status: "pending"}, + }, + } + h := &AgentHandler{db: db} + decision := h.finalizeAgentRunForDelivery(conversation.ID, message.ID, "single", result, nil, "") + if decision.Status != agentfinalizer.StatusBlocked || decision.Finalized || decision.Finalizable || decision.EvidenceVerified { + t.Fatalf("a draft must not be promoted to a completed result: %+v", decision) + } + reply := finalizationBlockedMessage(decision) + for _, want := range []string{"本轮任务未完成", "进行中 · 复核数字", "待执行 · 校对\\[标题\\] 和摘要", "阶段性结果", draft} { + if !strings.Contains(reply, want) { + t.Fatalf("reply is missing %q: %q", want, reply) + } + } + if strings.Contains(reply, "agent run status is blocked") { + t.Fatalf("reply contains a redundant internal status: %q", reply) + } + payload := finalizationResponsePayload(decision, nil) + steps, ok := payload["unfinishedPlanSteps"].([]multiagent.PlanStep) + if !ok || len(steps) != 2 || steps[1] != result.UnfinishedPlanSteps[1] { + t.Fatalf("response metadata lost unfinished steps: %+v", payload) + } + var saved string + if err := db.QueryRow("SELECT content FROM messages WHERE id = ?", message.ID).Scan(&saved); err != nil { + t.Fatal(err) + } + if saved != reply { + t.Fatalf("reloading chat should show the same reply, got %q", saved) + } + details, err := db.GetProcessDetails(message.ID) + if err != nil { + t.Fatal(err) + } + if len(details) != 1 || details[0].EventType != "finalization_check" || + !strings.Contains(details[0].Message, "复核数字") || strings.Contains(details[0].Message, draft) { + t.Fatalf("expected a concise finalization check, got %+v", details) + } +} + +func TestUnfinishedPlanWithoutDraftShowsOnlyNotice(t *testing.T) { + for _, response := range []string{"", "(Pi 会话已完成,但未捕获到助手文本输出。)"} { + result := &multiagent.RunResult{ + Response: response, + RuntimeStatus: agentfinalizer.StatusBlocked, + RuntimeCompletionReason: multiagent.ReasonUnfinishedPlan, + } + reply := finalizationBlockedMessage(agentfinalizer.FromRunResult(nil, result, agentfinalizer.Input{})) + if reply != "本轮任务未完成,计划中仍有待执行或进行中的步骤。" { + t.Fatalf("expected only the notice, got %q", reply) + } + } +} diff --git a/internal/handler/multi_agent.go b/internal/handler/multi_agent.go index 4fabe54f..7fb6a33d 100644 --- a/internal/handler/multi_agent.go +++ b/internal/handler/multi_agent.go @@ -426,7 +426,7 @@ func (h *AgentHandler) MultiAgentLoopStream(c *gin.Context) { responseText := decision.FinalText if !decision.Finalizable { responseText = finalizationBlockedMessage(decision) - sendEvent("finalization_check", responseText, decision) + sendEvent("finalization_check", finalizationCheckMessage(decision), decision) taskStatus = decision.Status h.tasks.UpdateTaskStatus(conversationID, taskStatus) } diff --git a/internal/handler/single_agent.go b/internal/handler/single_agent.go index 1add5e6c..31f9308d 100644 --- a/internal/handler/single_agent.go +++ b/internal/handler/single_agent.go @@ -412,7 +412,7 @@ func (h *AgentHandler) SingleAgentLoopStream(c *gin.Context) { responseText := decision.FinalText if !decision.Finalizable { responseText = finalizationBlockedMessage(decision) - sendEvent("finalization_check", responseText, decision) + sendEvent("finalization_check", finalizationCheckMessage(decision), decision) taskStatus = decision.Status h.tasks.UpdateTaskStatus(conversationID, taskStatus) } diff --git a/internal/multiagent/pi_integration_test.go b/internal/multiagent/pi_integration_test.go index 5ee504d5..9cc6799c 100644 --- a/internal/multiagent/pi_integration_test.go +++ b/internal/multiagent/pi_integration_test.go @@ -641,7 +641,7 @@ func TestPiChatCannotCompleteWithCurrentPlanOpen(t *testing.T) { } first := run("Draft the notes.") if finishPlan { - if first.RuntimeStatus != "completed" || calls.Load() != 3 { + if first.RuntimeStatus != "completed" || len(first.UnfinishedPlanSteps) != 0 || calls.Load() != 3 { t.Fatalf("expected completed plan, got %+v after %d calls", first, calls.Load()) } return @@ -649,6 +649,9 @@ func TestPiChatCannotCompleteWithCurrentPlanOpen(t *testing.T) { if first.RuntimeStatus != "blocked" || first.RuntimeCompletionReason != ReasonUnfinishedPlan || calls.Load() != 2 { t.Fatalf("expected unfinished plan, got %+v after %d calls", first, calls.Load()) } + if want := (PlanStep{ID: "1", Subject: "Draft notes", Status: "pending"}); len(first.UnfinishedPlanSteps) != 1 || first.UnfinishedPlanSteps[0] != want { + t.Fatalf("expected unfinished step %+v, got %+v", want, first.UnfinishedPlanSteps) + } if next := run("Please summarize what you have."); next.RuntimeStatus != "completed" { t.Fatalf("old plan state should not block a new reply: %+v", next) } @@ -656,6 +659,44 @@ func TestPiChatCannotCompleteWithCurrentPlanOpen(t *testing.T) { } } +func TestPiPlanExecuteRetainsSubmittedDraftForUnfinishedPlan(t *testing.T) { + cfg := piTestConfig(t) + cfg.MultiAgent.SubAgents = []config.MultiAgentSubConfig{{ID: "executor", Description: "Draft notes"}} + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + switch calls.Add(1) { + case 1: + piReply(w, "write_todos", "plan", map[string]any{"todos": []map[string]any{ + {"content": "Draft notes", "status": "completed"}, + {"content": "Check figures", "status": "in_progress"}, + {"content": "Review wording", "status": "pending"}, + }}, "") + case 2: + piReply(w, "exit", "submit", map[string]any{"final_result": "Here are the draft notes."}, "") + default: + t.Error("unexpected request after submitting draft") + } + })) + defer server.Close() + cfg.OpenAI.BaseURL = server.URL + "/v1" + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + ag := agent.NewAgent(&cfg.OpenAI, &cfg.Agent, mcp.NewServer(zap.NewNop()), nil, zap.NewNop(), 8) + result, err := RunMultiAgent(ctx, cfg, &cfg.MultiAgent, ag, nil, zap.NewNop(), "plan-execute-fixture", "", "Draft the notes.", nil, nil, nil, "", "plan_execute", nil, "") + if err != nil { + t.Fatal(err) + } + if result.RuntimeStatus != "blocked" || result.RuntimeCompletionReason != ReasonUnfinishedPlan || result.Response != "Here are the draft notes." { + t.Fatalf("expected a blocked run with the submitted draft, got %+v", result) + } + steps := result.UnfinishedPlanSteps + if len(steps) != 2 || + steps[0] != (PlanStep{ID: "2", Subject: "Check figures", Status: "in_progress"}) || + steps[1] != (PlanStep{ID: "3", Subject: "Review wording", Status: "pending"}) { + t.Fatalf("unexpected unfinished plan steps: %+v", steps) + } +} + func TestPiReportsTruncatedModelOutput(t *testing.T) { cfg := piTestConfig(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { diff --git a/internal/multiagent/pi_plan_tools.go b/internal/multiagent/pi_plan_tools.go index 235e82b6..4600e8ff 100644 --- a/internal/multiagent/pi_plan_tools.go +++ b/internal/multiagent/pi_plan_tools.go @@ -212,17 +212,14 @@ func (r *piRun) executePiPlan(ctx context.Context, call agentruntime.ToolCall) ( // piRunPlan records only plan changes made in this run. Older tasks in // the conversation's progress board must not block an unrelated reply. -type piRunPlan map[string]string +type piRunPlan map[string]PlanStep func (plan piRunPlan) observe(call agentruntime.ToolCall, response string) { switch call.Name { case "TaskCreate", "TaskUpdate": - var task struct { - ID string `json:"id"` - Status string `json:"status"` - } + var task PlanStep if json.Unmarshal([]byte(response), &task) == nil && task.ID != "" { - plan[task.ID] = task.Status + plan[task.ID] = task } case "write_todos": todos, ok := call.Arguments["todos"].([]any) @@ -232,17 +229,25 @@ func (plan piRunPlan) observe(call agentruntime.ToolCall, response string) { clear(plan) for i, entry := range todos { item, _ := entry.(map[string]any) + id := strconv.Itoa(i + 1) + subject, _ := item["content"].(string) status, _ := item["status"].(string) - plan[strconv.Itoa(i+1)] = status + plan[id] = PlanStep{ID: id, Subject: subject, Status: status} } } } -func (plan piRunPlan) unfinished() bool { - for _, status := range plan { - if status == "pending" || status == "in_progress" { - return true +func (plan piRunPlan) unfinishedSteps() []PlanStep { + var steps []PlanStep + for _, task := range plan { + if task.Status == "pending" || task.Status == "in_progress" { + steps = append(steps, task) } } - return false + sort.Slice(steps, func(i, j int) bool { + a, _ := strconv.Atoi(steps[i].ID) + b, _ := strconv.Atoi(steps[j].ID) + return a < b + }) + return steps } diff --git a/internal/multiagent/pi_runner.go b/internal/multiagent/pi_runner.go index e9a757ce..e10468ed 100644 --- a/internal/multiagent/pi_runner.go +++ b/internal/multiagent/pi_runner.go @@ -617,9 +617,10 @@ func (r *piRun) run(ctx context.Context, message string) (*RunResult, error) { switch res.Status { case "completed": out.RuntimeStatus = "completed" - if plan.unfinished() { + if steps := plan.unfinishedSteps(); len(steps) > 0 { out.RuntimeStatus = "blocked" out.RuntimeCompletionReason = ReasonUnfinishedPlan + out.UnfinishedPlanSteps = steps } case "output_truncated": out.RuntimeStatus = "blocked" diff --git a/internal/multiagent/runtime_types.go b/internal/multiagent/runtime_types.go index e850590a..249878b3 100644 --- a/internal/multiagent/runtime_types.go +++ b/internal/multiagent/runtime_types.go @@ -5,9 +5,16 @@ const ( ReasonUnfinishedPlan = "unfinished_plan" ) +type PlanStep struct { + ID string `json:"id"` + Subject string `json:"subject"` + Status string `json:"status"` +} + type RunResult struct { RuntimeStatus string // immutable runtime outcome; delivery finalization may update Status separately RuntimeCompletionReason string + UnfinishedPlanSteps []PlanStep Response string MCPExecutionIDs []string LastAgentTraceInput string // 已序列化的消息带(JSON):原生循环或 Agent 均写入,供续跑/攻击链等恢复上下文