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
15 changes: 12 additions & 3 deletions internal/httpapi/bot_clarify.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,11 @@ func (h *assistantHandlers) botClarifyMessage(ctx context.Context, bot domain.No
}

// botIssueLabel is the requirement key shown in chats (like the platform
// list: TAPD ID, 工蜂 #iid, or <project key>-<number>).
// list: TAPD ID, 工蜂 / GitHub #iid, or <project key>-<number>). Tracker
// issues keep the tracker number in issue.Number, so they must not use the
// <project key>-<number> form that platform requirements own.
func (h *assistantHandlers) botIssueLabel(issue domain.Issue) string {
if issue.Source == "gongfeng" && issue.ExternalRef != nil && issue.ExternalRef.ExternalIID > 0 {
if (issue.Source == "gongfeng" || issue.Source == "github") && issue.ExternalRef != nil && issue.ExternalRef.ExternalIID > 0 {
return "#" + strconv.Itoa(issue.ExternalRef.ExternalIID)
}
if issue.Source == "tapd" && issue.ExternalRef != nil && issue.ExternalRef.ExternalID != "" {
Expand Down Expand Up @@ -185,14 +187,18 @@ func (h *assistantHandlers) findBotClarifyIssue(bot domain.NotificationBot, conv
return issue, ""
}
project, _ := h.repo.Project(bot.ProjectID)
var matches []domain.Issue
// The displayed key is authoritative: a platform requirement LOOP-1 and a
// synced GitHub issue #1 share issue.Number, and either key names exactly
// one of them. Looser number or title matches apply only when no key does.
var exact, matches []domain.Issue
for _, issue := range h.repo.Issues() {
if issue.ProjectID != bot.ProjectID {
continue
}
label := h.botIssueLabel(issue)
switch {
case strings.EqualFold(label, ref):
exact = append(exact, issue)
case botIssueKeyPattern.MatchString(ref) && strings.EqualFold(ref, strings.TrimSpace(project.Key)+"-"+strconv.Itoa(issue.Number)):
case botIssueNumPattern.MatchString(ref) && botIssueNumPattern.FindStringSubmatch(ref)[1] == strconv.Itoa(issue.Number):
case strings.TrimSpace(issue.Title) == ref:
Expand All @@ -201,6 +207,9 @@ func (h *assistantHandlers) findBotClarifyIssue(bot domain.NotificationBot, conv
}
matches = append(matches, issue)
}
if len(exact) == 1 {
return exact[0], ""
}
if len(matches) == 1 {
return matches[0], ""
}
Expand Down
36 changes: 36 additions & 0 deletions internal/httpapi/bot_clarify_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -697,3 +697,39 @@ func TestChatClarificationRunsAsTheStarter(t *testing.T) {
t.Fatalf("analysis ran after the starter was removed: %d rounds", len(f.inputs))
}
}

// A GitHub issue synced into the project keeps the tracker number in
// issue.Number, so it shares the number of the platform requirement LOOP-7.
// Each displayed key names exactly one requirement; the bare number stays
// ambiguous and asks for a key.
func TestChatClarificationKeysOfSyncedGitHubIssues(t *testing.T) {
f := newClarifyChatFixture(t, domain.BotChannelFeishu)
if err := f.s.PutIssue(domain.Issue{ID: "gh-repo-7", ProjectID: "p", Number: 7, Kind: "issue", Source: "github", Title: "导出报表超时",
ExternalRef: &domain.ExternalRef{Source: "github", ExternalID: "990007", ExternalIID: 7, ExternalType: "issue"}}); err != nil {
t.Fatal(err)
}
local, _ := f.s.Issue("iss-7")
gh, _ := f.s.Issue("gh-repo-7")
if got := f.h.botIssueLabel(gh); got != "#7" {
t.Fatalf("GitHub issue label = %q, want #7", got)
}
if got := f.h.botIssueLabel(local); got != "LOOP-7" {
t.Fatalf("platform requirement label = %q, want LOOP-7", got)
}
for ref, want := range map[string]string{"LOOP-7": "iss-7", "loop-7": "iss-7", "#7": "gh-repo-7", "导出报表超时": "gh-repo-7"} {
issue, refusal := f.h.findBotClarifyIssue(f.bot, domain.BotConversation{}, ref)
if refusal != "" || issue.ID != want {
t.Fatalf("ref %q = %q (%s), want %s", ref, issue.ID, refusal, want)
}
}
if _, refusal := f.h.findBotClarifyIssue(f.bot, domain.BotConversation{}, "7"); !strings.Contains(refusal, "对应多个需求") {
t.Fatalf("bare number refusal = %q", refusal)
}
// Without a platform requirement of that number the old key still resolves.
if err := f.s.DeleteIssue("iss-7"); err != nil {
t.Fatal(err)
}
if issue, refusal := f.h.findBotClarifyIssue(f.bot, domain.BotConversation{}, "LOOP-7"); refusal != "" || issue.ID != "gh-repo-7" {
t.Fatalf("legacy key = %q (%s)", issue.ID, refusal)
}
}
2 changes: 1 addition & 1 deletion web/app/approvals.js
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ function approvalCardHTML(r){
const alignRun=r.workflowId==='scheduled-baseline-align'||r.workflowSnapshot?.id==='scheduled-baseline-align';
const repoName=r.repository?.name;
const title=alignRun?(repoName?`${repoName} · 确认对齐基线`:'定时任务 · 确认对齐基线'):issue?.title||r.workflowSnapshot?.name||r.workflowId;
const key=alignRun?'定时任务基线':issue?`${(state.data.projects||[]).find(p=>p.id===issue.projectId)?.key||'ISS'}-${issue.number}`:'未关联需求';
const key=alignRun?'定时任务基线':issue?issueKeyFor(issue,(state.data.projects||[]).find(p=>p.id===issue.projectId)):'未关联需求';
const keyHTML=issue&&!alignRun?`<code class="ap-key">${escapeHTML(key)}</code>`:`<span class="ap-key">${escapeHTML(key)}</span>`;
const sep='<span class="ap-sep" aria-hidden="true">·</span>';
const sideButton=issue?`<button class="button ghost small" data-open-issue="${escapeHTML(issue.id)}">打开需求</button>`:`<button class="button ghost small" data-open-logs="${escapeHTML(r.id)}">${alignRun?'查看对齐详情':'排查日志'}</button>`;
Expand Down
21 changes: 15 additions & 6 deletions web/app/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,26 @@ function normalizeIssueTitleSearch(value){
return String(value||'').normalize('NFKC').toLocaleLowerCase().replace(/[\s\p{P}\p{S}]+/gu,'');
}

// issueKeyFor is the requirement key shown everywhere (list, drawer, runs,
// approvals, search): 工蜂 and GitHub issues keep their tracker #iid, TAPD
// stories their TAPD ID, platform requirements <project key>-<number>.
// Tracker-synced issues store the tracker number in issue.number, so the
// project-key form would collide with platform requirements of the same number.
function issueKeyFor(issue,project){
const ref=issue?.externalRef;
if((issue?.source==='gongfeng'||issue?.source==='github')&&ref?.externalIid)return `#${ref.externalIid}`;
if(issue?.source==='tapd'&&ref?.externalId)return String(ref.externalId);
return `${project?.key||'ISS'}-${issue?.number||''}`;
}

function issueMatchesQuery(issue,project,query){
const raw=String(query||'').trim().toLocaleLowerCase();
if(!raw)return true;
const title=String(issue?.title||''),normalizedTitle=normalizeIssueTitleSearch(title),normalizedQuery=normalizeIssueTitleSearch(raw);
const titleTokens=raw.split(/[\s\p{P}\p{S}]+/u).map(normalizeIssueTitleSearch).filter(Boolean);
if(normalizedQuery&&normalizedTitle.includes(normalizedQuery))return true;
if(titleTokens.length&&titleTokens.every(token=>normalizedTitle.includes(token)))return true;
const key=`${project?.key||'ISS'}-${issue?.number||''}`,external=issue?.externalRef?.externalId||issue?.externalRef?.externalIid||'';
const key=issueKeyFor(issue,project),external=issue?.externalRef?.externalId||issue?.externalRef?.externalIid||'';
return `${key} ${title} ${issue?.description||''} ${external}`.toLocaleLowerCase().includes(raw);
}

Expand Down Expand Up @@ -330,10 +342,7 @@ function issueMatchesStatusFilter(issue,filter){
function issuePriorityLabel(value){return ({urgent:'紧急',high:'高',medium:'中',low:'低'}[value]||value||'—')}
function taskStatusLabel(value){return ({queued:'排队中',dispatched:'已调度',running:'运行中',completed:'已完成',failed:'失败',cancelled:'已取消'}[value]||value||'—')}
function issueKeyLabel(i){
if(i.source==='gongfeng'&&i.externalRef?.externalIid) return `#${i.externalRef.externalIid}`;
if(i.source==='tapd'&&i.externalRef?.externalId) return String(i.externalRef.externalId);
const p=(state.data.projects||[]).find(x=>x.id===i.projectId);
return `${p?.key||'ISS'}-${i.number||''}`;
return issueKeyFor(i,(state.data.projects||[]).find(x=>x.id===i?.projectId));
}
function issueKeyMarkup(i){
const raw=String(issueKeyLabel(i)||'');
Expand Down Expand Up @@ -497,7 +506,7 @@ function openIssue(issue=null){
renderIssueRepositoryBranchInputs(f.elements.baseBranch,$('#issueBaseBranchHint'),$('#issueRepositoryBranches'),selectedIssueRepositoryIds(),v.repositoryBranches||{[v.repositoryId]:storedIssueWorkBranch(v)});
f.elements.projectId.onchange=()=>{fillIssueRepositories(f.elements.projectId.value);fillIssueAssignees(f.elements.projectId.value,'');renderIssueRepositoryBranchInputs(f.elements.baseBranch,$('#issueBaseBranchHint'),$('#issueRepositoryBranches'),selectedIssueRepositoryIds(),{})};
$('#issueRepoChecks').onchange=refreshIssueBaseBranchInput;
$('#issueModalTitle').textContent=issue?`${(projects.find(p=>p.id===v.projectId)?.key||'ISS')}-${v.number} ${v.title}`:'新建工作项';
$('#issueModalTitle').textContent=issue?`${issueKeyFor(v,projects.find(p=>p.id===v.projectId))} ${v.title}`:'新建工作项';
const task=(state.data.tasks||[]).find(t=>t.id===v.latestTaskId);
let stateHtml=task?`最近任务 ${escapeHTML(task.id)} · ${taskStatusLabel(task.status)} · Run ${escapeHTML(task.runId)}`:'';
if(v.automationState==='ignored')stateHtml+=`${stateHtml?'<br>':''}定时 LOOP:<b>已忽略</b>`;
Expand Down
4 changes: 2 additions & 2 deletions web/app/runs.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ function runRowHTML(r,workflows){
const isPaused=Boolean(r.pauseRequested||r.status==='paused');
const isDeletable=r.status!=='queued'&&(!['running','waiting'].includes(r.status)||isPaused);
const sep='<span class="run-sep">·</span>';
const meta=group?`<span>${relativeTime(r.createdAt)}</span>${runTriggerChip(ctx.task)}`:`${ctx.issue?`<span class="run-ref">${escapeHTML(ctx.project?.key||'ISS')}-${escapeHTML(ctx.issue.number)}</span>${sep}`:''}<span class="run-meta-sop">${escapeHTML(sop)}</span>${sep}<span>${relativeTime(r.createdAt)}</span>${runTriggerChip(ctx.task)}`;
const meta=group?`<span>${relativeTime(r.createdAt)}</span>${runTriggerChip(ctx.task)}`:`${ctx.issue?`<span class="run-ref">${escapeHTML(issueKeyFor(ctx.issue,ctx.project))}</span>${sep}`:''}<span class="run-meta-sop">${escapeHTML(sop)}</span>${sep}<span>${relativeTime(r.createdAt)}</span>${runTriggerChip(ctx.task)}`;
const progress=group?'<div class="run-row-progress is-empty">—</div>':`<div class="run-row-progress"><span class="run-progress-text">${p.done}/${p.total}</span><div class="run-progress tone-${runStatusTone(r)}"><i style="width:${p.pct}%"></i></div></div>`;
const time=group?'<span class="run-row-time"></span>':`<span class="run-row-time" title="${escapeHTML(runTimingTitle(r))}">${runElapsed(r)}</span>`;
const actions=`<button type="button" class="run-row-action run-view-btn" data-view-run="${escapeHTML(r.id)}" aria-label="查看详情" title="查看详情">${runIconSlot('eye',15)}</button>${isDeletable?`<button type="button" class="run-row-action run-del-btn" data-delete-run="${escapeHTML(r.id)}" aria-label="删除记录" title="删除记录">${runIconSlot('trash',15)}</button>`:''}`;
Expand Down Expand Up @@ -1805,7 +1805,7 @@ function renderRunDetail(r){
const pickNodes=runIsGroupMode(r)?(graphNodes.length?graphNodes:nodes):nodes;if(!state.selectedRunNode||!pickNodes.some(n=>n.id===state.selectedRunNode)){state.selectedRunNode=pickNodes.find(n=>['running','waiting_approval','failed','cancelled'].includes(r.nodes?.[n.id]?.status))?.id||pickNodes.find(n=>r.nodes?.[n.id]?.status==='succeeded')?.id||pickNodes[0]?.id}const pg=runPageTarget(r,state.selectedRunNode);const selected=pickNodes.find(n=>n.id===state.selectedRunNode)||nodes.find(n=>n.id===state.selectedRunNode),nr=r.nodes?.[selected?.id]||{},nodeArtifacts=(r.artifacts||[]).filter(a=>a.nodeId===selected?.id),logPage=state.runLogs?.runId===pg.runId&&state.runLogs.nodeId===pg.nodeId&&state.runLogs.loaded?state.runLogs:null,telAdapter=state.runTelemetryAdapter||'live',telPage=state.runTelemetry?.runId===pg.runId&&state.runTelemetry.nodeId===pg.nodeId&&state.runTelemetry.adapter===telAdapter&&state.runTelemetry.loaded?state.runTelemetry:null,telemetry=compactTelemetry(telPage?.items||[]);
/** 首次渲染与实时更新使用同一节点活动判断。 */
const inspectorRunning=nodeInspectorIsRunning(r,selected?.id);
const issueRef=ctx.issue?`${escapeHTML(ctx.project?.key||'TASK')}-${ctx.issue.number}`:'独立运行';
const issueRef=ctx.issue?escapeHTML(issueKeyFor(ctx.issue,ctx.project)):'独立运行';
const alignPanelHTML=r.workflowId==='scheduled-baseline-align'?alignConflictPanelHTML(r):'';
const logBusy=state.runLogs?.runId===pg.runId&&state.runLogs.nodeId===pg.nodeId&&state.runLogs.loading&&!logPage;
const previewEnabled=runPreviewDeclared(r);
Expand Down
1 change: 1 addition & 0 deletions web/syntax_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2466,6 +2466,7 @@ eval(code.slice(code.indexOf('function huiIcon('), code.indexOf('// stage.key al
eval(code.slice(code.indexOf('function waitingNodeId('), code.indexOf('function failedNodeId(')));
eval(code.slice(code.indexOf('function restoredSOPResumeNode('), code.indexOf('function approvalCalloutHTML(')));
eval(code.slice(code.indexOf('function approvalStatusBadgeHTML('), code.indexOf('function closeApprovalMoreMenus(')));
eval(code.slice(code.indexOf('function issueKeyFor('), code.indexOf('function issueMatchesQuery(')));
const between = (html, from, to) => html.slice(html.indexOf(from), html.indexOf(to, html.indexOf(from)));
const node = {id:'gate', name:'confirm-brief', type:'agent'};
const waiting = {id:'run-1', status:'waiting', workflowSnapshot:{nodes:[node]}, nodes:{gate:{status:'waiting_approval'}}};
Expand Down
52 changes: 52 additions & 0 deletions webtest/tests/issue-keys.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadApp } from '../lib/load-app.mjs';

// GitHub and 工蜂 sync stores the tracker number in issue.number, so a synced
// issue and a platform requirement of the same project can both have number 1.
// Every surface must show the same, unambiguous key for each of them.
test('synced tracker issues keep their tracker key on every surface', async (t) => {
const app = await loadApp();
t.after(app.close);
const result = structuredClone(await app.evaluate(`(() => {
state.data.projects[0].key = 'SWP';
const local = {id:'local-1',projectId:'project-1',number:1,title:'title_case 吞掉连续空格',source:'local',status:'todo',priority:'medium'};
const github = {id:'gh-repo-1',projectId:'project-1',number:1,title:'word_count 全角空格',source:'github',kind:'issue',status:'todo',priority:'medium',
externalRef:{source:'github',externalId:'990001',externalIid:1,externalType:'issue'}};
const gongfeng = {id:'gf-repo-5',projectId:'project-1',number:5,title:'工蜂缺陷',source:'gongfeng',status:'todo',priority:'medium',
externalRef:{source:'gongfeng',externalId:'77005',externalIid:5}};
const tapd = {id:'tapd-1',projectId:'project-1',number:2,title:'TAPD 需求',source:'tapd',status:'todo',priority:'medium',
externalRef:{source:'tapd',externalId:'1010101'}};
const plain = {id:'p-9',projectId:'missing',number:9,title:'无项目',status:'todo'};
state.data.issues = [local, github, gongfeng, tapd];
state.projectFilter = 'project-1';
state.sourceFilter=''; state.issueStatusFilter=''; state.issueAssigneeFilter=''; state.issueRunFilter='';
const search = q => { state.issueQuery = q; return filteredIssues().map(i => i.id); };
state.data.tasks = [{id:'t1',issueId:'local-1',runId:'run-local'},{id:'t2',issueId:'gh-repo-1',runId:'run-gh'}];
const run = (id, issueId) => ({id, workflowId:'flow-1', status:'waiting', nodes:{}, createdAt:new Date().toISOString(),
executionContext:{issueId}, workflowSnapshot:{id:'flow-1', name:'LOOP', nodes:[{id:'accept',name:'人工验收',type:'approval'}]}});
const runRef = r => { const d = document.createElement('div'); d.innerHTML = runRowHTML(r, state.data.workflows || []); return d.querySelector('.run-ref')?.textContent; };
const apKey = r => { const d = document.createElement('div'); d.innerHTML = approvalCardHTML(r); return d.querySelector('.ap-key')?.textContent; };
openIssue(github);
const modalGitHub = document.querySelector('#issueModalTitle').textContent;
openIssue(local);
const modalLocal = document.querySelector('#issueModalTitle').textContent;
return {
labels: [local, github, gongfeng, tapd, plain].map(issueKeyLabel),
searchLocalKey: search('SWP-1'),
searchGitHubKey: search('#1'),
searchGongfengKey: search('#5'),
runRefs: [runRef(run('run-local','local-1')), runRef(run('run-gh','gh-repo-1'))],
approvalKeys: [apKey(run('run-local','local-1')), apKey(run('run-gh','gh-repo-1'))],
modalGitHub, modalLocal,
};
})()`));
assert.deepEqual(result.labels, ['SWP-1', '#1', '#5', '1010101', 'ISS-9']);
assert.deepEqual(result.searchLocalKey, ['local-1']);
assert.deepEqual(result.searchGitHubKey, ['gh-repo-1']);
assert.deepEqual(result.searchGongfengKey, ['gf-repo-5']);
assert.deepEqual(result.runRefs, ['SWP-1', '#1']);
assert.deepEqual(result.approvalKeys, ['SWP-1', '#1']);
assert.equal(result.modalGitHub, '#1 word_count 全角空格');
assert.equal(result.modalLocal, 'SWP-1 title_case 吞掉连续空格');
});
Loading