fix(chat): preserve draft replies when plans are unfinished
This commit is contained in:
parent
0a7020f62a
commit
6e0a6854fb
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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 均写入,供续跑/攻击链等恢复上下文
|
||||
|
|
|
|||
Loading…
Reference in New Issue