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
2 changes: 1 addition & 1 deletion chatbot/src/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions chatbot/tests/chat-data.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id>", () => {
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 负数格式", "评审员"],
);
});
14 changes: 13 additions & 1 deletion internal/httpapi/assistant_approval.go
Original file line number Diff line number Diff line change
Expand Up @@ -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。
// 模型有时省略这些字段(校验只在字段存在时才比对),平台保存端点却必填;
// 自动执行前注入可避免必然失败的写入。平台级资源不归属会话所在项目:
Expand Down Expand Up @@ -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
Expand Down
28 changes: 28 additions & 0 deletions internal/httpapi/assistant_draft_scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id> 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)
}
}
52 changes: 52 additions & 0 deletions internal/httpapi/issue_source_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
5 changes: 4 additions & 1 deletion internal/httpapi/issues.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
5 changes: 5 additions & 0 deletions internal/tracker/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
6 changes: 4 additions & 2 deletions internal/tracker/github_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
10 changes: 8 additions & 2 deletions web/app/issue-drawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)){
Expand All @@ -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=>`<div class="node-progress-row"><span class="node-name">${escapeHTML(g.name)}</span><span class="pill">${g.commands} 项命令 · ${g.manual?'需人工':''}${g.rejectTo?' · 可打回':''}</span><div style="flex:1"></div><span class="status ${g.status}">${escapeHTML(g.verdict)}</span></div>${g.status==='waiting_approval'?humanDecisionPanelHTML(run.id,g.nodeId,g.nr,g.node,nodes):''}`).join('');
const rows=gates.map(g=>`<div class="node-progress-row"><span class="node-name">${escapeHTML(g.name)}</span><span class="pill">${acceptanceGateSummary(g)}</span><div style="flex:1"></div><span class="status ${g.status}">${escapeHTML(g.verdict)}</span></div>${g.status==='waiting_approval'?humanDecisionPanelHTML(run.id,g.nodeId,g.nr,g.node,nodes):''}`).join('');
return `<div class="detail-section"><h3>验收门禁<span class="sub">节点自动验证与人工门禁,失败可打回指定节点</span></h3>${rows||'<div class="detail-empty">该流程没有配置验证门禁</div>'}</div>`;
}
function formatActivityTime(ts){
Expand Down
47 changes: 47 additions & 0 deletions webtest/tests/issue-acceptance-gates.test.mjs
Original file line number Diff line number Diff line change
@@ -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',
]);
});
Loading