Skip to content
Merged
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
17 changes: 12 additions & 5 deletions chatbot/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,8 @@ function LiveMessage({ live, generation, finished = false, local = false, readOn
function readIssueMention() {
const params = new URLSearchParams(location.search);
const issueId = params.get("mentionIssue") || "";
return issueId ? { issueId, projectId: params.get("projectId") || "" } : null;
const intent = params.get("mentionIntent") || "";
return issueId ? { issueId, projectId: params.get("projectId") || "", ...(intent ? { intent } : {}) } : null;
}

function RenameSessionDialog({ session, rename, onClose }) {
Expand Down Expand Up @@ -713,10 +714,11 @@ export default function App() {
if (event.data?.type !== "agentflow-chat-mention-issue") return;
const issueId = String(event.data.issueId || "");
const projectId = String(event.data.projectId || "");
const intent = String(event.data.intent || "");
if (!issueId || !projectId) return;
chat.startProjectDraft(projectId);
setIssueDraft({ issueId, projectId });
setIssueMention({ issueId, projectId });
setIssueMention({ issueId, projectId, ...(intent ? { intent } : {}) });
};
window.addEventListener("message", listener);
return () => window.removeEventListener("message", listener);
Expand Down Expand Up @@ -744,16 +746,20 @@ export default function App() {
projectId: issue.projectId,
};
const value = insertMention("", { start: 0, end: 0 }, ref);
setText(value.text);
const initialText = issueMention.intent === "clarify"
? `${value.text}帮我澄清这个需求`
: value.text;
const initialCaret = initialText.length;
setText(initialText);
setReferences([ref]);
setMention(null);
const editor = input.current;
requestAnimationFrame(() => {
// Preserve the user’s focus if they interacted during the handoff.
if (draftReady.current !== draftKey || !editor?.isConnected || editor.value !== value.text) return;
if (draftReady.current !== draftKey || !editor?.isConnected || editor.value !== initialText) return;
if (document.activeElement !== focusBeforeHandoff) return;
editor.focus();
editor.setSelectionRange(value.caret, value.caret);
editor.setSelectionRange(initialCaret, initialCaret);
});
})
.catch((e) => current && chat.setError(e.message))
Expand All @@ -762,6 +768,7 @@ export default function App() {
setIssueMention(null);
const url = new URL(location.href);
url.searchParams.delete("mentionIssue");
url.searchParams.delete("mentionIntent");
history.replaceState({}, "", url);
});
return () => {
Expand Down
37 changes: 37 additions & 0 deletions chatbot/tests/app-render.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,43 @@ describe("App", () => {
}
});

test("create-and-clarify handoff pre-fills a clarify prompt and cleans mentionIntent", async () => {
const previous = { ...chat };
const originalFetch = globalThis.fetch;
const issues = {
i1: { id: "i1", title: "导出 CSV", projectId: "p1" },
i2: { id: "i2", title: "筛选条件", projectId: "p1" },
};
globalThis.fetch = vi.fn(async (path) => ({
ok: true,
status: 200,
json: async () => ({ issue: issues[decodeURIComponent(String(path).split("/").pop())] }),
}));
Object.assign(chat, { projectId: "p1", startProjectDraft: vi.fn() });
history.replaceState({}, "", "/?projectId=p1&mentionIssue=i1&mentionIntent=clarify");
let view;
try {
view = render(<App />);
const box = screen.getByRole("textbox");
await waitFor(() => expect(box.value).toBe("@导出 CSV 帮我澄清这个需求"));
expect(new URLSearchParams(location.search).has("mentionIssue")).toBe(false);
expect(new URLSearchParams(location.search).has("mentionIntent")).toBe(false);

window.dispatchEvent(new MessageEvent("message", {
data: { type: "agentflow-chat-mention-issue", issueId: "i2", projectId: "p1", intent: "clarify" },
origin: location.origin,
source: window.parent,
}));
await waitFor(() => expect(box.value).toBe("@筛选条件 帮我澄清这个需求"));
} finally {
view?.unmount();
globalThis.fetch = originalFetch;
Object.assign(chat, previous);
delete chat.startProjectDraft;
localStorage.clear();
}
});

test("a requirement handoff keeps the project's unsent new-conversation draft", async () => {
const previous = { ...chat };
const originalFetch = globalThis.fetch;
Expand Down
130 changes: 130 additions & 0 deletions internal/httpapi/assistant_mention_issue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"strings"
"testing"

"agentflow/internal/domain"
Expand Down Expand Up @@ -81,3 +82,132 @@ func TestTurnRefusesAConcurrentIssueRebinding(t *testing.T) {
t.Fatal("a turn started over a concurrent issue rebinding")
}
}

func TestIssueReferenceAndTurnContextIncludeBoundSOPAndDeliveryMode(t *testing.T) {
h, u := workbenchFixture(t)
if err := h.repo.PutWorkflow(domain.WorkflowDefinition{
ID: "wf-fe",
ProjectID: "workbench",
Name: "前端交付",
Status: "published",
}); err != nil {
t.Fatal(err)
}
if err := h.repo.PutWorkflow(domain.WorkflowDefinition{
ID: "wf-be",
ProjectID: "workbench",
Name: "后端交付",
Status: "published",
}); err != nil {
t.Fatal(err)
}
for _, issue := range []domain.Issue{
{
ID: "issue-single-sop",
ProjectID: "workbench",
Title: "列表导出 CSV",
Status: "backlog",
WorkflowID: "wf-fe",
BaseBranch: "release/v1",
},
{
ID: "issue-chain-sop",
ProjectID: "workbench",
Title: "全栈报表",
Status: "backlog",
SOPBindings: []domain.IssueSOPBinding{
{WorkflowID: "wf-fe", Order: 1},
{WorkflowID: "wf-be", Order: 2},
},
},
{
ID: "issue-no-sop",
ProjectID: "workbench",
Title: "直接改样式",
Status: "backlog",
SOPMode: domain.IssueSOPNone,
},
} {
if err := h.repo.PutIssue(issue); err != nil {
t.Fatal(err)
}
}
if err := h.repo.PutAssistantSession(u.ID, domain.AssistantSession{ID: "sop-context-chat", ProjectID: "workbench"}); err != nil {
t.Fatal(err)
}

c, _ := workbenchContext(u, "POST", "/", bytes.NewBuffer(nil))
req := assistantRequest{
SessionID: "sop-context-chat",
ProjectID: "workbench",
Messages: []assistantMessage{{
Role: "user",
Content: "@列表导出 CSV",
References: []domain.AssistantReference{{Type: "issue", ID: "issue-single-sop"}},
}},
}
if err := h.prepareWorkbenchContext(c, &req, u); err != nil {
t.Fatal(err)
}
for _, want := range []string{
`"workflowId":"wf-fe"`,
`"boundSops":[{"name":"前端交付","workflowId":"wf-fe"}]`,
`"baseBranch":"release/v1"`,
"已绑定 LOOP:前端交付(wf-fe)",
"不要再反问用户「直接改代码还是走 LOOP」",
} {
if !strings.Contains(req.contextText, want) {
t.Fatalf("single-SOP context missing %q:\n%s", want, req.contextText)
}
}

// Subsequent turn without explicit @-mention still sees the linked issue's bound SOP.
followUp := assistantRequest{
SessionID: "sop-context-chat",
ProjectID: "workbench",
Messages: []assistantMessage{{Role: "user", Content: "补充一下导出字段"}},
}
if err := h.prepareWorkbenchContext(c, &followUp, u); err != nil {
t.Fatal(err)
}
for _, want := range []string{
`"boundSops":[{"name":"前端交付","workflowId":"wf-fe"}]`,
"已绑定 LOOP:前端交付(wf-fe)",
} {
if !strings.Contains(followUp.contextText, want) {
t.Fatalf("follow-up context missing %q:\n%s", want, followUp.contextText)
}
}

// Multi-step SOP bindings keep chain order.
chainReq := assistantRequest{
ProjectID: "workbench",
Messages: []assistantMessage{{
Role: "user",
Content: "@全栈报表",
References: []domain.AssistantReference{{Type: "issue", ID: "issue-chain-sop"}},
}},
}
if err := h.prepareWorkbenchContext(c, &chainReq, u); err != nil {
t.Fatal(err)
}
if !strings.Contains(chainReq.contextText, "已绑定 LOOP:前端交付(wf-fe) → 后端交付(wf-be)") {
t.Fatalf("chain SOP context missing bound chain:\n%s", chainReq.contextText)
}

// Explicit no-SOP mode reports sopMode=none without boundSops.
noSOPReq := assistantRequest{
ProjectID: "workbench",
Messages: []assistantMessage{{
Role: "user",
Content: "@直接改样式",
References: []domain.AssistantReference{{Type: "issue", ID: "issue-no-sop"}},
}},
}
if err := h.prepareWorkbenchContext(c, &noSOPReq, u); err != nil {
t.Fatal(err)
}
if !strings.Contains(noSOPReq.contextText, `"sopMode":"none"`) || strings.Contains(noSOPReq.contextText, `"boundSops"`) || !strings.Contains(noSOPReq.contextText, "交付方式:不使用 LOOP") {
t.Fatalf("no-SOP context unexpected:\n%s", noSOPReq.contextText)
}
}
98 changes: 79 additions & 19 deletions internal/httpapi/assistant_workbench.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,22 @@ func (h *assistantHandlers) workbenchReference(ref domain.AssistantReference, pr
break
}
ref.Name = v.Title
data = gin.H{"id": v.ID, "title": v.Title, "description": v.Description, "status": v.Status, "projectId": v.ProjectID,
issueData := gin.H{"id": v.ID, "title": v.Title, "description": v.Description, "status": v.Status, "projectId": v.ProjectID,
"repositoryId": v.RepositoryID, "repositoryIds": v.RepositoryIDs}
if branch := strings.TrimSpace(v.BaseBranch); branch != "" {
issueData["baseBranch"] = branch
}
if v.WithoutSOP() {
issueData["sopMode"] = domain.IssueSOPNone
} else {
if wfID := strings.TrimSpace(v.WorkflowID); wfID != "" {
issueData["workflowId"] = wfID
}
if bound := h.issueBoundSOPs(v); len(bound) > 0 {
issueData["boundSops"] = bound
}
}
data = issueData
case "sop":
v, ok := h.repo.Workflow(ref.ID)
if !ok || !(v.Generic && project != "" || allowed(v.ProjectID, v.Shared)) {
Expand Down Expand Up @@ -1269,35 +1283,75 @@ func runNodeAgentID(r domain.Run, id string) string {
return ""
}

func (h *assistantHandlers) issueBoundSOPs(issue domain.Issue) []gin.H {
if issue.WithoutSOP() {
return nil
}
bindings := issue.EffectiveSOPBindings()
if len(bindings) == 0 {
return nil
}
out := make([]gin.H, 0, len(bindings))
for _, b := range bindings {
item := gin.H{"workflowId": b.WorkflowID}
if wf, ok := h.repo.Workflow(b.WorkflowID); ok && strings.TrimSpace(wf.Name) != "" {
item["name"] = strings.TrimSpace(wf.Name)
}
out = append(out, item)
}
return out
}

func (h *assistantHandlers) issueBoundSOPLabels(issue domain.Issue) []string {
if issue.WithoutSOP() {
return nil
}
bindings := issue.EffectiveSOPBindings()
if len(bindings) == 0 {
return nil
}
out := make([]string, 0, len(bindings))
for _, b := range bindings {
if wf, ok := h.repo.Workflow(b.WorkflowID); ok && strings.TrimSpace(wf.Name) != "" {
out = append(out, fmt.Sprintf("%s(%s)", strings.TrimSpace(wf.Name), b.WorkflowID))
} else {
out = append(out, b.WorkflowID)
}
}
return out
}

// workspaceTurnContext tells Main Bot which workspace the conversation is
// bound to, which environments it used before, and what the requirements in
// play already delivered, so it resumes the right work instead of following @
// mentions mechanically.
func (h *assistantHandlers) workspaceTurnContext(req *assistantRequest, user domain.User) string {
session, ok := h.repo.AssistantSession(assistantStorageOwner(h.repo, req.SessionID, user.ID), req.SessionID)
if !ok || session.Shared || session.RunID != "" {
if ok && (session.Shared || session.RunID != "") {
return ""
}
var b strings.Builder
current, bound := h.repo.RunState(session.WorkspaceRunID)
bound = bound && conversationMayBind(session, current, req.ProjectID)
if bound {
fmt.Fprintf(&b, "本对话当前绑定的工作区:%s。", describeConversationWorkspace(current))
if !current.IsWorkspace() {
b.WriteString(borrowedSOPNotice(current))
} else if req.ProjectID != "" {
b.WriteString("从这里派发 LOOP 会复用该工作区。如果本轮仍在使用它,派发后先结束回复,LOOP 会在工作区释放后开始。")
if ok {
current, bound := h.repo.RunState(session.WorkspaceRunID)
bound = bound && conversationMayBind(session, current, req.ProjectID)
if bound {
fmt.Fprintf(&b, "本对话当前绑定的工作区:%s。", describeConversationWorkspace(current))
if !current.IsWorkspace() {
b.WriteString(borrowedSOPNotice(current))
} else if req.ProjectID != "" {
b.WriteString("从这里派发 LOOP 会复用该工作区。如果本轮仍在使用它,派发后先结束回复,LOOP 会在工作区释放后开始。")
}
b.WriteString("\n")
}
b.WriteString("\n")
}
others := []string{}
for _, id := range ownWorkspaceRunIDs(session) {
if run, ok := h.repo.RunState(id); ok && id != session.WorkspaceRunID && run.IsWorkspace() && conversationMayBind(session, run, req.ProjectID) {
others = append(others, "- "+describeConversationWorkspace(run))
others := []string{}
for _, id := range ownWorkspaceRunIDs(session) {
if run, ok := h.repo.RunState(id); ok && id != session.WorkspaceRunID && run.IsWorkspace() && conversationMayBind(session, run, req.ProjectID) {
others = append(others, "- "+describeConversationWorkspace(run))
}
}
if len(others) > 0 {
b.WriteString("本对话之前在其他运行环境开过的工作区(传它的 sandboxProfileId 或 workspaceRunId 切回,文件和已克隆的仓库都在):\n" + strings.Join(others, "\n") + "\n")
}
}
if len(others) > 0 {
b.WriteString("本对话之前在其他运行环境开过的工作区(传它的 sandboxProfileId 或 workspaceRunId 切回,文件和已克隆的仓库都在):\n" + strings.Join(others, "\n") + "\n")
}
issues := []string{}
for _, issue := range turnIssues(h.deps, req.ProjectID, session.IssueID, lastMessageReferences(req.Messages)) {
Expand All @@ -1310,10 +1364,16 @@ func (h *assistantHandlers) workspaceTurnContext(req *assistantRequest, user dom
} else {
line += ":没跑过 LOOP"
}
if issue.WithoutSOP() {
line += ";交付方式:不使用 LOOP(在对话里澄清并直接改代码)"
} else if labels := h.issueBoundSOPLabels(issue); len(labels) > 0 {
line += ";已绑定 LOOP:" + strings.Join(labels, " → ")
}
issues = append(issues, line)
}
if len(issues) > 0 {
b.WriteString("本条消息 @ 的需求和本会话关联的主需求:\n" + strings.Join(issues, "\n") + "\n")
b.WriteString("如果需求已绑定 LOOP,说明用户已选定按该 LOOP 交付,不要再反问用户「直接改代码还是走 LOOP」或要求重新选择交付方式;用户只 @ 需求或要求澄清/分析需求时,直接结合需求描述(需要核对代码现状时可先打开工作区查看)指出模糊点、边界条件或验收标准来澄清,若需求已足够清晰则直接给出评估,并说明可先更新需求(issues_save)或准备就绪后按已绑定的 LOOP 派发(issues_dispatch)。如果需求标记为不使用 LOOP,默认围绕澄清和在对话工作区直接实现协作,不要主动建议改走 LOOP。\n")
}
if b.Len() == 0 {
return ""
Expand Down
7 changes: 4 additions & 3 deletions web/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -1578,9 +1578,10 @@ function postPendingChatIssueMention(frame){
frame.contentWindow?.postMessage({type:'agentflow-chat-mention-issue',...pendingChatIssueMention},location.origin);
pendingChatIssueMention=null;
}
function openIssueInChat(issue){
function openIssueInChat(issue,opts){
if(!issue?.id||!issue.projectId)return;
pendingChatIssueMention={issueId:issue.id,projectId:issue.projectId};
const intent=String(opts?.intent||'').trim();
pendingChatIssueMention={issueId:issue.id,projectId:issue.projectId,...(intent?{intent}:{})};
localStorage.setItem('agentflow.activeProject',issue.projectId);
const url=new URL(location.href);
['chatSession','chatIssue'].forEach(key=>url.searchParams.delete(key));
Expand Down Expand Up @@ -1687,7 +1688,7 @@ function mountNativeChat(){
const mention=pendingChatIssueMention;
pendingChatIssueMention=null;
frame.src=mention
?'/chatbot/?projectId='+encodeURIComponent(mention.projectId)+'&mentionIssue='+encodeURIComponent(mention.issueId)
?'/chatbot/?projectId='+encodeURIComponent(mention.projectId)+'&mentionIssue='+encodeURIComponent(mention.issueId)+(mention.intent?'&mentionIntent='+encodeURIComponent(mention.intent):'')
:'/chatbot/?projectId='+encodeURIComponent(projectId)+(sessionId?'&session='+encodeURIComponent(sessionId):issueId?'&issueId='+encodeURIComponent(issueId):'')+(quickAccess?'&quickAccess=1':'');
}
postNativeChatProject(frame);
Expand Down
Loading
Loading