diff --git a/internal/domain/issue.go b/internal/domain/issue.go index a0c253375..4396cbc69 100644 --- a/internal/domain/issue.go +++ b/internal/domain/issue.go @@ -294,6 +294,8 @@ func (i Issue) IdentityBlock() string { b.WriteString("TAPD") case "gongfeng": b.WriteString("工蜂") + case "github": + b.WriteString("GitHub") default: b.WriteString("本地") } diff --git a/internal/domain/issue_identity_test.go b/internal/domain/issue_identity_test.go index 0c22b1bae..26e823fe0 100644 --- a/internal/domain/issue_identity_test.go +++ b/internal/domain/issue_identity_test.go @@ -40,3 +40,28 @@ func TestIssueIdentityBlockLocal(t *testing.T) { t.Fatalf("local identity:\n%s", got) } } + +// GitHub issues used to fall through to "本地", telling the LOOP agent the +// GitHub issue it was fixing had no tracker behind it. +func TestIssueIdentityBlockGitHub(t *testing.T) { + issue := Issue{ + ID: "gh-repo-1", + Source: "github", + ExternalRef: &ExternalRef{ + Source: "github", + ExternalID: "6663098674", + ExternalIID: 1, + ExternalType: "issue", + ExternalURL: "https://github.com/acme/widgets/issues/1", + }, + } + got := issue.IdentityBlock() + for _, want := range []string{"来源:GitHub", "外部编号:1", "https://github.com/acme/widgets/issues/1"} { + if !strings.Contains(got, want) { + t.Fatalf("identity block missing %q:\n%s", want, got) + } + } + if strings.Contains(got, "来源:本地") { + t.Fatalf("GitHub issue labelled local:\n%s", got) + } +} diff --git a/internal/httpapi/assistant_draft_invoker_test.go b/internal/httpapi/assistant_draft_invoker_test.go new file mode 100644 index 000000000..d226f73b8 --- /dev/null +++ b/internal/httpapi/assistant_draft_invoker_test.go @@ -0,0 +1,67 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "net/http" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/tracker" +) + +// The workbench runs a confirmed draft through /mcp with the chat session +// header. Models put only the fields they change into an issues_save draft, so +// confirming "switch the LOOP" must not clear the description or reset +// priority and status the way a full PUT /api/issues replacement does. +func TestConfirmedIssueSaveDraftKeepsOmittedFields(t *testing.T) { + for _, tc := range []struct { + name string + confirm bool + wantKept bool + }{ + {"confirmed workbench draft", true, true}, + {"plain MCP call keeps full replacement", false, false}, + } { + t.Run(tc.name, func(t *testing.T) { + h, user, _ := chatSandboxFixture(t) + for _, id := range []string{"loop-a", "loop-b"} { + if err := h.repo.PutWorkflow(domain.WorkflowDefinition{ID: id, Name: id, ProjectID: "workbench", Nodes: []domain.WorkflowNode{{ID: "check", Name: "Check", Type: "command", Command: "true"}}}); err != nil { + t.Fatal(err) + } + } + issue := domain.Issue{ID: "draft-issue", ProjectID: "workbench", Title: "human_bytes 边界", Description: "human_bytes(1024) 应为 1.0 KiB", Priority: "high", Status: "todo", Kind: "requirement", WorkflowID: "loop-a", AssigneeUserID: user.ID} + if err := h.repo.PutIssue(issue); err != nil { + t.Fatal(err) + } + if err := h.repo.PutAssistantSession(user.ID, domain.AssistantSession{ID: "draft-chat", ProjectID: "workbench"}); err != nil { + t.Fatal(err) + } + api := New(h.repo, h.engine, tracker.NewService(), "", "") + body := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"issues_save","arguments":{"body":{"id":"draft-issue","name":"draft-issue","projectId":"workbench","title":"human_bytes 边界","workflowId":"loop-b"}}}}` + c, rec := workbenchContext(user, http.MethodPost, "/mcp", bytes.NewBufferString(body)) + c.Request.Header.Set("Content-Type", "application/json") + if tc.confirm { + c.Request.Header.Set(chatSessionHeader, "draft-chat") + } + api.ServeHTTP(rec, c.Request) + var reply struct { + Result struct { + IsError bool `json:"isError"` + } `json:"result"` + Error any `json:"error"` + } + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &reply) != nil || reply.Error != nil || reply.Result.IsError { + t.Fatalf("issues_save returned %d: %s", rec.Code, rec.Body.String()) + } + got, ok := h.repo.Issue(issue.ID) + if !ok || got.WorkflowID != "loop-b" { + t.Fatalf("LOOP was not switched: %+v", got) + } + kept := got.Description == issue.Description && got.Priority == issue.Priority && got.Status == issue.Status + if kept != tc.wantKept { + t.Fatalf("description=%q priority=%q status=%q, want kept=%v", got.Description, got.Priority, got.Status, tc.wantKept) + } + }) + } +} diff --git a/internal/httpapi/assistant_write.go b/internal/httpapi/assistant_write.go index 9d92b3c92..31ca90025 100644 --- a/internal/httpapi/assistant_write.go +++ b/internal/httpapi/assistant_write.go @@ -6,7 +6,9 @@ import ( "fmt" "strings" + "agentflow/internal/application" "agentflow/internal/domain" + "agentflow/internal/mcpserver" ) type assistantExecModeKey struct{} @@ -121,6 +123,25 @@ func (h *assistantHandlers) mergeIssueSaveBody(body any, path map[string]string) return base } +// assistantDraftInvoker runs /mcp tool calls. The workbench executes a draft +// the user confirmed through /mcp with the chat session header, not through +// dispatchAssistantMCPCall, so the partial-body merge auto mode applies to +// issues_save has to happen here too. Models put only the fields they change +// in the draft; without the merge, confirming "switch the LOOP" saved an empty +// description and reset priority and status to their defaults. Calls without +// the header keep the plain PUT /api/issues semantics. +type assistantDraftInvoker struct { + next mcpserver.Invoker + asst *assistantHandlers +} + +func (i assistantDraftInvoker) Invoke(ctx context.Context, op application.Operation, input mcpserver.ToolInput) (mcpserver.InvokeResult, error) { + if op.Name == "issues_save" && conversationSessionFrom(ctx) != "" { + input.Body = i.asst.mergeIssueSaveBody(input.Body, input.Path) + } + return i.next.Invoke(ctx, op, input) +} + func (h *assistantHandlers) applyAssistantDrafts(ctx context.Context, user domain.User, projectID string, drafts []assistantDraft) []assistantDraft { out := make([]assistantDraft, 0, len(drafts)) for _, draft := range drafts { diff --git a/internal/httpapi/conversation_sop.go b/internal/httpapi/conversation_sop.go index 16dbe0b4f..ac5102d89 100644 --- a/internal/httpapi/conversation_sop.go +++ b/internal/httpapi/conversation_sop.go @@ -26,10 +26,20 @@ func withConversationSession(ctx context.Context, sessionID string) context.Cont return context.WithValue(ctx, conversationSessionKey{}, strings.TrimSpace(sessionID)) } +// conversationSessionFrom returns the conversation a browser-confirmed tool +// call was drafted in, or "" for ordinary API and MCP calls. +func conversationSessionFrom(ctx context.Context) string { + if ctx == nil { + return "" + } + id, _ := ctx.Value(conversationSessionKey{}).(string) + return id +} + // requestConversation returns the ordinary conversation of // projectID a request was made from. func requestConversation(d *deps, r *http.Request, userID int64, projectID string) (domain.AssistantSession, bool) { - id, _ := r.Context().Value(conversationSessionKey{}).(string) + id := conversationSessionFrom(r.Context()) if id == "" { id = strings.TrimSpace(r.Header.Get(chatSessionHeader)) } diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 94625f789..b5f150ef9 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -740,7 +740,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.GET("/deploy/bind-cli.sh", serveBindCLIScript) g.GET("/deploy/agentflow-runner", serveRunnerBinary) g.GET("/deploy/agentflow-gate-mcp", serveGateMCPBinary) - mcpHandler := mcpserver.New(mcpserver.LocalInvoker{Handler: g}).HTTPHandler() + mcpHandler := mcpserver.New(assistantDraftInvoker{next: mcpserver.LocalInvoker{Handler: g}, asst: asst}).HTTPHandler() g.Any("/mcp", func(c *gin.Context) { ctx := withConversationSession(c.Request.Context(), c.GetHeader(chatSessionHeader)) mcpHandler.ServeHTTP(c.Writer, c.Request.WithContext(ctx)) diff --git a/web/app/issue-drawer.js b/web/app/issue-drawer.js index c3cf398e1..be09787af 100644 --- a/web/app/issue-drawer.js +++ b/web/app/issue-drawer.js @@ -533,7 +533,7 @@ function issueTriggerLabel(issue,data,convo){ return issueWithoutSOP(issue)?'对话处理':'尚未触发'; } function overviewPane(issue,data){ - const project=(state.data.projects||[]).find(p=>p.id===issue.projectId),workflow=(state.data.workflows||[]).find(w=>w.id===(issue.workflowId||project?.workflowId)),repo=(state.data.repositories||[]).find(r=>r.id===(issue.repositoryId||project?.defaultRepositoryId)); + const project=(state.data.projects||[]).find(p=>p.id===issue.projectId),workflow=(state.data.workflows||[]).find(w=>w.id===(issue.workflowId||project?.workflowId)),repos=issueBoundRepositories(issue,project); // 对话工作区不是 LOOP 运行:不提供运行、日志和 LOOP 操作入口。 const convo=conversationWorkspaceIssue(issue,data.run); const run=convo?null:data.run,out=issueOutcome(issue),stage=issueCurrentStage(issue),task=data.task; @@ -553,7 +553,7 @@ function overviewPane(issue,data){ const ch=convo?conversationHeadState(issue):null; const banner=ch?`
对话交付${escapeHTML(ch.label)}

${escapeHTML(ch.hint||'')}

${actions}
` :`
${escapeHTML(out.title)}

${escapeHTML(out.body)}

${actions}
`; - const facts=`
${drawerFact('责任人',issueAssigneeName(issue)||'未指定')}${drawerFact('优先级',issuePriorityLabel(issue.priority))}${drawerFact('来源',issueSourceLabel(issue))}${metricsIssueSource(issue)==='local'?drawerFact('统计关联 TAPD',escapeHTML(issue.tapdId||'未绑定(仍参与统计)')):''}${drawerFact('触发方式',escapeHTML(issueTriggerLabel(issue,data,convo)))}${drawerFact('关联 LOOP',convo?'无 · 对话里直接改代码':(issueWithoutSOP(issue)?'不使用 LOOP':escapeHTML(workflow?.name||'未关联')))}${drawerFact('代码仓库',escapeHTML(repo?.name||'未绑定'))}${convo?drawerFact('工作分支',escapeHTML(conversationWorkBranchNames(issue,data)||'—')):drawerFact('继续开发分支',escapeHTML(storedIssueWorkBranch(issue)||'自动新建'))}
`; + const facts=`
${drawerFact('责任人',issueAssigneeName(issue)||'未指定')}${drawerFact('优先级',issuePriorityLabel(issue.priority))}${drawerFact('来源',issueSourceLabel(issue))}${metricsIssueSource(issue)==='local'?drawerFact('统计关联 TAPD',escapeHTML(issue.tapdId||'未绑定(仍参与统计)')):''}${drawerFact('触发方式',escapeHTML(issueTriggerLabel(issue,data,convo)))}${drawerFact('关联 LOOP',convo?'无 · 对话里直接改代码':(issueWithoutSOP(issue)?'不使用 LOOP':escapeHTML(workflow?.name||'未关联')))}${drawerFact('代码仓库',escapeHTML(repos.map(r=>r.name).join('、')||'未绑定'))}${convo?drawerFact('工作分支',escapeHTML(conversationWorkBranchNames(issue,data)||'—')):drawerFact('继续开发分支',escapeHTML(storedIssueWorkBranch(issue)||'自动新建'))}
`; const description=issue.description?`
${renderRequirementMarkdown(issue.description)}
`:''; const images=(data.images||[]).map(image=>{ const url=`/api/issues/${encodeURIComponent(issue.id)}/images/${encodeURIComponent(image.id)}`; @@ -728,7 +728,7 @@ function conversationRepoCards(issue,data){ const lower=s=>String(s||'').toLowerCase(); const cards=branches.map(b=>({name:b.repository||'仓库',path:pathOf(b.webUrl),webUrl:b.webUrl,work:b.workBranch,base:b.baseBranch,mrs:[]})); mrs.forEach(mr=>{ - const project=String(mr.project||''),repo=lower(mr.repository||project.split('/').pop()); + const project=repoPathLabel(mr.project),repo=lower(mr.repository||project.split('/').pop()); let card=cards.find(c=>(project&&lower(c.path)===lower(project))||lower(c.name)===repo); if(!card){card={name:mr.repository||project.split('/').pop()||'仓库',path:project,webUrl:'',work:'',base:'',mrs:[]};cards.push(card)} const mrRoot=String(mr.url||'').match(/^(https?:\/\/.+?)\/(?:(?:-\/)?merge_requests|pull)\//)?.[1]; @@ -754,7 +754,7 @@ function conversationRepoCards(issue,data){ const tail=!target?'':target===c.work?'直接提交在这个分支上':`${escapeHTML(target)}`; const flow=`
${work}${tail}
`; const acts=[ - ...c.mrs.map(m=>{const pr=/\/pull\/\d+/.test(String(m.url||'')),iid=m.iid||String(m.url).match(/(?:merge_requests|pull)\/(\d+)/)?.[1]||'';return `${escapeHTML(iid?(pr?`PR #${iid}`:`MR !${iid}`):(pr?'打开 PR':'打开 MR'))} ↗`}), + ...c.mrs.map(m=>{const ref=deliveryMRRef(m),word=deliveryMRWord(m);return `${escapeHTML(ref?`${word} ${ref}`:`打开 ${word}`)} ↗`}), links.compare?`查看改动 ↗`:'' ].filter(Boolean).join(''); return `
${name}${badge}
${flow}${acts?`
${acts}
`:''}
`; @@ -865,9 +865,9 @@ function deliveryRepoFacts(issue,repos){ const mrs=deliveryMRList(issue),multi=repos.length>1; return repos.map(r=>{ const mr=mrs.find(m=>(m.repositoryId&&m.repositoryId===r.id)||(r.project&&String(m.project||'').toLowerCase()===r.project.toLowerCase())); - const iid=mr&&(mr.iid||String(mr.url).match(/merge_requests\/(\d+)/)?.[1]); - const link=(label,url)=>`
${label}${escapeHTML(url===mr?.url&&iid?`!${iid}`:'打开')} ↗
`; - const grid=`
${multi?'':drawerFact('仓库',escapeHTML(r.name))}${drawerFact('仓库路径',escapeHTML(r.project||'—'))}${drawerFact('配置主分支',escapeHTML(r.defaultBranch||'—'))}${drawerFact('目标主分支',escapeHTML(r.baseBranch||'—'))}${drawerFact('工作分支',escapeHTML(r.workBranch||'待新建'))}${mr?link('交付 PR',mr.url):''}${r.webUrl?link('仓库链接',r.webUrl):''}
`; + const ref=mr?deliveryMRRef(mr):''; + const link=(label,url)=>`
${label}${escapeHTML(url===mr?.url&&ref?ref:'打开')} ↗
`; + const grid=`
${multi?'':drawerFact('仓库',escapeHTML(r.name))}${drawerFact('仓库路径',escapeHTML(repoPathLabel(r.project)||'—'))}${drawerFact('配置主分支',escapeHTML(r.defaultBranch||'—'))}${drawerFact('目标主分支',escapeHTML(r.baseBranch||'—'))}${drawerFact('工作分支',escapeHTML(r.workBranch||'待新建'))}${mr?link(`交付 ${deliveryMRWord(mr)}`,mr.url):''}${r.webUrl?link('仓库链接',r.webUrl):''}
`; return multi?`
${escapeHTML(r.name)}
${grid}
`:grid; }).join(''); } diff --git a/web/app/issue-model.js b/web/app/issue-model.js index 4e752fabc..f87929622 100644 --- a/web/app/issue-model.js +++ b/web/app/issue-model.js @@ -354,23 +354,36 @@ function issueExternallyDone(i){ function deliveryMRLinked(i){return deliveryMRList(i).length>0} // 待处理 MR:已创建但还没合入的 MR(opened/reopened)。状态未知的历史 MR 不计入,避免数字虚高。 function pendingDeliveryMRCount(i){return deliveryMRList(i).filter(m=>['opened','reopened'].includes(String(m.state||'').toLowerCase())).length} +// 需求绑定的仓库,主仓库在前;一个都没绑时按项目默认仓库算。需求列表和详情概览共用。 +function issueBoundRepositories(i,project){ + const ids=i?.repositoryIds||[],main=i?.repositoryId; + const bound=(state.data.repositories||[]).filter(x=>ids.includes(x.id)||x.id===main||(!(ids.length||main)&&x.id===project?.defaultRepositoryId)); + return [bound.find(x=>x.id===main),...bound.filter(x=>x.id!==main)].filter(Boolean); +} // 多仓库交付每个仓库一个 MR;旧数据只有 deliveryMrUrl。 function deliveryMRList(i){ - const withRef=m=>{const hit=String(m.url).match(/^https?:\/\/[^/]+\/(.+?)(?:\/-)?\/merge_requests\/(\d+)/);return{...m,project:m.project||hit?.[1]||'',iid:m.iid||Number(hit?.[2])||0}}; + // GitHub PR 的仓库键与后端一致写成 github:owner/repo(domain.ParseGongfengMRs)。 + const withRef=m=>{const url=String(m.url),hit=url.match(/^https?:\/\/[^/]+\/(.+?)(?:\/-)?\/merge_requests\/(\d+)/),pull=url.match(/^https?:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/(\d+)/i);return{...m,project:m.project||hit?.[1]||(pull?`github:${pull[1]}`:''),iid:m.iid||Number(hit?.[2]||pull?.[2])||0}}; const list=(i?.deliveryMrs||[]).filter(m=>String(m?.url||'').trim()); if(list.length)return list.map(withRef); const url=String(i?.deliveryMrUrl||'').trim(); return url?[withRef({url,state:i?.deliveryMrState||''})]:[]; } const deliveryMRStateText={merged:'已合入',integrated:'已合入基线',opened:'待合入',reopened:'待合入',closed:'已关闭'}; +// GitHub 的合并请求叫 PR、编号写 #3;工蜂叫 MR、编号写 !3。GitHub 仓库在平台里存成 github:owner/repo。 +function deliveryMRIsPR(mr){return /\/pull\/\d+/.test(String(mr?.url||''))||String(mr?.project||'').startsWith('github:')} +function deliveryMRWord(mr){return deliveryMRIsPR(mr)?'PR':'MR'} +function deliveryMRRef(mr){const iid=Number(mr?.iid)||0;return iid?`${deliveryMRIsPR(mr)?'#':'!'}${iid}`:''} +// 仓库路径给人看时去掉平台内部的 github: 前缀。 +function repoPathLabel(project){return String(project||'').replace(/^github:/,'')} function deliveryMRButtons(issue,{cls='button ghost small'}={}){ const list=deliveryMRList(issue); return list.map(mr=>{ - const iid=mr.iid||String(mr.url).match(/merge_requests\/(\d+)/)?.[1]||''; - const repo=mr.repository||String(mr.project||'').split('/').pop(); - const label=list.length>1?`打开 MR · ${repo||'仓库'}${iid?` !${iid}`:''}`:'打开 MR'; + const ref=deliveryMRRef(mr),word=deliveryMRWord(mr); + const repo=mr.repository||repoPathLabel(mr.project).split('/').pop(); + const label=list.length>1?`打开 ${word} · ${repo||'仓库'}${ref?` ${ref}`:''}`:`打开 ${word}`; const st=deliveryMRStateText[String(mr.state||'').toLowerCase()]; - return `${escapeHTML(label)} ↗`; + return `${escapeHTML(label)} ↗`; }).join(''); } function deliveryLockedLabel(i){ diff --git a/web/app/issues.js b/web/app/issues.js index 00c7bef2e..b7132f3e1 100644 --- a/web/app/issues.js +++ b/web/app/issues.js @@ -379,7 +379,7 @@ function issueListProgress(i,run,w){ return raw; } function issueRow(i){ - const {project:p,run,workflow:w}=issueExecution(i),boundRepos=(state.data.repositories||[]).filter(x=>(i.repositoryIds||[]).includes(x.id)||x.id===i.repositoryId||(!((i.repositoryIds||[]).length||i.repositoryId)&&x.id===p?.defaultRepositoryId)),issueRepos=[boundRepos.find(x=>x.id===i.repositoryId),...boundRepos.filter(x=>x.id!==i.repositoryId)].filter(Boolean),repo=issueRepos[0],repoLabel=issueRepos.length>1?`${repo?.name||'未绑定'} 等${issueRepos.length}个`:repo?.name||'未绑定',health=issueRunHealth(i),stage=issueCurrentStage(i),progress=issueListProgress(i,run,w); + const {project:p,run,workflow:w}=issueExecution(i),issueRepos=issueBoundRepositories(i,p),repo=issueRepos[0],repoLabel=issueRepos.length>1?`${repo?.name||'未绑定'} 等${issueRepos.length}个`:repo?.name||'未绑定',health=issueRunHealth(i),stage=issueCurrentStage(i),progress=issueListProgress(i,run,w); const sop=issueSOPLabel(i); const laneDots=issueLaneDots(i); const convo=conversationIssueProgress(i,run); diff --git a/web/i18n-en.js b/web/i18n-en.js index bcbb89c8d..317235df7 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -1094,4 +1094,6 @@ Object.assign(window.LF_I18N_EN, { "对话处理": "Handled in chat", "在对话里澄清和改代码": "Clarify and change code in chat", "这条需求不使用 LOOP,在对话里澄清需求、直接改代码;定时任务不会自动认领它。": "This requirement uses no LOOP: clarify and change code in chat; scheduled jobs won't pick it up.", + "打开 MR": "Open MR", + "交付 MR": "Delivery MR", }); diff --git a/webtest/tests/issue-delivery-github.test.mjs b/webtest/tests/issue-delivery-github.test.mjs new file mode 100644 index 000000000..12e990bec --- /dev/null +++ b/webtest/tests/issue-delivery-github.test.mjs @@ -0,0 +1,88 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { loadApp } from '../lib/load-app.mjs'; + +// Records as the platform stores them after a LOOP opened PRs on GitHub: +// GitHub repositories carry gongfengProjectId "github:owner/repo" and the +// delivery MR keeps that key in project. +const fixture = ` + state.data.projects=[{id:'p1',name:'项目',workflowId:'wf',defaultRepositoryId:'core'}]; + state.data.workflows=[{id:'wf',name:'缺陷修复',nodes:[{id:'n1',name:'实现'}],edges:[]}]; + state.data.repositories=[ + {id:'core',projectId:'p1',provider:'github',name:'acme/convkit',gongfengProjectId:'github:acme/convkit',webUrl:'https://github.com/acme/convkit',defaultBranch:'main'}, + {id:'docs',projectId:'p1',provider:'github',name:'acme/convkit-docs',gongfengProjectId:'github:acme/convkit-docs',webUrl:'https://github.com/acme/convkit-docs',defaultBranch:'main'}, + {id:'gf',projectId:'p1',provider:'gongfeng',name:'g/web',gongfengProjectId:'g/web',webUrl:'https://git.example.com/g/web',defaultBranch:'master'} + ]; + state.data.tasks=[];state.data.runs=[];state.data.issues=[];state.data.agents=[]; + const pr=(repo,iid)=>({repositoryId:repo,repository:'acme/'+(repo==='core'?'convkit':'convkit-docs'),project:'github:acme/'+(repo==='core'?'convkit':'convkit-docs'),iid,url:'https://github.com/acme/'+(repo==='core'?'convkit':'convkit-docs')+'/pull/'+iid,state:'opened',targetBranch:'main'}); + const run=(repos)=>({id:'run-1795860430327874880',workflowId:'wf',status:'succeeded',nodes:{},executionContext:{}, + repositories:repos.map(id=>({repositoryId:id,name:state.data.repositories.find(r=>r.id===id).name,baseBranch:'main',workBranch:'feature/fix-1'}))}); + const html=s=>{const d=document.createElement('div');d.innerHTML=s;return d}; + const facts=el=>[...el.querySelectorAll('.detail-fact')].map(f=>f.querySelector('span').textContent+'='+f.querySelector('b').textContent.trim()); +`; + +test('LOOP delivery of a GitHub repository shows PR #N and the plain repository path', async (t) => { + const app = await loadApp(); + t.after(app.close); + const out = structuredClone(app.evaluate(`(() => {${fixture} + const issue={id:'gh-repo-1',projectId:'p1',source:'github',status:'done',workflowId:'wf',repositoryId:'core',repositoryIds:['core'], + deliveryMrs:[pr('core',3)],deliveryMrUrl:'https://github.com/acme/convkit/pull/3',deliveryMrState:'opened'}; + const r=run(['core']); + // A record without iid falls back to the number in the PR URL. + const legacy={...issue,deliveryMrs:[],deliveryMrUrl:'https://github.com/acme/convkit/pull/7'}; + return { + facts:facts(html(sopDeliveryPane(issue,{issue,run:r}))), + legacyFacts:facts(html(sopDeliveryPane(legacy,{issue:legacy,run:r}))), + button:html(deliveryMRButtons(issue)).textContent.trim(), + buttonTitle:html(deliveryMRButtons(issue)).querySelector('a').title, + }; + })()`)); + assert.ok(out.facts.includes('仓库路径=acme/convkit'), out.facts.join(' | ')); + assert.ok(out.facts.includes('交付 PR=#3 ↗'), out.facts.join(' | ')); + assert.ok(out.legacyFacts.includes('交付 PR=#7 ↗'), out.legacyFacts.join(' | ')); + assert.equal(out.button, '打开 PR ↗'); + assert.equal(out.buttonTitle, 'acme/convkit · 待合入'); + assert.ok(!out.facts.some(f => f.includes('github:') || f.includes('!3')), out.facts.join(' | ')); +}); + +test('multi-repository requirements list every bound repository and label each PR', async (t) => { + const app = await loadApp(); + t.after(app.close); + const out = structuredClone(app.evaluate(`(() => {${fixture} + const issue={id:'issue-5',projectId:'p1',source:'local',status:'done',workflowId:'wf',repositoryId:'core',repositoryIds:['core','docs'], + deliveryMrs:[pr('core',5),pr('docs',1)],deliveryMrState:'opened'}; + state.data.issues=[issue]; + const r=run(['core','docs']); + const overview=facts(html(overviewPane(issue,{issue,run:r}))); + const delivery=html(sopDeliveryPane(issue,{issue,run:r})); + return { + repoFact:overview.find(f=>f.startsWith('代码仓库=')), + perRepo:[...delivery.querySelectorAll('.delivery-repo')].map(el=>el.querySelector('.delivery-repo-name').textContent+':'+facts(el).filter(f=>/仓库路径|交付/.test(f)).join(',')), + buttons:[...html(deliveryMRButtons(issue)).querySelectorAll('a')].map(a=>a.textContent.trim()), + bound:issueBoundRepositories(issue,state.data.projects[0]).map(r=>r.id), + fallback:issueBoundRepositories({id:'x',projectId:'p1'},state.data.projects[0]).map(r=>r.id), + }; + })()`)); + assert.equal(out.repoFact, '代码仓库=acme/convkit、acme/convkit-docs'); + assert.deepEqual(out.perRepo, [ + 'acme/convkit:仓库路径=acme/convkit,交付 PR=#5 ↗', + 'acme/convkit-docs:仓库路径=acme/convkit-docs,交付 PR=#1 ↗', + ]); + assert.deepEqual(out.buttons, ['打开 PR · acme/convkit #5 ↗', '打开 PR · acme/convkit-docs #1 ↗']); + assert.deepEqual(out.bound, ['core', 'docs']); + assert.deepEqual(out.fallback, ['core']); +}); + +test('Gongfeng merge requests keep the MR !N wording', async (t) => { + const app = await loadApp(); + t.after(app.close); + const out = structuredClone(app.evaluate(`(() => {${fixture} + const issue={id:'gf-1',projectId:'p1',source:'gongfeng',status:'done',workflowId:'wf',repositoryId:'gf',repositoryIds:['gf'], + deliveryMrs:[{repositoryId:'gf',repository:'web',url:'https://git.example.com/g/web/-/merge_requests/9',state:'merged',targetBranch:'master'}],deliveryMrState:'merged'}; + const r=run(['gf']); + return {facts:facts(html(sopDeliveryPane(issue,{issue,run:r}))),button:html(deliveryMRButtons(issue)).textContent.trim()}; + })()`)); + assert.ok(out.facts.includes('仓库路径=g/web'), out.facts.join(' | ')); + assert.ok(out.facts.includes('交付 MR=!9 ↗'), out.facts.join(' | ')); + assert.equal(out.button, '打开 MR ↗'); +});