Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion chatbot/src/operations.js
Original file line number Diff line number Diff line change
Expand Up @@ -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],
[
Expand Down
29 changes: 29 additions & 0 deletions chatbot/tests/composer-operations.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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],
["名称", "独立评审"],
);
});
3 changes: 3 additions & 0 deletions internal/engine/engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
38 changes: 35 additions & 3 deletions internal/engine/human_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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 {
Expand All @@ -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
}
Expand Down
92 changes: 92 additions & 0 deletions internal/engine/human_context_prompt_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
5 changes: 4 additions & 1 deletion internal/engine/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
40 changes: 40 additions & 0 deletions internal/engine/prompt_context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion web/app/access.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)}}));
Expand Down
5 changes: 3 additions & 2 deletions web/app/approvals.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
16 changes: 16 additions & 0 deletions web/command_palette_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
49 changes: 49 additions & 0 deletions web/command_palette_test.js
Original file line number Diff line number Diff line change
@@ -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(/<script src="\/(app\.js|app\/[^"?]+\.js)(?:\?[^"]*)?"><\/script>/g)];
return modules.map(([, file]) => fs.readFileSync(path.join(__dirname, file), 'utf8')).join('\n');
}
const bundle = process.argv[2] ? fs.readFileSync(process.argv[2], 'utf8') : localBundle();
function source(name) {
const match = new RegExp('^(?:async )?function ' + name + '\\(', 'm').exec(bundle);
assert(match, name);
const tail = bundle.slice(match.index);
const next = /\n(?:async )?function |\n(?:let|const) [A-Za-z]|\n\/\/ /.exec(tail);
return next ? tail.slice(0, next.index) : tail;
}
const elements = { '#commandSearch': { value: '' }, '#commandResults': { innerHTML: '' } };
const context = vm.createContext({
state: { data: {
projects: [{ id: 'ledger', key: 'LED' }],
issues: [
{ id: 'a', projectId: 'ledger', number: 1, title: 'split_evenly 平分金额时丢分', priority: 'medium', status: 'done' },
{ id: 'b', projectId: 'ledger', number: 2, title: '按分类汇总支出', priority: 'high', status: 'in_progress' },
{ id: 'c', projectId: 'ledger', number: 3, title: '工蜂导入', source: 'gongfeng', externalRef: { externalIid: 12 }, status: 'backlog' },
],
agents: [],
} },
$: sel => elements[sel], escapeHTML: s => String(s), sopRuns: () => [], catalogWorkflows: () => [],
openIssueDetail: () => {}, openRunFromId: () => {}, switchView: () => {}, openSOPWizard: () => {},
});
vm.runInContext('let commandMatches=[],commandSelectedIndex=0;', context);
const helpers = ['commandCatalog', 'renderCommandResults', 'issueKeyLabel', 'issuePriorityLabel', 'issueStatusLabel'];
// issueKeyLabel may delegate to the shared key rule issueKeyFor (#1517); load it when the bundle has it.
if (/^function issueKeyFor\(/m.test(bundle)) helpers.push('issueKeyFor');
for (const name of helpers) vm.runInContext(source(name), context);
function search(query) {
elements['#commandSearch'].value = query;
context.renderCommandResults();
return [...vm.runInContext('commandMatches', context)].filter(item => item.kind === '需求').map(item => `${item.title} | ${item.meta}`);
}
assert.deepEqual(search('LED-2'), ['按分类汇总支出 | LED-2 · 高 · 进行中']);
assert.deepEqual(search('led-1'), ['split_evenly 平分金额时丢分 | LED-1 · 中 · 已完成']);
assert.deepEqual(search('#12'), ['工蜂导入 | #12 · — · 待规划']);
// Titles still match, and the raw priority enum no longer leaks into the row.
assert.deepEqual(search('平分'), ['split_evenly 平分金额时丢分 | LED-1 · 中 · 已完成']);
assert.ok(!search('').some(row => /medium|high/.test(row)));
16 changes: 16 additions & 0 deletions web/human_context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package web

import (
"os/exec"
"testing"
)

func TestWorkbenchSendsHumanContextOnce(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("node not installed")
}
if out, err := exec.Command(node, "human_context_test.js", appBundlePath(t)).CombinedOutput(); err != nil {
t.Fatalf("human context: %v\n%s", err, out)
}
}
Loading
Loading