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: 2 additions & 0 deletions internal/domain/issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ func (i Issue) IdentityBlock() string {
b.WriteString("TAPD")
case "gongfeng":
b.WriteString("工蜂")
case "github":
b.WriteString("GitHub")
default:
b.WriteString("本地")
}
Expand Down
25 changes: 25 additions & 0 deletions internal/domain/issue_identity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
67 changes: 67 additions & 0 deletions internal/httpapi/assistant_draft_invoker_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
21 changes: 21 additions & 0 deletions internal/httpapi/assistant_write.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"fmt"
"strings"

"agentflow/internal/application"
"agentflow/internal/domain"
"agentflow/internal/mcpserver"
)

type assistantExecModeKey struct{}
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 11 additions & 1 deletion internal/httpapi/conversation_sop.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
2 changes: 1 addition & 1 deletion internal/httpapi/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
14 changes: 7 additions & 7 deletions web/app/issue-drawer.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -553,7 +553,7 @@ function overviewPane(issue,data){
const ch=convo?conversationHeadState(issue):null;
const banner=ch?`<div class="issue-outcome conv-outcome ${escapeHTML(ch.tone)}"><span class="conv-outcome-kicker">对话交付</span><b>${escapeHTML(ch.label)}</b><p>${escapeHTML(ch.hint||'')}</p><div class="issue-outcome-actions">${actions}</div></div>`
:`<div class="issue-outcome ${out.key}"><b>${escapeHTML(out.title)}</b><p>${escapeHTML(out.body)}</p><div class="issue-outcome-actions">${actions}</div></div>`;
const facts=`<div class="detail-grid">${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)||'自动新建'))}</div>`;
const facts=`<div class="detail-grid">${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)||'自动新建'))}</div>`;
const description=issue.description?`<div class="markdown-body">${renderRequirementMarkdown(issue.description)}</div>`:'';
const images=(data.images||[]).map(image=>{
const url=`/api/issues/${encodeURIComponent(issue.id)}/images/${encodeURIComponent(image.id)}`;
Expand Down Expand Up @@ -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];
Expand All @@ -754,7 +754,7 @@ function conversationRepoCards(issue,data){
const tail=!target?'':target===c.work?'<span class="conv-flow-note">直接提交在这个分支上</span>':`<span class="conv-arrow" aria-hidden="true">→</span><span class="conv-branch is-base" title="目标分支">${escapeHTML(target)}</span>`;
const flow=`<div class="conv-repo-flow">${work}${tail}</div>`;
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 `<a class="button ghost small" href="${escapeHTML(safeURL(m.url))}" ${newTab}>${escapeHTML(iid?(pr?`PR #${iid}`:`MR !${iid}`):(pr?'打开 PR':'打开 MR'))} ↗</a>`}),
...c.mrs.map(m=>{const ref=deliveryMRRef(m),word=deliveryMRWord(m);return `<a class="button ghost small" href="${escapeHTML(safeURL(m.url))}" ${newTab}>${escapeHTML(ref?`${word} ${ref}`:`打开 ${word}`)} ↗</a>`}),
links.compare?`<a class="button ghost small" href="${escapeHTML(safeURL(links.compare))}" ${newTab} title="${escapeHTML(target)}...${escapeHTML(c.work)}">查看改动 ↗</a>`:''
].filter(Boolean).join('');
return `<div class="conv-repo"><div class="conv-repo-head">${name}${badge}</div>${flow}${acts?`<div class="conv-repo-actions">${acts}</div>`:''}</div>`;
Expand Down Expand Up @@ -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)=>`<div class="detail-fact"><span>${label}</span><b><a href="${escapeHTML(safeURL(url))}" target="_blank" rel="noopener noreferrer">${escapeHTML(url===mr?.url&&iid?`!${iid}`:'打开')} ↗</a></b></div>`;
const grid=`<div class="detail-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):''}</div>`;
const ref=mr?deliveryMRRef(mr):'';
const link=(label,url)=>`<div class="detail-fact"><span>${label}</span><b><a href="${escapeHTML(safeURL(url))}" target="_blank" rel="noopener noreferrer">${escapeHTML(url===mr?.url&&ref?ref:'打开')} ↗</a></b></div>`;
const grid=`<div class="detail-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):''}</div>`;
return multi?`<div class="delivery-repo"><div class="delivery-repo-name">${escapeHTML(r.name)}</div>${grid}</div>`:grid;
}).join('');
}
Expand Down
23 changes: 18 additions & 5 deletions web/app/issue-model.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<a class="${cls}" href="${escapeHTML(safeURL(mr.url))}" target="_blank" rel="noopener noreferrer" title="${escapeHTML([mr.project,st].filter(Boolean).join(' · ')||mr.url)}">${escapeHTML(label)} ↗</a>`;
return `<a class="${cls}" href="${escapeHTML(safeURL(mr.url))}" target="_blank" rel="noopener noreferrer" title="${escapeHTML([repoPathLabel(mr.project),st].filter(Boolean).join(' · ')||mr.url)}">${escapeHTML(label)} ↗</a>`;
}).join('');
}
function deliveryLockedLabel(i){
Expand Down
2 changes: 1 addition & 1 deletion web/app/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions web/i18n-en.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading