diff --git a/chatbot/src/operations.js b/chatbot/src/operations.js index 107053954..6816263a6 100644 --- a/chatbot/src/operations.js +++ b/chatbot/src/operations.js @@ -111,7 +111,11 @@ export function operationSummary( "项目", project ? projects.find((p) => p.id === project)?.name || project : "", ], - ["名称", body.name || body.title], + // Requirements are saved by title; a stray `name` in the body is ignored. + [ + "名称", + draft.tool === "issues_save" ? body.title : body.name || body.title, + ], ["目标", draft.path?.id || body.id], ["TAPD 链接", body.url], [ diff --git a/chatbot/tests/composer-operations.test.mjs b/chatbot/tests/composer-operations.test.mjs index 84acba5bb..5895ee811 100644 --- a/chatbot/tests/composer-operations.test.mjs +++ b/chatbot/tests/composer-operations.test.mjs @@ -191,3 +191,32 @@ test("a requirement saved without a LOOP says so instead of naming the LOOP it d assert.equal(sopOf({ workflowId: "wf" }), "后端交付 LOOP"); assert.equal(sopOf({}), undefined); }); +test("a requirement draft is shown by the title it will be saved with", () => { + // issues_save persists `title`; models sometimes add an ignored `name` + // (often the requirement ID), which the card must not present as its name. + const summary = operationSummary( + { + tool: "issues_save", + body: { + id: "ledger-summary", + name: "ledger-summary", + title: "按分类汇总支出并校验 CSV 导入", + projectId: "ledger", + }, + }, + { projects: [{ id: "ledger", name: "家庭账本" }] }, + ); + assert.deepEqual(summary.fields.slice(0, 3), [ + ["项目", "家庭账本"], + ["名称", "按分类汇总支出并校验 CSV 导入"], + ["目标", "ledger-summary"], + ]); + // Other resources keep their name. + assert.deepEqual( + operationSummary({ + tool: "agents_save", + body: { id: "rev", name: "独立评审", title: "x" }, + }).fields[0], + ["名称", "独立评审"], + ); +}); diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 014ee8aeb..947e5e54a 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -3825,6 +3825,9 @@ func TestRecordHumanContextPersistsForRetryAndPrompt(t *testing.T) { if !strings.Contains(prompt, "人工补充上下文") || !strings.Contains(prompt, "TestCanonicalPayloadMarshal") { t.Fatalf("prompt missing human context: %s", prompt) } + if got := strings.Count(prompt, "TestCanonicalPayloadMarshal"); got != 1 || !strings.Contains(prompt, "人工确认重试本节点") { + t.Fatalf("prompt must carry the reason and the human context exactly once, got %d copies: %s", got, prompt) + } if err := writeHumanContextFile(dir, current.HumanContext); err != nil { t.Fatal(err) } diff --git a/internal/engine/human_context.go b/internal/engine/human_context.go index 35b4defca..b9f101713 100644 --- a/internal/engine/human_context.go +++ b/internal/engine/human_context.go @@ -9,6 +9,14 @@ import ( const maxHumanContextBytes = 8000 +const ( + // humanContextLabel prefixes the operator note composeHumanFeedback folds + // into a node's feedback. + humanContextLabel = "人工补充上下文:\n" + // humanContextSeparator joins successive notes in Run.HumanContext. + humanContextSeparator = "\n\n---\n" +) + func composeHumanFeedback(reason, context string) string { reason = strings.TrimSpace(reason) context = strings.TrimSpace(context) @@ -19,10 +27,34 @@ func composeHumanFeedback(reason, context string) string { case context == "": return reason case reason == "": - return "人工补充上下文:\n" + context + return humanContextLabel + context default: - return reason + "\n\n人工补充上下文:\n" + context + return reason + "\n\n" + humanContextLabel + context + } +} + +// feedbackWithoutHumanContext drops the operator notes recordHumanContext +// folded into a node's feedback when the prompt renders Run.HumanContext as its +// own section, so the agent reads each note once. Text the notes do not cover, +// such as the retry reason, stays. +func feedbackWithoutHumanContext(feedback, humanContext string) string { + humanContext = strings.TrimSpace(humanContext) + if feedback == "" || humanContext == "" { + return feedback + } + stripped := feedback + for _, note := range append([]string{humanContext}, strings.Split(humanContext, humanContextSeparator)...) { + if note = strings.TrimSpace(note); note == "" { + continue + } + block := humanContextLabel + note + stripped = strings.ReplaceAll(stripped, "\n\n"+block, "") + stripped = strings.ReplaceAll(stripped, block, "") + } + if stripped == feedback { + return feedback } + return strings.TrimSpace(stripped) } func recordHumanContext(r *domain.Run, nodeID, reason, context string) string { @@ -35,7 +67,7 @@ func recordHumanContext(r *domain.Run, nodeID, reason, context string) string { ctx = ctx[:maxHumanContextBytes] } if prev := strings.TrimSpace(r.HumanContext); prev != "" && prev != ctx { - r.HumanContext = prev + "\n\n---\n" + ctx + r.HumanContext = prev + humanContextSeparator + ctx } else { r.HumanContext = ctx } diff --git a/internal/engine/human_context_prompt_test.go b/internal/engine/human_context_prompt_test.go new file mode 100644 index 000000000..33b720abb --- /dev/null +++ b/internal/engine/human_context_prompt_test.go @@ -0,0 +1,92 @@ +package engine + +import ( + "strings" + "testing" + + "agentflow/internal/domain" +) + +func TestPromptRendersEachHumanContextNoteOnce(t *testing.T) { + t.Parallel() + retry := func(r *domain.Run, reason, context string) { + r.Nodes["build"].Feedback = recordHumanContext(r, "build", reason, context) + } + render := func(r domain.Run) string { + return renderPromptSpec(domain.WorkflowDefinition{ID: "lab"}, domain.WorkflowNode{ID: "build"}, "do work", r) + } + newRun := func() domain.Run { + return domain.Run{Input: "input", Nodes: map[string]*domain.NodeRun{"build": {Attempt: 1}}} + } + + t.Run("reason and context", func(t *testing.T) { + r := newRun() + retry(&r, "人工确认重试本节点", "[CTX1] 请把错误信息改成中文") + prompt := render(r) + if got := strings.Count(prompt, "[CTX1]"); got != 1 { + t.Fatalf("context copies = %d, prompt:\n%s", got, prompt) + } + if !strings.Contains(prompt, "上一轮反馈:人工确认重试本节点\n") || !strings.Contains(prompt, "## 人工补充上下文") { + t.Fatalf("reason or section missing:\n%s", prompt) + } + }) + + t.Run("context only", func(t *testing.T) { + r := newRun() + retry(&r, "", "[CTX2] 只补充上下文") + prompt := render(r) + if got := strings.Count(prompt, "[CTX2]"); got != 1 || strings.Contains(prompt, humanContextLabel) { + t.Fatalf("context copies = %d, prompt:\n%s", got, prompt) + } + }) + + t.Run("successive retries", func(t *testing.T) { + r := newRun() + retry(&r, "第一次重试", "[CTX3] 第一条") + retry(&r, "第二次重试", "[CTX4] 第二条") + prompt := render(r) + for _, marker := range []string{"[CTX3]", "[CTX4]"} { + if got := strings.Count(prompt, marker); got != 1 { + t.Fatalf("%s copies = %d, prompt:\n%s", marker, got, prompt) + } + } + if !strings.Contains(prompt, "上一轮反馈:第二次重试\n") { + t.Fatalf("latest reason missing:\n%s", prompt) + } + }) + + t.Run("resume restores earlier feedback", func(t *testing.T) { + r := newRun() + earlier := recordHumanContext(&r, "build", "切回 SOP", "[CTX5] 早先的说明") + note := recordHumanContext(&r, "build", "", "[CTX6] 继续时的说明") + r.Nodes["build"].Feedback = strings.TrimSpace(earlier + "\n" + note) + prompt := render(r) + for _, marker := range []string{"[CTX5]", "[CTX6]"} { + if got := strings.Count(prompt, marker); got != 1 { + t.Fatalf("%s copies = %d, prompt:\n%s", marker, got, prompt) + } + } + if !strings.Contains(prompt, "上一轮反馈:切回 SOP\n") { + t.Fatalf("restored reason missing:\n%s", prompt) + } + }) + + t.Run("feedback without human context is untouched", func(t *testing.T) { + r := newRun() + r.HumanContext = "[CTX7] 来自别的节点" + r.Nodes["build"].Feedback = "门禁失败:go test 退出 1" + prompt := render(r) + if !strings.Contains(prompt, "上一轮反馈:门禁失败:go test 退出 1\n") || strings.Count(prompt, "[CTX7]") != 1 { + t.Fatalf("prompt:\n%s", prompt) + } + }) + + t.Run("no human context keeps feedback verbatim", func(t *testing.T) { + r := newRun() + r.Nodes["build"].Feedback = "人工补充上下文:\n不是本次运行记录的说明" + prompt := render(r) + if !strings.Contains(prompt, "上一轮反馈:人工补充上下文:\n不是本次运行记录的说明") || strings.Contains(prompt, "## 人工补充上下文") { + t.Fatalf("prompt:\n%s", prompt) + } + }) +} diff --git a/internal/engine/prompt.go b/internal/engine/prompt.go index 489e5af54..3b3769f81 100644 --- a/internal/engine/prompt.go +++ b/internal/engine/prompt.go @@ -80,8 +80,11 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, node if current := run.Nodes[node.ID]; current != nil { feedback = current.Feedback } - prompt = strings.ReplaceAll(prompt, "{{feedback}}", feedback) humanNote := strings.TrimSpace(run.HumanContext) + // The 人工补充上下文 section below carries every note; keep only the retry + // reason in the feedback line. + feedback = feedbackWithoutHumanContext(feedback, humanNote) + prompt = strings.ReplaceAll(prompt, "{{feedback}}", feedback) prompt = strings.ReplaceAll(prompt, "{{humanContext}}", humanNote) if humanNote != "" { prompt += "\n\n## 人工补充上下文\n\n操作员在审核或重试时补充了以下信息,请优先采信并据此行动:\n\n" + humanNote + "\n" diff --git a/internal/engine/prompt_context_test.go b/internal/engine/prompt_context_test.go index 87d1e2162..a6f0242de 100644 --- a/internal/engine/prompt_context_test.go +++ b/internal/engine/prompt_context_test.go @@ -6,6 +6,46 @@ import ( "testing" ) +// The operator's note reaches the node once, in the human-context section: +// the copy composeHumanFeedback folded into the retried node's feedback is +// dropped when the prompt is rendered. +func TestHumanContextReachesTheNodeOnce(t *testing.T) { + t.Parallel() + wf := domain.WorkflowDefinition{Edges: []domain.WorkflowEdge{{Source: "source", Target: "report"}}} + node := domain.WorkflowNode{ID: "report"} + note := "把结论写成人话,别贴原始 JSON" + role := &domain.AgentDefinition{Prompt: "完成分析"} + // The retried node: its feedback already carries the note through + // composeHumanFeedback, and run.HumanContext holds the same text. + run := domain.Run{Input: "整理数据", HumanContext: note, + Nodes: map[string]*domain.NodeRun{"report": {Feedback: composeHumanFeedback("补充信息,重跑当前节点", note)}}} + if got := applyPromptPlaceholders(nil, wf, node, role, run); strings.Count(got, note) != 1 { + t.Fatalf("human context must appear once: %s", got) + } + // A later node whose feedback does not carry the note still receives it. + run.Nodes = map[string]*domain.NodeRun{"report": {Feedback: "上一轮失败"}} + if got := applyPromptPlaceholders(nil, wf, node, role, run); strings.Count(got, note) != 1 || !strings.Contains(got, "## 人工补充上下文") { + t.Fatalf("human context must reach a node without feedback: %s", got) + } + // Notes accumulate with "---"; each of them reaches the node once. + older, newer := "第一轮的补充", "第二轮的补充" + run.HumanContext = older + "\n\n---\n" + newer + run.Nodes = map[string]*domain.NodeRun{"report": {Feedback: composeHumanFeedback("", newer)}} + got := applyPromptPlaceholders(nil, wf, node, role, run) + if strings.Count(got, newer) != 1 || !strings.Contains(got, older) { + t.Fatalf("every accumulated note must appear once: %s", got) + } + // A note whose text also appears elsewhere in the prompt, such as the run + // input, still reaches the node as an operator note. + run.Input = "整理数据," + note + run.HumanContext = note + run.Nodes = map[string]*domain.NodeRun{"report": {Feedback: composeHumanFeedback("补充信息,重跑当前节点", note)}} + got = applyPromptPlaceholders(nil, wf, node, role, run) + if strings.Count(got, note) != 2 || !strings.Contains(got, "## 人工补充上下文") || !strings.Contains(got, "补充信息,重跑当前节点") { + t.Fatalf("an operator note repeated in the input must keep its section: %s", got) + } +} + // A role node's brief comes from the role prompt alone: the node's taskPrompt // (an approval node's 「需要确认什么」) never reaches it, while the run input // and upstream output always do, exactly once. diff --git a/web/app/access.js b/web/app/access.js index f1d41fcb7..af6ad72dd 100644 --- a/web/app/access.js +++ b/web/app/access.js @@ -276,7 +276,7 @@ async function revokePersonalToken(id){ let commandMatches=[],commandSelectedIndex=0; function commandCatalog(){ const pages=[['collaboration','AI 工作台','和 AI 对话,派发与跟进任务'],['issues','需求列表','查看进度,触发或重试'],['approvals','待我确认','批准或退回卡住的需求'],['observability','统计','用量分析 · Token 与质量'],['settings','个人配置','账号、模型与执行凭据'],['projects','项目配置','项目、成员和仓库'],['bots','通道管理','企业微信、飞书、钉钉机器人通道'],['sops','流程模板','Issue 修复与需求开发'],['runs','运行记录','查看节点日志和产物'],['aiSchedules','定时任务','提示词任务、LOOP 触发与共享任务'],['agents','角色定义','管理角色和能力资产'],['evolution','RSI工作台','诊断问题、运行记录与修复提案'],['mcp','能力资产 · MCP','添加项目级或个人 MCP'],['rules','能力资产 · 规则','当前项目的行为与执行约束'],['skills','能力资产 · 技能','当前项目的技能和附加文件'],['runners','执行机器','用自己的电脑或 CVM 跑任务'],['sandboxes','沙箱管理','隔离方式、Dockerfile 与环境变量'],['guide','访问密钥','创建和撤销访问密钥']].map(([view,title,meta])=>({kind:'页面',title,meta,action:()=>switchView(view)})); - const issues=(state.data.issues||[]).map(i=>({kind:'需求',title:i.title,meta:`${i.priority||'—'} · ${issueStatusLabel(i.status)}`,action:()=>openIssueDetail(i.id)})); + const issues=(state.data.issues||[]).map(i=>({kind:'需求',title:i.title,meta:`${issueKeyLabel(i)} · ${issuePriorityLabel(i.priority)} · ${issueStatusLabel(i.status)}`,action:()=>openIssueDetail(i.id)})); const runs=sopRuns(state.data.runs).map(r=>({kind:'运行',title:runIssueTitle(r),meta:`${runDisplayStatus(r)} · ${r.workflowSnapshot?.name||r.workflowId}`,action:()=>openRunFromId(r.id)})); const sops=catalogWorkflows().map(w=>({kind:'LOOP',title:w.name,meta:`${w.status==='published'?'已发布':'草稿'} · ${w.nodes?.length||0} 个节点`,action:()=>{state.workflow=clone(w);state.selectedNode=null;switchView('flow')}})); const agents=(state.data.agents||[]).map(a=>({kind:'Agent',title:a.name,meta:a.description||a.id,action:()=>{switchView('agents');openAgentWizard(a)}})); diff --git a/web/app/approvals.js b/web/app/approvals.js index 19dc6cfcd..04fcac50f 100644 --- a/web/app/approvals.js +++ b/web/app/approvals.js @@ -8,11 +8,12 @@ function readHumanContext(fromEl){ const root=fromEl?.closest?.('[data-human-context-root], .approval-callout, .ap-card, .issue-outcome, .node-inspector, .human-decision'); return String(root?.querySelector?.('[data-human-context]')?.value||'').trim(); } +// The server composes reason + context into the node feedback (and caps the +// context); sending them pre-merged would repeat the context in the prompt. function withHumanContext(payload){ const context=String(payload?.context||'').trim(); if(!context)return payload; - const reason=String(payload.reason||'').trim(); - return {...payload, context, reason:reason?`${reason}\n\n人工补充上下文:\n${context}`:context}; + return {...payload, context}; } function reworkTarget(node,nodes){ const id=String(node?.rejectTo||'').trim(); diff --git a/web/command_palette_test.go b/web/command_palette_test.go new file mode 100644 index 000000000..8d1272507 --- /dev/null +++ b/web/command_palette_test.go @@ -0,0 +1,16 @@ +package web + +import ( + "os/exec" + "testing" +) + +func TestCommandPaletteFindsRequirementsByKey(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed") + } + if out, err := exec.Command(node, "command_palette_test.js", appBundlePath(t)).CombinedOutput(); err != nil { + t.Fatalf("command palette: %v\n%s", err, out) + } +} diff --git a/web/command_palette_test.js b/web/command_palette_test.js new file mode 100644 index 000000000..4ba02ddbe --- /dev/null +++ b/web/command_palette_test.js @@ -0,0 +1,49 @@ +// ⌘K says "换一个标题、编号或页面名称试试": requirements must be found by the +// key the list shows (LED-2, #12 for Gongfeng, the TAPD ID), not only by title. +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const assert = require('node:assert/strict'); +function localBundle() { + const page = fs.readFileSync(path.join(__dirname, 'index.html'), 'utf8'); + const modules = [...page.matchAll(/