diff --git a/chatbot/src/api.js b/chatbot/src/api.js index a710f98c5..3710a3a6c 100644 --- a/chatbot/src/api.js +++ b/chatbot/src/api.js @@ -122,7 +122,7 @@ export function collectArtifacts(session) { const resource = draft.savedResult?.data || draft.savedResult; artifacts.push({ id: `draft-${messageIndex}-${index}`, - name: draft.body?.name || draft.body?.title || actionName(draft.tool), + name: draft.body?.title || draft.body?.name || actionName(draft.tool), kind, resourceKey: draft.saved && resource?.id && ["sop", "role"].includes(kind) diff --git a/chatbot/tests/chat-data.test.mjs b/chatbot/tests/chat-data.test.mjs index dd3c50298..24502ca52 100644 --- a/chatbot/tests/chat-data.test.mjs +++ b/chatbot/tests/chat-data.test.mjs @@ -90,3 +90,31 @@ test("reply duration uses recorded timestamps without inventing missing history null, ); }); +test("a requirement draft artifact is listed under its title even when the draft carries name=", () => { + const session = { + id: "chat-3", + messages: [ + { + role: "assistant", + content: JSON.stringify({ + message: "已准备好", + drafts: [ + { + tool: "issues_save", + body: { + id: "issue-1795", + name: "issue-1795", + title: "format_currency 负数格式", + }, + }, + { tool: "agents_save", body: { id: "a", name: "评审员" } }, + ], + }), + }, + ], + }; + assert.deepEqual( + collectArtifacts(session).map((x) => x.name), + ["format_currency 负数格式", "评审员"], + ); +}); diff --git a/internal/httpapi/assistant_approval.go b/internal/httpapi/assistant_approval.go index 2197cc8b2..01e0be746 100644 --- a/internal/httpapi/assistant_approval.go +++ b/internal/httpapi/assistant_approval.go @@ -138,6 +138,18 @@ func assistantGlobalSaveTool(tool string) bool { } } +// assistantDraftHasName 报告保存的资源是否以 name 字段命名。需求用 title, +// 澄清和同步配置没有名称;给它们补 name=id 不会被保存端点使用,却会让 +// 确认卡片的「名称」显示成内部 ID(如 issue-179…)。 +func assistantDraftHasName(tool string) bool { + switch strings.TrimSpace(tool) { + case "issues_save", "issues_clarification_save", "sync_config_save": + return false + default: + return true + } +} + // injectAssistantDraftProjectID 给保存类草稿补上缺失的 projectId 与 name。 // 模型有时省略这些字段(校验只在字段存在时才比对),平台保存端点却必填; // 自动执行前注入可避免必然失败的写入。平台级资源不归属会话所在项目: @@ -165,7 +177,7 @@ func injectAssistantDraftProjectID(tool string, body json.RawMessage, projectID changed = true } } - if raw, exists := obj["name"]; !exists || func() bool { s, _ := raw.(string); return strings.TrimSpace(s) == "" }() { + if raw, exists := obj["name"]; assistantDraftHasName(tool) && (!exists || func() bool { s, _ := raw.(string); return strings.TrimSpace(s) == "" }()) { if id, _ := obj["id"].(string); strings.TrimSpace(id) != "" { obj["name"] = id changed = true diff --git a/internal/httpapi/assistant_draft_scope_test.go b/internal/httpapi/assistant_draft_scope_test.go index 8081b80e6..e50f3df06 100644 --- a/internal/httpapi/assistant_draft_scope_test.go +++ b/internal/httpapi/assistant_draft_scope_test.go @@ -89,3 +89,31 @@ func TestAssistantDraftScopeCoversEveryWriteTool(t *testing.T) { t.Fatalf("no-project chat injected a project: %s", got) } } + +// A draft names its target only through the field the resource really has. +// Requirements are titled, not named: injecting name= into an issues_save +// draft made the confirmation card show 「名称 issue-179…」 instead of the title. +func TestAssistantDraftNameInjectedOnlyForNamedResources(t *testing.T) { + untitled := map[string]bool{"issues_save": true, "issues_clarification_save": true, "sync_config_save": true} + for tool := range assistantDraftScope { + got := map[string]any{} + if err := json.Unmarshal(injectAssistantDraftProjectID(tool, json.RawMessage(`{"id":"x"}`), "p"), &got); err != nil { + t.Fatalf("%s: %v", tool, err) + } + _, named := got["name"] + if untitled[tool] && named { + t.Errorf("%s: injected name %v into a resource without a name field", tool, got["name"]) + } + if !untitled[tool] && tool != "assistant_tasks_save" && got["name"] != "x" { + t.Errorf("%s: name = %v, want the id", tool, got["name"]) + } + } + got := map[string]any{} + body := `{"id":"issue-1","title":"split_bill 合计不等于总额","priority":"high"}` + if err := json.Unmarshal(injectAssistantDraftProjectID("issues_save", json.RawMessage(body), "p"), &got); err != nil { + t.Fatal(err) + } + if _, ok := got["name"]; ok || got["title"] != "split_bill 合计不等于总额" || got["projectId"] != "p" { + t.Fatalf("issues_save draft = %v", got) + } +} diff --git a/internal/httpapi/issue_source_test.go b/internal/httpapi/issue_source_test.go new file mode 100644 index 000000000..058138914 --- /dev/null +++ b/internal/httpapi/issue_source_test.go @@ -0,0 +1,52 @@ +package httpapi + +import ( + "net/http" + "path/filepath" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/engine" + "agentflow/internal/repo" + "agentflow/internal/runtime" + "agentflow/internal/tracker" +) + +// The AI assistant edits an issue by echoing it back through issues_save and +// drafted "source":"local" for a synced GitHub issue when only asked to change +// its priority. The edit relabelled the issue 平台新建 while its externalRef +// still pointed at GitHub, so a closed GitHub issue no longer counted as +// tracker-closed until the next pull. Where an item came from is not editable. +func TestIssueEditKeepsWhereTheIssueCameFrom(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + if err := st.PutProject(domain.Project{ID: "p", Key: "P", Name: "P"}); err != nil { + t.Fatal(err) + } + synced := domain.Issue{ID: "gh-r-1", ProjectID: "p", Number: 1, Kind: "issue", Title: "days_in_month", Status: "todo", Priority: "medium", + Source: "github", ExternalRef: &domain.ExternalRef{Source: "github", ExternalID: "10", ExternalIID: 1, ExternalState: "closed", ExternalType: "issue"}} + if err := st.PutIssue(synced); err != nil { + t.Fatal(err) + } + h := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") + edited := requestJSON[domain.Issue](t, h, http.MethodPut, "/api/issues", map[string]any{ + "id": synced.ID, "projectId": "p", "title": synced.Title, "priority": "high", "source": "local", + }, http.StatusOK) + stored, _ := st.Issue(synced.ID) + for _, got := range []domain.Issue{edited, stored} { + if got.Source != "github" || got.Priority != "high" || !got.TrackerClosed() { + t.Fatalf("edit relabelled a GitHub issue: source=%q priority=%q trackerClosed=%v", got.Source, got.Priority, got.TrackerClosed()) + } + } + + local := requestJSON[domain.Issue](t, h, http.MethodPost, "/api/issues", map[string]any{"projectId": "p", "title": "平台需求"}, http.StatusOK) + forged := requestJSON[domain.Issue](t, h, http.MethodPut, "/api/issues", map[string]any{ + "id": local.ID, "projectId": "p", "title": local.Title, "source": "github", + }, http.StatusOK) + if local.Source != "local" || forged.Source != "local" { + t.Fatalf("a platform requirement became %q after an edit claiming GitHub", forged.Source) + } +} diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index fe8206ec2..27fc18605 100644 --- a/internal/httpapi/issues.go +++ b/internal/httpapi/issues.go @@ -388,7 +388,10 @@ func mergeIssueEdit(v, existing domain.Issue) domain.Issue { if v.LatestTaskID == "" { v.LatestTaskID = existing.LatestTaskID } - if v.Source == "" { + // Source records where the item came from; only intake and tracker sync + // set it. An edit that echoes a guessed source (the assistant drafted + // "source":"local" for a synced GitHub issue) must not relabel the item. + if strings.TrimSpace(existing.Source) != "" || v.Source == "" { v.Source = existing.Source } if v.ExternalRef == nil { diff --git a/internal/tracker/github.go b/internal/tracker/github.go index 880293bc4..d2d10f745 100644 --- a/internal/tracker/github.go +++ b/internal/tracker/github.go @@ -292,6 +292,11 @@ func (s *Service) pullGitHubIssues(store IssueStoreAdapter, repo domain.Reposito } if old, ok := store.Issue(id); ok { applyExistingIssue(&issue, old) + // GitHub issues carry no priority, so the one set on the + // platform is the only one; a pull must not reset it to medium. + if strings.TrimSpace(old.Priority) != "" { + issue.Priority = old.Priority + } if old.Clarification.Status != "" || (old.ExternalRef != nil && githubBodyHash(old.Description) != old.ExternalRef.SourceContentHash) { issue.Description = old.Description } diff --git a/internal/tracker/github_test.go b/internal/tracker/github_test.go index 9d6d04a69..3f541d603 100644 --- a/internal/tracker/github_test.go +++ b/internal/tracker/github_test.go @@ -61,18 +61,20 @@ func TestGitHubImportPreservesLocalWorkAndMergeChecksConfirmation(t *testing.T) t.Fatalf("import: %d %v", n, err) } issue, ok := st.Issue("gh-github-repo-2") - if !ok || issue.Source != "github" { + if !ok || issue.Source != "github" || issue.Priority != "medium" { t.Fatalf("issue: %+v", issue) } issue.Description = "Locally clarified requirement" issue.Status = "in_progress" + // GitHub has no priority: the one set on the platform must survive pulls. + issue.Priority = "urgent" if err := st.PutIssue(issue); err != nil { t.Fatal(err) } if _, err := s.pullGitHubIssues(st, r); err != nil { t.Fatal(err) } - if got, _ := st.Issue(issue.ID); got.Description != issue.Description || got.Status != "in_progress" { + if got, _ := st.Issue(issue.ID); got.Description != issue.Description || got.Status != "in_progress" || got.Priority != "urgent" { t.Fatalf("local work overwritten: %+v", got) } if _, err := s.EnsureAndMergeBranchMR(r.GongfengProjectID, "feature/work", "main", "Title", ""); err == nil { diff --git a/web/app/issue-drawer.js b/web/app/issue-drawer.js index c3cf398e1..7a12a66bc 100644 --- a/web/app/issue-drawer.js +++ b/web/app/issue-drawer.js @@ -903,6 +903,12 @@ function nodesInExecutionOrder(wf){ } return out; } +// An approval node is itself the human gate and runs no commands; only the +// parts that apply are joined, so no row ends in or repeats a bare separator. +function acceptanceGateSummary(g){ + const n=g.commands; + return [g.isApproval?lfT('人工门禁','Human gate'):lfT(`${n} 项命令`,`${n} ${n===1?'command':'commands'}`),g.manual?lfT('需人工','Needs human'):'',g.rejectTo?lfT('可打回','Can send back'):''].filter(Boolean).join(' · '); +} function acceptancePane(issue,data){ const run=data.run; if(conversationWorkspaceIssue(issue,run)){ @@ -917,9 +923,9 @@ function acceptancePane(issue,data){ if(nr.status==='waiting_approval')verdict=turnsExhausted(nr)?'等待确认是否重试':(isApproval?'等待人工判断':'等待人工验收'); if(nr.status==='failed')verdict='门禁失败'; if(nr.status==='running')verdict='执行中'; - return {name:n.name||n.id,status:nr.status||'pending',verdict,commands:commands.length,manual,rejectTo:n.rejectTo,nodeId:n.id,nr,node:n}; + return {name:n.name||n.id,status:nr.status||'pending',verdict,commands:commands.length,manual,isApproval,rejectTo:n.rejectTo,nodeId:n.id,nr,node:n}; }); - const rows=gates.map(g=>`
${escapeHTML(g.name)}${g.commands} 项命令 · ${g.manual?'需人工':''}${g.rejectTo?' · 可打回':''}
${escapeHTML(g.verdict)}
${g.status==='waiting_approval'?humanDecisionPanelHTML(run.id,g.nodeId,g.nr,g.node,nodes):''}`).join(''); + const rows=gates.map(g=>`
${escapeHTML(g.name)}${acceptanceGateSummary(g)}
${escapeHTML(g.verdict)}
${g.status==='waiting_approval'?humanDecisionPanelHTML(run.id,g.nodeId,g.nr,g.node,nodes):''}`).join(''); return `

验收门禁节点自动验证与人工门禁,失败可打回指定节点

${rows||'
该流程没有配置验证门禁
'}
`; } function formatActivityTime(ts){ diff --git a/webtest/tests/issue-acceptance-gates.test.mjs b/webtest/tests/issue-acceptance-gates.test.mjs new file mode 100644 index 000000000..ba13f09dd --- /dev/null +++ b/webtest/tests/issue-acceptance-gates.test.mjs @@ -0,0 +1,47 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { loadApp } from '../lib/load-app.mjs'; + +// The 验收 tab used to print "0 项命令 · " on every node and "0 项命令 · · 可打回" +// on the 人工验收 approval node: a separator was emitted even when nothing +// followed it, and the approval node (the human gate itself) was described as +// running zero commands. +test('acceptance gate pills list only the parts that apply and name the approval node as the human gate', async (t) => { + const app = await loadApp(); + t.after(app.close); + const result = structuredClone(app.evaluate(`(() => { + state.data.agents=[...(state.data.agents||[]), + {id:'impl',name:'开发实现',verification:[]}, + {id:'mr',name:'发起 MR',verification:[{id:'g1',mode:'command',commands:['git push'],required:true}]}, + {id:'qa',name:'人工复核',verification:[{id:'g2',mode:'manual',required:true},{id:'g3',mode:'command',commands:['make test','make lint'],required:true}]}]; + const wf={id:'flow-1',nodes:[ + {id:'implement',name:'开发实现',type:'agent',agentId:'impl'}, + {id:'qa',name:'人工复核',type:'agent',agentId:'qa',rejectTo:'implement'}, + {id:'accept',name:'人工验收',type:'approval',rejectTo:'implement'}, + {id:'mr',name:'发起 MR',type:'agent',agentId:'mr'}], + edges:[{source:'implement',target:'qa'},{source:'qa',target:'accept'},{source:'accept',target:'mr'}]}; + const run={id:'run-1',status:'succeeded',workflowId:'flow-1',workflowSnapshot:wf, + nodes:{implement:{status:'succeeded'},qa:{status:'succeeded'},accept:{status:'succeeded'},mr:{status:'succeeded'}}}; + const issue={...state.data.issues[0],source:'manual'}; + const rows=()=>{const box=document.createElement('div'); + box.innerHTML=acceptancePane(issue,{issue,run,task:null,requirement:null}); + return [...box.querySelectorAll('.node-progress-row')].map(r=>[r.querySelector('.node-name').textContent,r.querySelector('.pill').textContent,r.querySelector('.status').textContent]);}; + const zh=rows(); + const lfT0=window.lfT; + window.lfT=(zhText,en)=>en; + try{return {zh,en:rows().map(r=>r[1])}}finally{window.lfT=lfT0} + })()`)); + assert.deepEqual(result.zh, [ + ['开发实现', '0 项命令', '完成'], + ['人工复核', '1 项命令 · 需人工 · 可打回', '门禁通过'], + ['人工验收', '人工门禁 · 可打回', '已批准'], + ['发起 MR', '1 项命令', '门禁通过'], + ]); + for (const [, pill] of result.zh) assert.doesNotMatch(pill, /·\s*$|·\s*·/); + assert.deepEqual(result.en, [ + '0 commands', + '1 command · Needs human · Can send back', + 'Human gate · Can send back', + '1 command', + ]); +});