在个人配置中填写个人访问令牌(PAT)与 HTTPS 克隆账号,返回后继续。
+
- {repo.provider === "github" && repo.webUrl
+ {["github", "codeup"].includes(repo.provider) && repo.webUrl
? repo.webUrl.replace(
/^https?:\/\//,
"",
@@ -2098,8 +2309,8 @@ export default function QuickAccessWizard({
{projectMode === "existing" && projectRepos.length
- ? "为该项目添加 GitHub 仓库"
- : "绑定默认 GitHub 仓库"}
+ ? "为该项目添加代码仓库"
+ : "绑定默认代码仓库"}
) : (
- 支持 Git HTTPS 链接或 Git SSH 地址,例如 git@gitlab.com:group/repo.git。
+ 支持 Git HTTPS 链接或 Git SSH 地址,例如 git@gitlab.com:group/repo.git;云效仓库粘贴 https://codeup.aliyun.com/组织ID/分组/仓库.git。
)}
{selectedSSHRepo?.provider === "ssh" && sshKeysLoaded && !sshReady ? (
@@ -2346,10 +2557,10 @@ export default function QuickAccessWizard({
凭据
- {sshRepository ? "Git SSH" : "GitHub"} {(sshRepository ? sshReady : gitReady) ? "已配置" : "未配置"} ·
+ {sshRepository ? "Git SSH" : codeupRepository ? "云效 Codeup" : "GitHub"} {(sshRepository ? sshReady : codeupRepository ? codeupReady : gitReady) ? "已配置" : "未配置"} ·
CodeBuddy{" "}
{codeBuddyReady
? "已配置"
diff --git a/chatbot/src/assets/provider-logos/README.md b/chatbot/src/assets/provider-logos/README.md
index 463253741..b4112f180 100644
--- a/chatbot/src/assets/provider-logos/README.md
+++ b/chatbot/src/assets/provider-logos/README.md
@@ -10,6 +10,11 @@ The interface uses these bundled assets in both chat and configuration.
and the pinned assets were downloaded from the corresponding
`cdn.jsdelivr.net/npm/simple-icons@v16/icons/.svg` URLs.
- `pi.svg` is the official primary color mark from the [Pi press kit](https://pi.dev/press-kit).
+- `codeup.svg` is an original LoopForge monochrome placeholder glyph (a cloud
+ with code brackets) for the Yunxiao Codeup credential card, following the
+ monochrome-glyph precedent of `pi.svg`. It is not an official Alibaba Cloud
+ or Codeup mark; replace it if an official brand asset becomes available.
+ The same file is mirrored at `web/images/credentials/codeup.svg`.
- `antigravity.svg` is the full-color icon from the [Google Antigravity press assets](https://antigravity.google/press).
- `kimi-code.png` is the icon published by Moonshot AI for the [Kimi Code extension](https://marketplace.visualstudio.com/items?itemName=moonshot-ai.kimi-code).
- `qoder.svg` is the official Qoder CN brand mark, extracted from the installed
diff --git a/chatbot/src/assets/provider-logos/SOURCE.md b/chatbot/src/assets/provider-logos/SOURCE.md
index 66946a324..3c3274774 100644
--- a/chatbot/src/assets/provider-logos/SOURCE.md
+++ b/chatbot/src/assets/provider-logos/SOURCE.md
@@ -7,6 +7,9 @@ including the Pi, Antigravity, and Kimi Code product marks added separately.
`qoder.svg` is the official Qoder CN brand mark (monochrome, background
removed) extracted from the installed Qoder CN client, mirrored from
`web/images/credentials/qoder.svg`.
+`codeup.svg` is original LoopForge artwork (monochrome cloud-and-brackets
+placeholder for Yunxiao Codeup), mirrored from
+`web/images/credentials/codeup.svg`; it carries no upstream license.
ModelProviderIcon.jsx adapts Grasp's visual brand matching and theme treatment.
Its internal light animation is local presentation code. A visual brand match
diff --git a/chatbot/src/assets/provider-logos/codeup.svg b/chatbot/src/assets/provider-logos/codeup.svg
new file mode 100644
index 000000000..8c622714a
--- /dev/null
+++ b/chatbot/src/assets/provider-logos/codeup.svg
@@ -0,0 +1,5 @@
+
\ No newline at end of file
diff --git a/chatbot/src/changes.js b/chatbot/src/changes.js
index 573371072..af52a1e12 100644
--- a/chatbot/src/changes.js
+++ b/chatbot/src/changes.js
@@ -252,6 +252,10 @@ export function branchCompareUrl(repository) {
return same
? `https://github.com/${github}/tree/${refPath(work)}`
: `https://github.com/${github}/compare/${refPath(base)}...${refPath(work)}`;
+ const codeup = codeupRepoPath(repository?.cloneUrl);
+ // Codeup's compare page URL differs between editions, so both cases link to
+ // the work branch tree, which is stable across center/region deployments.
+ if (codeup) return `https://codeup.aliyun.com/${codeup}/tree/${refPath(work)}`;
const path = gongfengProjectPath(repository?.cloneUrl);
if (!path) return "";
if (same) return `https://git.example.com/${path}/-/tree/${refPath(work)}`;
@@ -269,6 +273,18 @@ export function githubRepoPath(remote) {
return match ? match[1] : "";
}
+// Codeup paths keep the organization id as the first segment and may nest
+// groups: {orgId}/{group...}/{repo}. SSH remotes map to the same HTTPS web path.
+export function codeupRepoPath(remote) {
+ const raw = String(remote || "").trim();
+ const match =
+ /^(?:git@|ssh:\/\/git@)codeup\.aliyun\.com[:/](.+?)(?:\.git)?\/?$/.exec(raw) ||
+ /^https:\/\/codeup\.aliyun\.com\/(.+?)(?:\.git)?\/?$/.exec(raw);
+ if (!match) return "";
+ const path = match[1].replace(/\.git$/, "").replace(/^\/+|\/+$/g, "");
+ return path.split("/").length >= 2 ? path : "";
+}
+
export function gongfengProjectPath(remote) {
const raw = String(remote || "").trim();
const match =
diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js
index a3ca202ee..db9925258 100644
--- a/chatbot/src/credentials.js
+++ b/chatbot/src/credentials.js
@@ -6,6 +6,7 @@ export const CREDENTIALS = {
codexApiKey: "Codex API Key",
claudeCodeApiKey: "Claude Code API Key",
gitToken: "GitHub Git Token",
+ codeupToken: "云效 Codeup 仓库授权",
gitSshKey: "Git SSH 密钥",
gitHttpCredentials: "Git 访问令牌",
};
@@ -111,6 +112,16 @@ export const CREDENTIAL_GUIDES = {
"回到这里点「重试节点」",
],
},
+ codeupToken: {
+ url: "/#/settings",
+ link: "配置云效仓库授权",
+ steps: [
+ "在云效 Codeup「个人设置 → 个人访问令牌」创建授予代码读写权限的 PAT",
+ "在「个人设置 → HTTPS 密码」查看 HTTPS 克隆账号",
+ "到「个人配置 → 云效仓库授权」填写克隆账号与令牌,保存前会自动校验",
+ "回到这里点「重试节点」",
+ ],
+ },
codeBuddyApiKey: {
url: CODEBUDDY_ENVIRONMENTS[0].keyUrl,
link: "打开 CodeBuddy 创建 Key",
@@ -156,6 +167,10 @@ const RULES = [
"gitSshKey",
/Git SSH (?:密钥|私钥)/i,
],
+ [
+ "codeupToken",
+ /Codeup|云效[^。\n]{0,12}(令牌|授权|凭据|克隆账号)/i,
+ ],
[
"gitToken",
/Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]/i,
diff --git a/chatbot/tests/conversation-runs.test.mjs b/chatbot/tests/conversation-runs.test.mjs
index b32ef96ca..6f043fa32 100644
--- a/chatbot/tests/conversation-runs.test.mjs
+++ b/chatbot/tests/conversation-runs.test.mjs
@@ -1,6 +1,6 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import { branchCompareUrl, githubRepoPath, gongfengProjectPath } from "../src/changes.js";
+import { branchCompareUrl, codeupRepoPath, githubRepoPath, gongfengProjectPath } from "../src/changes.js";
import { isConversationWorkspaceRun } from "../src/runs.js";
// 自由协作 runs and chat workspaces are not SOPs; listing them showed
@@ -35,6 +35,27 @@ test("branchCompareUrl points at the work branch on GitHub", () => {
assert.equal(githubRepoPath("https://gitlab.com/o/r.git"), "");
});
+test("branchCompareUrl points at the work branch on Codeup", () => {
+ const repository = {
+ cloneUrl: "https://codeup.aliyun.com/org123/ai/loopforge.git",
+ baseBranch: "main",
+ workBranch: "feature/fix-1",
+ };
+ // Codeup links to the work branch tree; the compare page URL is not stable.
+ assert.equal(
+ branchCompareUrl(repository),
+ "https://codeup.aliyun.com/org123/ai/loopforge/tree/feature/fix-1",
+ );
+ assert.equal(
+ branchCompareUrl({ ...repository, cloneUrl: "git@codeup.aliyun.com:org123/ai/loopforge.git", baseBranch: "" }),
+ "https://codeup.aliyun.com/org123/ai/loopforge/tree/feature/fix-1",
+ );
+ assert.equal(codeupRepoPath("https://codeup.aliyun.com/org123/ai/loopforge"), "org123/ai/loopforge");
+ assert.equal(codeupRepoPath("git@codeup.aliyun.com:org123/ai/loopforge.git"), "org123/ai/loopforge");
+ assert.equal(codeupRepoPath("https://codeup.aliyun.com/org123"), "");
+ assert.equal(codeupRepoPath("https://github.com/o/r.git"), "");
+});
+
test("branchCompareUrl points at the work branch on a legacy host", () => {
const repository = {
cloneUrl: "git@git.example.com:example/agent-flow.git",
diff --git a/chatbot/tests/credentials.test.mjs b/chatbot/tests/credentials.test.mjs
index 377c3e90a..123bbd50e 100644
--- a/chatbot/tests/credentials.test.mjs
+++ b/chatbot/tests/credentials.test.mjs
@@ -49,6 +49,8 @@ test("CodeBuddy key links follow the selected network environment", () => {
assert.match(china.link, /国内站/);
assert.deepEqual(china.steps, CREDENTIAL_GUIDES.codeBuddyApiKey.steps);
assert.equal(credentialGuide("gitToken", {}), CREDENTIAL_GUIDES.gitToken);
+ assert.equal(credentialGuide("codeupToken", {}), CREDENTIAL_GUIDES.codeupToken);
+ assert.equal(CREDENTIAL_GUIDES.codeupToken.url, "/#/settings");
assert.equal(credentialGuide("unknown", {}), null);
});
@@ -108,6 +110,16 @@ test("credential errors from the platform link to the right setting", () => {
"gitToken",
false,
],
+ [
+ "当前责任人未配置云效 Codeup 仓库授权:请先在个人配置中填写个人访问令牌与 HTTPS 克隆账号",
+ "codeupToken",
+ true,
+ ],
+ [
+ "git clone https://codeup.aliyun.com/org/group/repo.git: exit status 128: Authentication failed",
+ "codeupToken",
+ false,
+ ],
];
for (const [message, field, owner] of cases) {
const hint = credentialHint(message);
diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx
index 5883ae003..cd0041b63 100644
--- a/chatbot/tests/quick-access-wizard.test.jsx
+++ b/chatbot/tests/quick-access-wizard.test.jsx
@@ -22,6 +22,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {
if (path === "/api/projects") return [project];
if (path === "/api/repositories") return [];
if (path === "/api/users/1/git-ssh-keys") return mockState.sshKeys || [];
+ if (path === "/api/users/1/git-http-credentials") return mockState.codeupCredentials || [];
if (path === "/api/workflows")
return [
{
@@ -36,9 +37,11 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {
if (path.includes("/verify")) return { valid: true };
return [];
});
- const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null };
+ const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null, codeupCredentials: null };
const writeMock = vi.fn(async (path, body) => {
if (path.includes("/git-token/verify")) return { valid: true };
+ if (path === "/api/auth/codeup/verify") return { valid: true, login: "clone-account" };
+ if (path.includes("/git-http-credentials/") && path.endsWith("/verify")) return { valid: true, login: "clone-account" };
if (path === "/api/projects") return { ...project, ...body };
if (path.includes("/clone")) {
if (mockState.failClone) throw new Error("clone unavailable");
@@ -95,6 +98,19 @@ describe("QuickAccessWizard", () => {
expect(parseGongfengRepo("https://git.example.com/team/repo/-/tree/main")?.name).toBe("repo");
expect(parseGongfengRepo("https://example.com/team/repo")).toMatchObject({provider:"https",cloneUrl:"https://example.com/team/repo"});
expect(parseGongfengRepo("")).toBeNull();
+ // Codeup keeps the organization in the path and normalizes SSH/shorthand to HTTPS.
+ expect(parseGongfengRepo("https://codeup.aliyun.com/org123/ai/loopforge.git")).toEqual({
+ provider: "codeup",
+ host: "codeup.aliyun.com",
+ organizationId: "org123",
+ project: "codeup:org123/ai/loopforge",
+ name: "loopforge",
+ webUrl: "https://codeup.aliyun.com/org123/ai/loopforge",
+ cloneUrl: "https://codeup.aliyun.com/org123/ai/loopforge.git",
+ });
+ expect(parseGongfengRepo("git@codeup.aliyun.com:org123/ai/loopforge.git")?.provider).toBe("codeup");
+ expect(parseGongfengRepo("codeup:org123/ai/loopforge")?.cloneUrl).toBe("https://codeup.aliyun.com/org123/ai/loopforge.git");
+ expect(parseGongfengRepo("https://codeup.aliyun.com/org123/loopforge")).toBeNull();
});
test("select and switch controls respond to keyboard and pointer input", async () => {
@@ -203,7 +219,7 @@ describe("QuickAccessWizard", () => {
);
await screen.findByRole("dialog");
await userAction.click(screen.getByRole("button", { name: "下一步" }));
- expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key");
+ expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、云效 Codeup 令牌、Git SSH 密钥或 CodeBuddy API Key");
expect(screen.queryByText(/工蜂/)).toBeNull();
await userAction.click(screen.getByText("使用访问令牌(高级)"));
await userAction.type(
@@ -219,6 +235,37 @@ describe("QuickAccessWizard", () => {
mockState.unconfigured = false;
});
+ test("validates and saves a typed Codeup PAT with the HTTPS clone account", async () => {
+ mockState.unconfigured = true;
+ writeMock.mockClear();
+ const userAction = userEvent.setup();
+ render(
+ ,
+ );
+ await screen.findByRole("dialog");
+ await userAction.click(screen.getByText("直接填写令牌(高级)"));
+ await userAction.type(screen.getByLabelText("云效 HTTPS 克隆账号"), "clone-account");
+ await userAction.type(screen.getByLabelText("云效个人访问令牌"), "pt-token");
+ await userAction.click(screen.getByRole("button", { name: "校验并连接" }));
+ await waitFor(() => expect(writeMock).toHaveBeenCalledWith("/api/auth/codeup/verify", { token: "pt-token", username: "clone-account" }));
+ await waitFor(() => expect(writeMock).toHaveBeenCalledWith(
+ "/api/users/1/git-http-credentials",
+ expect.objectContaining({ host: "codeup.aliyun.com", platform: "codeup", username: "clone-account", token: "pt-token" }),
+ "PUT",
+ ));
+ // The card flips to configured without a page reload.
+ expect(await screen.findByText("管理云效授权")).toBeInTheDocument();
+ mockState.unconfigured = false;
+ });
+
test("saves a typed CodeBuddy key when moving past the credential step", async () => {
mockState.unconfigured = true;
writeMock.mockClear();
diff --git a/internal/domain/codeup_test.go b/internal/domain/codeup_test.go
new file mode 100644
index 000000000..f2837ecfa
--- /dev/null
+++ b/internal/domain/codeup_test.go
@@ -0,0 +1,69 @@
+package domain
+
+import "testing"
+
+func TestParseCodeupRepositoryURL(t *testing.T) {
+ const org = "60d54f3daccf2bbd6659f3ad"
+ wantProject := "codeup:" + org + "/team/app"
+ wantClone := "https://codeup.aliyun.com/" + org + "/team/app.git"
+ for _, raw := range []string{
+ "https://codeup.aliyun.com/" + org + "/team/app",
+ "https://codeup.aliyun.com/" + org + "/team/app.git",
+ "git@codeup.aliyun.com:" + org + "/team/app.git",
+ "ssh://git@codeup.aliyun.com/" + org + "/team/app.git",
+ "codeup:" + org + "/team/app",
+ "codeup.aliyun.com/" + org + "/team/app",
+ "git clone https://codeup.aliyun.com/" + org + "/team/app.git",
+ } {
+ got, ok := ParseRepositoryURL(raw)
+ if !ok || got.Project != wantProject || got.CloneURL != wantClone || got.Name != "app" {
+ t.Fatalf("%s: %+v %v", raw, got, ok)
+ }
+ }
+ // Nested subgroups keep the full path in the identity.
+ if got, ok := ParseRepositoryURL("https://codeup.aliyun.com/" + org + "/group/sub/app.git"); !ok || got.Project != "codeup:"+org+"/group/sub/app" {
+ t.Fatalf("nested: %+v %v", got, ok)
+ }
+ for _, raw := range []string{
+ "https://codeup.aliyun.com/" + org + "/app", // missing group segment
+ "https://codeup.aliyun.com/" + org, // org only
+ "https://codeup.aliyun.com/../team/app", // traversal
+ "https://codeup.aliyun.com/" + org + "/../app", // traversal segment
+ "https://user:secret@codeup.aliyun.com/" + org + "/team/app", // embedded credentials
+ "https://codeup.aliyun.com.attacker.invalid/" + org + "/team/app",
+ "https://github.com/" + org + "/team/app", // github stays two-segment
+ } {
+ if got, ok := ParseRepositoryURL(raw); ok && got.Project == wantProject {
+ t.Fatalf("invalid reference accepted as codeup: %s %+v", raw, got)
+ }
+ }
+}
+
+func TestParseCodeupProject(t *testing.T) {
+ org, repoPath, ok := ParseCodeupProject("codeup:60d54f3daccf2bbd6659f3ad/team/app")
+ if !ok || org != "60d54f3daccf2bbd6659f3ad" || repoPath != "60d54f3daccf2bbd6659f3ad/team/app" {
+ t.Fatalf("org=%q repoPath=%q ok=%v", org, repoPath, ok)
+ }
+ for _, project := range []string{"github:acme/web", "team/app", "codeup:org", "codeup:org/../app", "codeup:"} {
+ if _, _, ok := ParseCodeupProject(project); ok {
+ t.Fatalf("%q accepted", project)
+ }
+ }
+}
+
+func TestCodeupDeliveryMRURL(t *testing.T) {
+ const org = "60d54f3daccf2bbd6659f3ad"
+ url := "https://codeup.aliyun.com/" + org + "/team/app/change/12"
+ project, iid, got, ok := ParseDeliveryMRURL(url)
+ if !ok || project != "codeup:"+org+"/team/app" || iid != 12 || got != url {
+ t.Fatalf("ParseDeliveryMRURL = %q %d %q %v", project, iid, got, ok)
+ }
+ if built := GongfengMRURL(project, iid); built != url {
+ t.Fatalf("GongfengMRURL = %q", built)
+ }
+ // detailUrl is recovered from free text like a GitHub PR link.
+ refs := ParseGongfengMRs("Delivered " + url + " and " + url)
+ if len(refs) != 1 || refs[0].Project != project || refs[0].IID != 12 || refs[0].URL != url {
+ t.Fatalf("ParseGongfengMRs = %+v", refs)
+ }
+}
\ No newline at end of file
diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.go
index 46948438c..7d0c332bb 100644
--- a/internal/domain/delivery_mr.go
+++ b/internal/domain/delivery_mr.go
@@ -48,6 +48,9 @@ func GongfengMRURL(project string, iid int) string {
if strings.HasPrefix(project, "github:") {
return fmt.Sprintf("https://github.com/%s/pull/%d", strings.TrimPrefix(project, "github:"), iid)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return fmt.Sprintf("https://%s/%s/change/%d", CodeupRepoHost, strings.TrimPrefix(project, "codeup:"), iid)
+ }
if platform, host, path, ok := ExternalMRProject(project); ok {
if platform == GitPlatformGitHub {
return fmt.Sprintf("https://%s/%s/pull/%d", host, path, iid)
diff --git a/internal/domain/mr.go b/internal/domain/mr.go
index 97539507f..44ec84341 100644
--- a/internal/domain/mr.go
+++ b/internal/domain/mr.go
@@ -15,6 +15,10 @@ var githubPRURL = regexp.MustCompile(`https?://github\.com/([A-Za-z0-9_.-]+/[A-Z
var gongfengMRURL = regexp.MustCompile(`https?://git\.example\.com/([^\s"'<>#]+)/merge_requests/(\d+)`)
+// codeupMRURL matches a Codeup change-request detailUrl/webUrl:
+// https://codeup.aliyun.com/{orgId}/{group}/{repo}/change/{localId}.
+var codeupMRURL = regexp.MustCompile(`https?://codeup\.aliyun\.com/([A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+){2,})/change/(\d+)`)
+
var githubPRLink = regexp.MustCompile(`^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/pull/\d+/?$`)
// IsGitHubPRURL reports whether text is exactly one GitHub pull request link.
@@ -114,10 +118,11 @@ func ParseGongfengMRs(text string) []GongfengMRRef {
text = strings.ReplaceAll(text, match[0], "https://git.example.com/github:"+match[1]+"/merge_requests/"+match[2])
}
matches := gongfengMRURL.FindAllStringSubmatch(text, -1)
- if len(matches) == 0 {
+ codeupMatches := codeupMRURL.FindAllStringSubmatch(text, -1)
+ if len(matches) == 0 && len(codeupMatches) == 0 {
return nil
}
- out := make([]GongfengMRRef, 0, len(matches))
+ out := make([]GongfengMRRef, 0, len(matches)+len(codeupMatches))
seen := map[string]struct{}{}
for _, match := range matches {
project := strings.TrimSuffix(strings.TrimSuffix(match[1], "/"), "/-")
@@ -132,6 +137,19 @@ func ParseGongfengMRs(text string) []GongfengMRRef {
seen[key] = struct{}{}
out = append(out, GongfengMRRef{Project: project, IID: iid, URL: GongfengMRURL(project, iid)})
}
+ for _, match := range codeupMatches {
+ project := "codeup:" + match[1]
+ iid, _ := strconv.Atoi(match[2])
+ if iid <= 0 {
+ continue
+ }
+ key := gongfengMRKey(project, iid)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ out = append(out, GongfengMRRef{Project: project, IID: iid, URL: GongfengMRURL(project, iid)})
+ }
return out
}
diff --git a/internal/domain/project.go b/internal/domain/project.go
index ba5e49432..c85630ade 100644
--- a/internal/domain/project.go
+++ b/internal/domain/project.go
@@ -69,6 +69,11 @@ const RepositoryProviderSSH = "ssh"
// RepositoryProviderHTTPS uses Git transport without a hosting API adapter.
const RepositoryProviderHTTPS = "https"
+// RepositoryProviderCodeup is Aliyun Yunxiao Codeup hosting. Like GitHub it
+// carries its identity in GongfengProjectID ("codeup:{orgId}/{group}/{repo}")
+// and has a hosting API adapter for MR delivery; it is not git-only.
+const RepositoryProviderCodeup = "codeup"
+
func GitOnlyRepositoryProvider(provider string) bool {
return provider == RepositoryProviderSSH || provider == RepositoryProviderHTTPS
}
diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go
index 772e262b4..ffd41670b 100644
--- a/internal/domain/public_repository.go
+++ b/internal/domain/public_repository.go
@@ -8,12 +8,23 @@ import (
var githubRepositoryPath = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$`)
+// CodeupRepoHost is the Git/web host of Aliyun Yunxiao Codeup (central station).
+// A repository web/clone URL is https://codeup.aliyun.com/{orgId}/{group}/{repo}.
+const CodeupRepoHost = "codeup.aliyun.com"
+
+// codeupRepositoryPath matches "{orgId}/{group}/{repo}" (orgId plus at least two
+// path segments); Codeup repositories always live under an organization group.
+var codeupRepositoryPath = regexp.MustCompile(`^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+){2,}$`)
+
// ParseRepositoryURL adds public hosting without changing the upstream adapter.
// The prefixed remote identity prevents collisions with enterprise project IDs.
func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) {
s := strings.TrimSpace(raw)
s = strings.TrimPrefix(s, "git clone ")
s = strings.Trim(s, "\"'")
+ if info, ok := parseCodeupRepositoryURL(s); ok {
+ return info, true
+ }
if strings.HasPrefix(s, "github:") {
s = "https://github.com/" + strings.TrimPrefix(s, "github:")
}
@@ -41,3 +52,63 @@ func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) {
}
return ParseGongfengRepoURL(raw)
}
+
+// parseCodeupRepositoryURL recognizes a Codeup repository reference and returns
+// the prefixed identity "codeup:{orgId}/{group}/{repo}" plus normalized HTTPS
+// URLs. Accepted inputs mirror GitHub: the codeup: shorthand, git@/ssh:// clone
+// forms, a bare codeup.aliyun.com/... path and an https:// web or clone URL.
+func parseCodeupRepositoryURL(s string) (GongfengRepoInfo, bool) {
+ if strings.HasPrefix(s, "codeup:") {
+ s = "https://" + CodeupRepoHost + "/" + strings.TrimPrefix(s, "codeup:")
+ }
+ for _, prefix := range []string{"git@" + CodeupRepoHost + ":", "ssh://git@" + CodeupRepoHost + "/", "ssh://git@" + CodeupRepoHost + ":22/"} {
+ if strings.HasPrefix(s, prefix) {
+ s = "https://" + CodeupRepoHost + "/" + strings.TrimPrefix(s, prefix)
+ break
+ }
+ }
+ if strings.HasPrefix(s, CodeupRepoHost+"/") {
+ s = "https://" + s
+ }
+ u, err := url.Parse(s)
+ if err != nil || u.Host != CodeupRepoHost || u.User != nil || (u.Scheme != "https" && u.Scheme != "http") {
+ return GongfengRepoInfo{}, false
+ }
+ parts := strings.Split(strings.Trim(u.Path, "/"), "/")
+ if len(parts) < 3 {
+ return GongfengRepoInfo{}, false
+ }
+ parts[len(parts)-1] = strings.TrimSuffix(parts[len(parts)-1], ".git")
+ for _, seg := range parts {
+ if seg == "" || seg == "." || seg == ".." {
+ return GongfengRepoInfo{}, false
+ }
+ }
+ path := strings.Join(parts, "/")
+ if !codeupRepositoryPath.MatchString(path) {
+ return GongfengRepoInfo{}, false
+ }
+ base := "https://" + CodeupRepoHost + "/" + path
+ return GongfengRepoInfo{Project: "codeup:" + path, Name: parts[len(parts)-1], WebURL: base, CloneURL: base + ".git"}, true
+}
+
+// ParseCodeupProject splits the "codeup:{orgId}/{group}/{repo}" repository
+// identity into its organization ID and full repository path. The full path
+// (orgId/group/repo) is what the Codeup OpenAPI accepts as a URL-encoded
+// repositoryId, and the organization ID scopes every central-station call.
+func ParseCodeupProject(project string) (org, repoPath string, ok bool) {
+ rest, found := strings.CutPrefix(strings.TrimSpace(project), "codeup:")
+ if !found {
+ return "", "", false
+ }
+ org, path, found := strings.Cut(rest, "/")
+ if !found || org == "" || path == "" || !codeupRepositoryPath.MatchString(rest) {
+ return "", "", false
+ }
+ for _, seg := range strings.Split(rest, "/") {
+ if seg == "." || seg == ".." {
+ return "", "", false
+ }
+ }
+ return org, rest, true
+}
diff --git a/internal/domain/user.go b/internal/domain/user.go
index d55026290..e28ad2af7 100644
--- a/internal/domain/user.go
+++ b/internal/domain/user.go
@@ -60,9 +60,15 @@ type GitSSHKey struct {
const (
GitPlatformGitHub = "github"
GitPlatformGitLab = "gitlab"
+ GitPlatformCodeup = "codeup"
GitPlatformOther = "other"
)
+// CodeupAPIBase is the central-station OpenAPI root of Aliyun Yunxiao Codeup.
+// It is independent of the Git host (codeup.aliyun.com): the REST API lives on
+// openapi-rdc.aliyuncs.com and authenticates with the x-yunxiao-token header.
+const CodeupAPIBase = "https://openapi-rdc.aliyuncs.com"
+
// GitTokenHTTPUser is the Basic-auth user when a credential names none; the
// GitHub and Gitea families accept any user with a token password.
const GitTokenHTTPUser = "x-access-token"
@@ -101,6 +107,8 @@ func (c GitHTTPCredential) APIBase() string {
return "https://" + c.Host + "/api/v3"
case GitPlatformGitLab:
return "https://" + c.Host + "/api/v4"
+ case GitPlatformCodeup:
+ return CodeupAPIBase
default:
return ""
}
@@ -110,6 +118,9 @@ func (c GitHTTPCredential) APIBase() string {
// a bearer token for GitHub and GitLab OAuth tokens, PRIVATE-TOKEN for other
// GitLab tokens.
func (c GitHTTPCredentialSecret) APIAuthHeader() (string, string) {
+ if c.Platform == GitPlatformCodeup {
+ return "x-yunxiao-token", c.Token
+ }
if c.Platform == GitPlatformGitLab && c.Username != "oauth2" {
return "PRIVATE-TOKEN", c.Token
}
@@ -134,10 +145,10 @@ type GitHTTPExecutionCredential struct {
ExpiresAt time.Time `json:"expiresAt,omitempty"`
}
-// NormalizeGitPlatform reports ok=false for a platform outside the three kinds.
+// NormalizeGitPlatform reports ok=false for a platform outside the supported kinds.
func NormalizeGitPlatform(raw string) (string, bool) {
switch p := strings.ToLower(strings.TrimSpace(raw)); p {
- case GitPlatformGitHub, GitPlatformGitLab, GitPlatformOther:
+ case GitPlatformGitHub, GitPlatformGitLab, GitPlatformCodeup, GitPlatformOther:
return p, true
default:
return "", false
diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go
index cbc41fc3f..34cff55ce 100644
--- a/internal/httpapi/catalog.go
+++ b/internal/httpapi/catalog.go
@@ -218,7 +218,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) {
if v.GongfengProjectID != "" {
if info, ok := domain.ParseRepositoryURL(v.GongfengProjectID); ok {
v.GongfengProjectID = info.Project
- } else if !strings.HasPrefix(v.GongfengProjectID, "github:") && !domain.IsSafeGongfengProjectID(v.GongfengProjectID) {
+ } else if !strings.HasPrefix(v.GongfengProjectID, "github:") && !strings.HasPrefix(v.GongfengProjectID, "codeup:") && !domain.IsSafeGongfengProjectID(v.GongfengProjectID) {
c.JSON(400, map[string]string{"error": "仓库链接无法识别:请提供有效的 GitHub 仓库地址"})
return
}
@@ -258,11 +258,17 @@ func (h *catalogHandlers) repositories(c *gin.Context) {
v.DefaultBranch = "main"
}
}
+ if strings.HasPrefix(v.GongfengProjectID, "codeup:") {
+ v.Provider = domain.RepositoryProviderCodeup
+ if v.DefaultBranch == "" {
+ v.DefaultBranch = "master"
+ }
+ }
if v.Provider == "" {
v.Provider = "gongfeng"
}
- if v.Provider != "gongfeng" && v.Provider != "github" {
- c.JSON(400, map[string]string{"error": "provider must be github or gongfeng"})
+ if v.Provider != "gongfeng" && v.Provider != "github" && v.Provider != domain.RepositoryProviderCodeup {
+ c.JSON(400, map[string]string{"error": "provider must be github, gongfeng or codeup"})
return
}
if v.DefaultBranch == "" {
diff --git a/internal/httpapi/codeup_auth.go b/internal/httpapi/codeup_auth.go
new file mode 100644
index 000000000..fabd74187
--- /dev/null
+++ b/internal/httpapi/codeup_auth.go
@@ -0,0 +1,190 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "agentflow/internal/domain"
+
+ "github.com/gin-gonic/gin"
+)
+
+// codeupHandlers serves Aliyun Yunxiao Codeup repository discovery. Unlike
+// GitHub there is no OAuth device flow: the user saves a personal access token
+// (plus the HTTPS clone account) as a per-host Git HTTP credential for
+// codeup.aliyun.com, and these endpoints read with that stored credential.
+type codeupHandlers struct {
+ *deps
+ client *http.Client
+}
+
+func newCodeupHandlers(shared *deps) *codeupHandlers {
+ return &codeupHandlers{deps: shared, client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
+}
+
+var codeupOrganizationID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
+
+func (h *codeupHandlers) current(c *gin.Context) (int64, bool) {
+ c.Header("Cache-Control", "no-store")
+ user, ok := h.requestUser(c.Request, false)
+ if !ok || user == nil || user.IsGuest || user.ID <= 0 {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录 LoopForge,再连接云效 Codeup"})
+ return 0, false
+ }
+ if c.Request.Method != http.MethodGet {
+ origin, err := url.Parse(c.GetHeader("Origin"))
+ if err != nil || origin.Host != c.Request.Host || (origin.Scheme != "http" && origin.Scheme != "https") {
+ c.JSON(http.StatusForbidden, gin.H{"error": "请求来源不允许"})
+ return 0, false
+ }
+ }
+ return user.ID, true
+}
+
+func (h *codeupHandlers) credential(c *gin.Context, userID int64) (domain.GitHTTPCredentialSecret, bool) {
+ cred, ok := h.repo.GitHTTPCredentialForHost(c.Request.Context(), userID, domain.CodeupRepoHost)
+ if !ok || strings.TrimSpace(cred.Token) == "" {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请先在个人配置中连接云效 Codeup(填写 HTTPS 克隆账号与个人访问令牌)"})
+ return domain.GitHTTPCredentialSecret{}, false
+ }
+ return cred, true
+}
+
+// request calls the Codeup central-station OpenAPI with the stored PAT.
+func (h *codeupHandlers) request(c *gin.Context, method, path, token string, output any) error {
+ req, err := http.NewRequestWithContext(c.Request.Context(), method, domain.CodeupAPIBase+path, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", "LoopForge")
+ req.Header.Set("x-yunxiao-token", token)
+ res, err := h.client.Do(req)
+ if err != nil {
+ return errors.New("无法连接云效 Codeup,请稍后重试")
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return errors.New("云效 Codeup 请求失败(HTTP " + strconv.Itoa(res.StatusCode) + "),请检查个人访问令牌与组织/仓库权限")
+ }
+ if err := json.NewDecoder(io.LimitReader(res.Body, 4<<20)).Decode(output); err != nil {
+ return errors.New("云效 Codeup 返回了无效响应")
+ }
+ return nil
+}
+
+// organizations lists the Codeup organizations the credential can access; the
+// returned id is the organizationId required by the repository list endpoint.
+func (h *codeupHandlers) organizations(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ cred, ok := h.credential(c, userID)
+ if !ok {
+ return
+ }
+ var organizations []struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ }
+ if err := h.request(c, http.MethodGet, "/oapi/v1/platform/organizations", cred.Token, &organizations); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"organizations": organizations})
+}
+
+// repositories lists one organization's repositories. httpUrlToRepo is the
+// HTTPS clone URL ParseRepositoryURL turns into the codeup: identity.
+func (h *codeupHandlers) repositories(c *gin.Context) {
+ userID, ok := h.current(c)
+ if !ok {
+ return
+ }
+ cred, ok := h.credential(c, userID)
+ if !ok {
+ return
+ }
+ org := strings.TrimSpace(c.Query("organizationId"))
+ if org == "" || !codeupOrganizationID.MatchString(org) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "请提供有效的 organizationId"})
+ return
+ }
+ page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
+ if err != nil || page < 1 || page > 10000 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "无效页码"})
+ return
+ }
+ q := url.Values{"page": {strconv.Itoa(page)}, "perPage": {"100"}}
+ if search := strings.TrimSpace(c.Query("search")); search != "" {
+ q.Set("search", search)
+ }
+ var repositories []struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ Path string `json:"path"`
+ PathWithNamespace string `json:"pathWithNamespace"`
+ WebURL string `json:"webUrl"`
+ SSHURLToRepo string `json:"sshUrlToRepo"`
+ HTTPURLToRepo string `json:"httpUrlToRepo"`
+ DefaultBranch string `json:"defaultBranch"`
+ }
+ path := "/oapi/v1/codeup/organizations/" + url.PathEscape(org) + "/repositories?" + q.Encode()
+ if err := h.request(c, http.MethodGet, path, cred.Token, &repositories); err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"repositories": repositories, "hasMore": len(repositories) == 100, "page": page})
+}
+
+// verifyCodeupToken checks a saved Codeup credential against the current-user
+// endpoint. It is the Codeup branch of verifyGitHTTPToken and always answers
+// with a structured result.
+func verifyCodeupToken(ctx context.Context, cred domain.GitHTTPCredentialSecret) gitTokenVerifyResult {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, cred.APIBase()+"/oapi/v1/platform/user", nil)
+ if err != nil {
+ return gitTokenVerifyResult{Error: "无效的校验请求"}
+ }
+ req.Header.Set(cred.APIAuthHeader())
+ res, err := gitHTTPVerifyClient().Do(req)
+ if err != nil {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("无法连接 %s:%v", cred.Host, err)}
+ }
+ defer res.Body.Close()
+ if res.StatusCode != http.StatusOK {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回 HTTP %d,请检查个人访问令牌", cred.Host, res.StatusCode)}
+ }
+ var user struct {
+ Username string `json:"username"`
+ Login string `json:"login"`
+ Name string `json:"name"`
+ NickName string `json:"nickName"`
+ }
+ if json.NewDecoder(io.LimitReader(res.Body, 64<<10)).Decode(&user) != nil {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回了无法识别的响应", cred.Host)}
+ }
+ login := user.Username
+ if login == "" {
+ login = user.Login
+ }
+ if login == "" {
+ login = user.Name
+ }
+ if login == "" {
+ login = user.NickName
+ }
+ if login == "" {
+ return gitTokenVerifyResult{Error: fmt.Sprintf("%s 返回了无法识别的响应", cred.Host)}
+ }
+ return gitTokenVerifyResult{Valid: true, Login: login}
+}
\ No newline at end of file
diff --git a/internal/httpapi/git_http_credentials.go b/internal/httpapi/git_http_credentials.go
index 4f2f80126..78e07fb68 100644
--- a/internal/httpapi/git_http_credentials.go
+++ b/internal/httpapi/git_http_credentials.go
@@ -96,7 +96,7 @@ func respondGitHTTPCredentialError(c *gin.Context, err error) {
}
// gitHTTPCredentialFromInput validates the form. The platform defaults to
-// GitHub for github.com and "other" elsewhere.
+// GitHub for github.com, Codeup for codeup.aliyun.com and "other" elsewhere.
func (h *usersHandlers) gitHTTPCredentialFromInput(ctx context.Context, userID int64, input gitHTTPCredentialInput) (domain.GitHTTPCredentialSecret, error) {
host, err := gitwork.HTTPSHostScope(input.Host)
if err != nil {
@@ -110,10 +110,13 @@ func (h *usersHandlers) gitHTTPCredentialFromInput(ctx context.Context, userID i
if host == "github.com" {
platform = domain.GitPlatformGitHub
}
+ if host == domain.CodeupRepoHost {
+ platform = domain.GitPlatformCodeup
+ }
if strings.TrimSpace(input.Platform) != "" {
var ok bool
if platform, ok = domain.NormalizeGitPlatform(input.Platform); !ok {
- return domain.GitHTTPCredentialSecret{}, errors.New("平台只能是 github、gitlab 或 other")
+ return domain.GitHTTPCredentialSecret{}, errors.New("平台只能是 github、gitlab、codeup 或 other")
}
}
username := strings.TrimSpace(input.Username)
@@ -153,6 +156,9 @@ func verifyGitHTTPToken(ctx context.Context, cred domain.GitHTTPCredentialSecret
if cred.Managed {
return verifyGongfengToken(ctx, cred.Token)
}
+ if cred.Platform == domain.GitPlatformCodeup {
+ return verifyCodeupToken(ctx, cred)
+ }
base := cred.APIBase()
if base == "" {
return gitTokenVerifyResult{Error: "该平台不支持在线校验,令牌会在 Git 操作时使用"}
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 70df9146d..615986b97 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -70,6 +70,7 @@ type Server struct {
*deps
auth *authHandlers // auth.go
github *githubHandlers
+ codeup *codeupHandlers // codeup_auth.go
users *usersHandlers // users.go
projects *projectsHandlers
insights *insightsHandlers
@@ -153,6 +154,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
notifications: ¬ificationHandlers{deps: d, service: notifications},
auth: &authHandlers{deps: d},
github: newGitHubHandlers(d),
+ codeup: newCodeupHandlers(d),
users: &usersHandlers{deps: d},
catalog: &catalogHandlers{deps: d},
businessDomains: &businessDomainsHandlers{deps: d},
@@ -250,6 +252,8 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
g.POST("/api/auth/github/device", api.github.start)
g.POST("/api/auth/github/poll", api.github.poll)
g.GET("/api/auth/github/repositories", api.github.repositories)
+ g.GET("/api/auth/codeup/organizations", api.codeup.organizations)
+ g.GET("/api/auth/codeup/repositories", api.codeup.repositories)
g.GET("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/exchange", api.auth.authExchange)
g.POST("/api/auth/logout", api.auth.authLogout)
diff --git a/internal/tracker/codeup.go b/internal/tracker/codeup.go
new file mode 100644
index 000000000..4571c264c
--- /dev/null
+++ b/internal/tracker/codeup.go
@@ -0,0 +1,388 @@
+package tracker
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ "agentflow/internal/domain"
+)
+
+// codeupClient talks to the Aliyun Yunxiao Codeup central-station OpenAPI. It
+// mirrors githubClient: the token is the project owner's per-host HTTPS Git
+// credential for codeup.aliyun.com (the PAT doubles as the API token), and the
+// repository is addressed by its URL-encoded full path orgId/group/repo.
+type codeupClient struct {
+ base, org, repoPath, token string
+ http *http.Client
+ repoID int // cached integer repository id resolved on first write/list
+}
+
+func (s *Service) codeupClient(project string) (*codeupClient, error) {
+ org, repoPath, ok := domain.ParseCodeupProject(project)
+ if !ok {
+ return nil, fmt.Errorf("invalid Codeup repository")
+ }
+ var token string
+ if s.projectAuth != nil {
+ for _, repo := range s.projectAuth.Repositories() {
+ if repo.Provider != domain.RepositoryProviderCodeup || repo.GongfengProjectID != project {
+ continue
+ }
+ if p, found := s.projectAuth.Project(repo.ProjectID); found {
+ token = s.codeupTokenForUser(p.OwnerID)
+ }
+ break
+ }
+ }
+ base := s.codeupAPIBase
+ if base == "" {
+ base = domain.CodeupAPIBase
+ }
+ return &codeupClient{base: base, org: org, repoPath: repoPath, token: token, http: &http.Client{Timeout: 30 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}}, nil
+}
+
+// codeupClientForRun authenticates as the run did: its push token when set,
+// else the Owner of the run's project when that project binds the repository.
+func (s *Service) codeupClientForRun(project, localProjectID, gitToken string) (*codeupClient, string, error) {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return nil, "", err
+ }
+ if token := strings.TrimSpace(gitToken); token != "" {
+ c.token = token
+ return c, "本轮责任人的 Git Token", nil
+ }
+ local := strings.TrimSpace(localProjectID)
+ if s.projectAuth == nil || local == "" {
+ return c, "首个绑定该仓库的项目 Owner 的 Git Token", nil
+ }
+ for _, repo := range s.projectAuth.Repositories() {
+ if repo.Provider != domain.RepositoryProviderCodeup || repo.GongfengProjectID != project || repo.ProjectID != local {
+ continue
+ }
+ c.token = ""
+ if p, found := s.projectAuth.Project(local); found {
+ c.token = s.codeupTokenForUser(p.OwnerID)
+ }
+ return c, "项目 " + local + " Owner 的 Git Token", nil
+ }
+ return c, "首个绑定该仓库的项目 Owner 的 Git Token", nil
+}
+
+func (s *Service) codeupTokenForUser(userID int64) string {
+ if credentials, ok := s.projectAuth.(GitHTTPCredentialStore); ok {
+ if credential, ok := credentials.GitHTTPCredentialForHost(context.Background(), userID, domain.CodeupRepoHost); ok {
+ return credential.Token
+ }
+ }
+ return ""
+}
+
+func (c *codeupClient) request(method, path string, input, output any) error {
+ var body io.Reader
+ if input != nil {
+ b, err := json.Marshal(input)
+ if err != nil {
+ return err
+ }
+ body = bytes.NewReader(b)
+ }
+ r, err := http.NewRequest(method, c.base+path, body)
+ if err != nil {
+ return err
+ }
+ r.Header.Set("Accept", "application/json")
+ r.Header.Set("Content-Type", "application/json")
+ if c.token != "" {
+ r.Header.Set("x-yunxiao-token", c.token)
+ }
+ res, err := c.http.Do(r)
+ if err != nil {
+ return fmt.Errorf("Codeup request failed")
+ }
+ defer res.Body.Close()
+ if res.StatusCode < 200 || res.StatusCode >= 300 {
+ return fmt.Errorf("Codeup returned HTTP %d; check the project owner's Codeup token and repository permissions", res.StatusCode)
+ }
+ if output == nil {
+ _, err = io.Copy(io.Discard, io.LimitReader(res.Body, 4<<20))
+ return err
+ }
+ return json.NewDecoder(io.LimitReader(res.Body, 8<<20)).Decode(output)
+}
+
+func (c *codeupClient) repoPathEscape() string { return url.PathEscape(c.repoPath) }
+
+// repositoryID resolves the integer repository id the create/list APIs require.
+// The repositoryId path parameter accepts the URL-encoded full path, so no
+// separate lookup table is needed; the result is cached for the client's life.
+func (c *codeupClient) repositoryID() (int, error) {
+ if c.repoID != 0 {
+ return c.repoID, nil
+ }
+ var repo struct {
+ ID int `json:"id"`
+ }
+ if err := c.request("GET", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape(), nil, &repo); err != nil {
+ return 0, err
+ }
+ if repo.ID == 0 {
+ return 0, fmt.Errorf("Codeup repository %s has no id", c.repoPath)
+ }
+ c.repoID = repo.ID
+ return repo.ID, nil
+}
+
+// codeupChangeRequest is one merge request (变更) in a Codeup repository.
+type codeupChangeRequest struct {
+ LocalID int `json:"localId"`
+ State string `json:"state"`
+ DetailURL string `json:"detailUrl"`
+ WebURL string `json:"webUrl"`
+ SourceBranch string `json:"sourceBranch"`
+ TargetBranch string `json:"targetBranch"`
+ MergedRevision string `json:"mergedRevision"`
+ ProjectID int `json:"projectId"`
+ SourceProjectID int `json:"sourceProjectId"`
+ TargetProjectID int `json:"targetProjectId"`
+ Title string `json:"title"`
+}
+
+// codeupMRState maps the Codeup change-request status onto the platform's
+// opened/merged/closed delivery vocabulary.
+func codeupMRState(state string) string {
+ switch strings.ToUpper(strings.TrimSpace(state)) {
+ case "UNDER_DEV", "UNDER_REVIEW", "TO_BE_MERGED":
+ return "opened"
+ case "MERGED":
+ return "merged"
+ case "CLOSED":
+ return "closed"
+ default:
+ return ""
+ }
+}
+
+// ref is the "!N" reference returned to delivery callers (localId is per-repo).
+func (cr codeupChangeRequest) ref() string { return "!" + strconv.Itoa(cr.LocalID) }
+
+func (cr codeupChangeRequest) webURL(project string) string {
+ if u := strings.TrimSpace(cr.DetailURL); u != "" {
+ return u
+ }
+ if u := strings.TrimSpace(cr.WebURL); u != "" {
+ return u
+ }
+ return domain.GongfengMRURL(project, cr.LocalID)
+}
+
+// delivery converts a change request into a delivery MR. Codeup's list response
+// exposes no source-branch head commit, so HeadSHA stays empty: an open MR then
+// satisfies the coverage gate, and merged MRs are classified by state alone.
+func (cr codeupChangeRequest) delivery(project string) domain.DeliveryMR {
+ state := codeupMRState(cr.State)
+ return domain.DeliveryMR{
+ Project: project,
+ IID: cr.LocalID,
+ URL: cr.webURL(project),
+ State: state,
+ GongfengState: state,
+ TargetBranch: strings.TrimSpace(cr.TargetBranch),
+ }
+}
+
+// listChangeRequests lists the repository's change requests, most recently
+// updated first. The central-station list endpoint is organization-scoped and
+// filters by projectIds/state only, so source/target branch matching is done by
+// the caller. An empty state queries every status.
+func (c *codeupClient) listChangeRequests(state string) ([]codeupChangeRequest, error) {
+ id, err := c.repositoryID()
+ if err != nil {
+ return nil, err
+ }
+ var out []codeupChangeRequest
+ for page := 1; page <= 20; page++ {
+ q := url.Values{"projectIds": {strconv.Itoa(id)}, "perPage": {"100"}, "page": {strconv.Itoa(page)}, "orderBy": {"updated_at"}, "sort": {"desc"}}
+ if state != "" {
+ q.Set("state", state)
+ }
+ var list []codeupChangeRequest
+ if err := c.request("GET", "/oapi/v1/codeup/organizations/"+c.org+"/changeRequests?"+q.Encode(), nil, &list); err != nil {
+ return nil, err
+ }
+ out = append(out, list...)
+ if len(list) < 100 {
+ break
+ }
+ }
+ return out, nil
+}
+
+func (c *codeupClient) createChangeRequest(sourceBranch, targetBranch, title, description string) (codeupChangeRequest, error) {
+ id, err := c.repositoryID()
+ if err != nil {
+ return codeupChangeRequest{}, err
+ }
+ body := map[string]any{
+ "sourceBranch": sourceBranch,
+ "targetBranch": targetBranch,
+ "title": title,
+ "sourceProjectId": id,
+ "targetProjectId": id,
+ }
+ if strings.TrimSpace(description) != "" {
+ body["description"] = description
+ }
+ var cr codeupChangeRequest
+ if err := c.request("POST", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape()+"/changeRequests", body, &cr); err != nil {
+ return codeupChangeRequest{}, err
+ }
+ return cr, nil
+}
+
+// mergeChangeRequest merges with a merge commit (no-fast-forward) and keeps the
+// source branch, matching the Gongfeng/GitHub delivery convention.
+func (c *codeupClient) mergeChangeRequest(localID int, message string) error {
+ body := map[string]any{
+ "mergeType": "no-fast-forward",
+ "removeSourceBranch": false,
+ }
+ if strings.TrimSpace(message) != "" {
+ body["mergeMessage"] = message
+ }
+ return c.request("POST", "/oapi/v1/codeup/organizations/"+c.org+"/repositories/"+c.repoPathEscape()+"/changeRequests/"+strconv.Itoa(localID)+"/merge", body, nil)
+}
+
+func findCodeupChangeRequest(items []codeupChangeRequest, branch, target string) (codeupChangeRequest, bool) {
+ for _, cr := range items {
+ if domain.SameGitBranch(cr.SourceBranch, branch) && (target == "" || domain.SameGitBranch(cr.TargetBranch, target)) {
+ return cr, true
+ }
+ }
+ return codeupChangeRequest{}, false
+}
+
+// pickCodeupBranchMR returns the newest non-closed change request whose source
+// is branch, else the newest closed one (mirrors pickBranchMR).
+func pickCodeupBranchMR(items []codeupChangeRequest, sourceBranch string) (codeupChangeRequest, bool) {
+ var best codeupChangeRequest
+ found, bestClosed := false, false
+ for _, item := range items {
+ if s := strings.TrimSpace(item.SourceBranch); s != "" && !domain.SameGitBranch(s, sourceBranch) {
+ continue
+ }
+ closed := codeupMRState(item.State) == "closed"
+ switch {
+ case !found:
+ case bestClosed && !closed:
+ case bestClosed == closed && item.LocalID > best.LocalID:
+ default:
+ continue
+ }
+ best, found, bestClosed = item, true, closed
+ }
+ return best, found
+}
+
+func (s *Service) codeupFindBranch(project, branch string) (domain.DeliveryMR, bool, error) {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return domain.DeliveryMR{}, false, err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return domain.DeliveryMR{}, false, err
+ }
+ cr, ok := pickCodeupBranchMR(list, branch)
+ if !ok {
+ return domain.DeliveryMR{}, false, nil
+ }
+ return cr.delivery(project), true, nil
+}
+
+func (s *Service) codeupMergeBranch(project, branch, target, title, description string) (string, error) {
+ if branch == "" {
+ return "", fmt.Errorf("source branch is required")
+ }
+ if branch == target {
+ return "", nil
+ }
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return "", err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return "", err
+ }
+ cr, found := findCodeupChangeRequest(list, branch, target)
+ if found && codeupMRState(cr.State) == "merged" {
+ return cr.ref(), nil
+ }
+ if !found || codeupMRState(cr.State) == "closed" {
+ if target == "" {
+ return "", ErrNoOpenMR
+ }
+ if strings.TrimSpace(title) == "" {
+ title = "LoopForge: " + branch + " → " + target
+ }
+ cr, err = c.createChangeRequest(branch, target, title, description)
+ if err != nil {
+ return "", err
+ }
+ }
+ if err := c.mergeChangeRequest(cr.LocalID, title); err != nil {
+ return "", fmt.Errorf("merge MR !%d: %w", cr.LocalID, err)
+ }
+ return cr.ref(), nil
+}
+
+func (s *Service) codeupFindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR, error) {
+ project := strings.TrimSpace(q.RemoteProject)
+ src, target := strings.TrimSpace(q.SourceBranch), strings.TrimSpace(q.TargetBranch)
+ c, identity, err := s.codeupClientForRun(project, q.ProjectID, q.GitToken)
+ if err != nil {
+ return nil, err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return nil, fmt.Errorf("以%s查询云效失败:%w", identity, err)
+ }
+ var out []domain.DeliveryMR
+ for _, cr := range list {
+ if !domain.SameGitBranch(cr.SourceBranch, src) || !domain.SameGitBranch(cr.TargetBranch, target) {
+ continue
+ }
+ out = append(out, cr.delivery(project))
+ }
+ return out, nil
+}
+
+// refreshCodeupDelivery re-reads one change request's state for the background
+// delivery sync. Codeup's list response carries no merge timestamp, so mergedAt
+// stays zero; the classified state and target branch are still refreshed.
+func (s *Service) refreshCodeupDelivery(store MRDeliveryStore, project string, localID int) error {
+ c, err := s.codeupClient(project)
+ if err != nil {
+ return err
+ }
+ list, err := c.listChangeRequests("")
+ if err != nil {
+ return err
+ }
+ for _, cr := range list {
+ if cr.LocalID == localID {
+ d := cr.delivery(project)
+ return store.UpdateMRDeliveryState(project, localID, d.GongfengState, d.TargetBranch, time.Time{}, time.Now().UTC())
+ }
+ }
+ return fmt.Errorf("Codeup change request %s!%d not found", project, localID)
+}
\ No newline at end of file
diff --git a/internal/tracker/codeup_test.go b/internal/tracker/codeup_test.go
new file mode 100644
index 000000000..765442722
--- /dev/null
+++ b/internal/tracker/codeup_test.go
@@ -0,0 +1,195 @@
+package tracker
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "agentflow/internal/domain"
+ "agentflow/internal/repo"
+)
+
+func TestCodeupMRStateMapping(t *testing.T) {
+ cases := map[string]string{
+ "UNDER_DEV": "opened",
+ "UNDER_REVIEW": "opened",
+ "TO_BE_MERGED": "opened",
+ "MERGED": "merged",
+ "CLOSED": "closed",
+ "under_review": "opened",
+ "UNKNOWN": "",
+ "": "",
+ }
+ for state, want := range cases {
+ if got := codeupMRState(state); got != want {
+ t.Errorf("codeupMRState(%q) = %q want %q", state, got, want)
+ }
+ }
+}
+
+// codeupTestStore wires a project owner with a per-host Codeup credential and a
+// codeup repository, mirroring the GitHub adapter test fixtures.
+func codeupTestStore(t *testing.T) (*Service, domain.Repository) {
+ t.Helper()
+ st, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(st.Close)
+ if err := st.PutUser(domain.User{LoginName: "codeup-owner"}); err != nil {
+ t.Fatal(err)
+ }
+ u, _ := st.UserByLoginName("codeup-owner")
+ if err := st.SaveGitHTTPCredential(u.ID, "", domain.GitHTTPCredentialSecret{
+ GitHTTPCredential: domain.GitHTTPCredential{Name: "Codeup", Host: domain.CodeupRepoHost, Platform: domain.GitPlatformCodeup, Username: "clone-account"},
+ Token: "codeup-pat",
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.PutProject(domain.Project{ID: "pub", Name: "Pub", OwnerID: u.ID}); err != nil {
+ t.Fatal(err)
+ }
+ r := domain.Repository{ID: "codeup-repo", ProjectID: "pub", Provider: domain.RepositoryProviderCodeup, Name: "app", GongfengProjectID: "codeup:60d54f3daccf2bbd6659f3ad/team/app", DefaultBranch: "master", WebURL: "https://codeup.aliyun.com/60d54f3daccf2bbd6659f3ad/team/app"}
+ if err := st.PutRepository(r); err != nil {
+ t.Fatal(err)
+ }
+ s := NewService()
+ s.ConfigureWithStore(domain.SyncConfig{}, st)
+ return s, r
+}
+
+const (
+ codeupTestOrg = "60d54f3daccf2bbd6659f3ad"
+ codeupTestRepoBase = "/oapi/v1/codeup/organizations/" + codeupTestOrg + "/repositories/" + codeupTestOrg + "%2Fteam%2Fapp"
+ codeupTestListPath = "/oapi/v1/codeup/organizations/" + codeupTestOrg + "/changeRequests"
+)
+
+// codeupTestServer simulates the Codeup OpenAPI: repository id resolution, the
+// organization-scoped change-request list, create and merge. It records writes
+// and the decoded create/merge bodies for assertions.
+func codeupTestServer(t *testing.T, listJSON string) (*httptest.Server, *[]string, *map[string]any, *map[string]any) {
+ t.Helper()
+ var writes []string
+ var createBody, mergeBody map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("x-yunxiao-token") != "codeup-pat" {
+ t.Errorf("missing or wrong Codeup token header: %q", r.Header.Get("x-yunxiao-token"))
+ }
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case r.Method == http.MethodGet && r.URL.EscapedPath() == codeupTestRepoBase:
+ _, _ = w.Write([]byte(`{"id":2813489}`))
+ case r.Method == http.MethodGet && r.URL.Path == codeupTestListPath:
+ if r.URL.Query().Get("projectIds") != "2813489" {
+ t.Errorf("list must filter by the resolved repository id, got %q", r.URL.RawQuery)
+ }
+ _, _ = w.Write([]byte(listJSON))
+ case r.Method == http.MethodPost && r.URL.EscapedPath() == codeupTestRepoBase+"/changeRequests":
+ writes = append(writes, "POST create")
+ _ = json.NewDecoder(r.Body).Decode(&createBody)
+ _, _ = w.Write([]byte(`{"localId":21,"state":"UNDER_REVIEW","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/21"}`))
+ case r.Method == http.MethodPost && strings.HasPrefix(r.URL.EscapedPath(), codeupTestRepoBase+"/changeRequests/") && strings.HasSuffix(r.URL.EscapedPath(), "/merge"):
+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.EscapedPath(), codeupTestRepoBase+"/changeRequests/"), "/merge")
+ writes = append(writes, "POST merge "+id)
+ _ = json.NewDecoder(r.Body).Decode(&mergeBody)
+ _, _ = w.Write([]byte(`{}`))
+ default:
+ t.Errorf("unexpected request %s %s", r.Method, r.URL.EscapedPath())
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &writes, &createBody, &mergeBody
+}
+
+func TestCodeupEnsureAndMergeBranchMR(t *testing.T) {
+ project := "codeup:" + codeupTestOrg + "/team/app"
+
+ t.Run("create then merge", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ srv, writes, createBody, mergeBody := codeupTestServer(t, `[]`)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "Title", "desc")
+ if err != nil || ref != "!21" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 2 || (*writes)[0] != "POST create" || (*writes)[1] != "POST merge 21" {
+ t.Fatalf("writes=%v", *writes)
+ }
+ if (*createBody)["sourceProjectId"] != float64(2813489) || (*createBody)["targetProjectId"] != float64(2813489) {
+ t.Fatalf("create must bind integer repo ids: %v", *createBody)
+ }
+ if (*createBody)["sourceBranch"] != "feature/work" || (*createBody)["targetBranch"] != "master" || (*createBody)["title"] != "Title" {
+ t.Fatalf("create body: %v", *createBody)
+ }
+ if (*mergeBody)["mergeType"] != "no-fast-forward" || (*mergeBody)["removeSourceBranch"] != false {
+ t.Fatalf("merge body: %v", *mergeBody)
+ }
+ })
+
+ t.Run("merge existing open without create", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ list := `[{"localId":7,"state":"TO_BE_MERGED","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/7"}]`
+ srv, writes, _, mergeBody := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "", "")
+ if err != nil || ref != "!7" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 1 || (*writes)[0] != "POST merge 7" {
+ t.Fatalf("open MR must be merged without re-create: %v", *writes)
+ }
+ if (*mergeBody)["mergeType"] != "no-fast-forward" {
+ t.Fatalf("merge body: %v", *mergeBody)
+ }
+ })
+
+ t.Run("short-circuit already merged", func(t *testing.T) {
+ s, _ := codeupTestStore(t)
+ list := `[{"localId":9,"state":"MERGED","sourceBranch":"feature/work","targetBranch":"master","mergedRevision":"abc"}]`
+ srv, writes, _, _ := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+ ref, err := s.EnsureAndMergeBranchMR(project, "feature/work", "master", "", "")
+ if err != nil || ref != "!9" {
+ t.Fatalf("ref=%q err=%v", ref, err)
+ }
+ if len(*writes) != 0 {
+ t.Fatalf("merged MR must not be re-created or re-merged: %v", *writes)
+ }
+ })
+}
+
+func TestCodeupFindBranchMRAndInto(t *testing.T) {
+ s, r := codeupTestStore(t)
+ list := `[
+ {"localId":7,"state":"UNDER_REVIEW","sourceBranch":"feature/work","targetBranch":"master","detailUrl":"https://codeup.aliyun.com/` + codeupTestOrg + `/team/app/change/7"},
+ {"localId":5,"state":"MERGED","sourceBranch":"feature/work","targetBranch":"master","mergedRevision":"old"},
+ {"localId":8,"state":"CLOSED","sourceBranch":"feature/work","targetBranch":"master"},
+ {"localId":9,"state":"UNDER_DEV","sourceBranch":"other","targetBranch":"master"}
+ ]`
+ srv, _, _, _ := codeupTestServer(t, list)
+ s.codeupAPIBase = srv.URL
+
+ mr, ok, err := s.FindBranchMR(r.GongfengProjectID, "feature/work")
+ if err != nil || !ok {
+ t.Fatalf("FindBranchMR ok=%v err=%v", ok, err)
+ }
+ if mr.IID != 7 || mr.GongfengState != "opened" || mr.URL != "https://codeup.aliyun.com/"+codeupTestOrg+"/team/app/change/7" {
+ t.Fatalf("FindBranchMR = %+v", mr)
+ }
+
+ into, err := s.FindBranchMRsInto(domain.BranchMRQuery{ProjectID: "pub", RemoteProject: r.GongfengProjectID, SourceBranch: "feature/work", TargetBranch: "master"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(into) != 3 {
+ t.Fatalf("FindBranchMRsInto = %+v", into)
+ }
+ for _, mr := range into {
+ if mr.TargetBranch != "master" || mr.Project != r.GongfengProjectID {
+ t.Fatalf("unexpected MR in result: %+v", mr)
+ }
+ }
+}
\ No newline at end of file
diff --git a/internal/tracker/merge_mr.go b/internal/tracker/merge_mr.go
index e5c2593e2..5a2bf20c2 100644
--- a/internal/tracker/merge_mr.go
+++ b/internal/tracker/merge_mr.go
@@ -29,6 +29,9 @@ func (s *Service) EnsureAndMergeBranchMR(project, sourceBranch, targetBranch, ti
if strings.HasPrefix(project, "github:") {
return s.githubMergeBranch(project, sourceBranch, targetBranch, title, description)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupMergeBranch(project, sourceBranch, targetBranch, title, description)
+ }
project = strings.TrimSpace(project)
src := strings.TrimSpace(sourceBranch)
tgt := strings.TrimSpace(targetBranch)
@@ -141,6 +144,9 @@ func (s *Service) FindBranchMR(project, sourceBranch string) (domain.DeliveryMR,
if strings.HasPrefix(project, "github:") {
return s.githubFindBranch(project, sourceBranch)
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupFindBranch(project, sourceBranch)
+ }
project = strings.TrimSpace(project)
src := strings.TrimSpace(sourceBranch)
if project == "" || src == "" {
@@ -201,6 +207,9 @@ func (s *Service) FindBranchMRsInto(q domain.BranchMRQuery) ([]domain.DeliveryMR
}
return githubPullsInto(pulls, project, src, target), nil
}
+ if strings.HasPrefix(project, "codeup:") {
+ return s.codeupFindBranchMRsInto(q)
+ }
client, source, err := s.gongfengClientForRun(project, q)
if err != nil {
return nil, err
diff --git a/internal/tracker/mr_delivery_sync.go b/internal/tracker/mr_delivery_sync.go
index 212d9d03c..fa5550eba 100644
--- a/internal/tracker/mr_delivery_sync.go
+++ b/internal/tracker/mr_delivery_sync.go
@@ -132,6 +132,14 @@ func (s *Service) syncMRDeliveryStates(store MRDeliveryStore) {
}
continue
}
+ if strings.HasPrefix(row.MRProject, "codeup:") {
+ if err := s.refreshCodeupDelivery(store, row.MRProject, row.MRIID); err != nil {
+ log.Printf("Codeup delivery refresh: %v", err)
+ } else {
+ updated++
+ }
+ continue
+ }
if strings.HasPrefix(row.MRProject, domain.MRProjectGHE) || strings.HasPrefix(row.MRProject, domain.MRProjectGitLab) {
if ok, err := s.refreshExternalDelivery(store, row); err != nil {
log.Printf("mr-delivery refresh %s!%d: %v", row.MRProject, row.MRIID, err)
@@ -170,7 +178,7 @@ func (s *Service) discoverPromoteMRs(store MRDeliveryStore) {
now := time.Now().UTC()
for _, repo := range store.Repositories() {
project := strings.TrimSpace(repo.GongfengProjectID)
- if strings.HasPrefix(project, "github:") {
+ if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "codeup:") {
continue
}
def := strings.TrimSpace(repo.DefaultBranch)
@@ -233,7 +241,7 @@ func (s *Service) syncWorkCommitsOnDefaultBranch(store MRDeliveryStore) {
}
for _, repo := range store.Repositories() {
project := strings.TrimSpace(repo.GongfengProjectID)
- if strings.HasPrefix(project, "github:") {
+ if strings.HasPrefix(project, "github:") || strings.HasPrefix(project, "codeup:") {
continue
}
def := strings.TrimSpace(repo.DefaultBranch)
diff --git a/internal/tracker/service.go b/internal/tracker/service.go
index 7edf45f75..e9037d150 100644
--- a/internal/tracker/service.go
+++ b/internal/tracker/service.go
@@ -20,6 +20,7 @@ import (
type Service struct {
githubAPIBase string // Tests inject an HTTP server; production uses api.github.com.
gitHostAPIBase string // Tests inject an HTTP server for every Git HTTP credential host.
+ codeupAPIBase string // Tests inject an HTTP server; production uses openapi-rdc.aliyuncs.com.
cfg *syncConfigHolder
gongfeng *MCPClient
tapd *MCPClient
diff --git a/web/app/access.js b/web/app/access.js
index 0a8530fe1..0d3453d4a 100644
--- a/web/app/access.js
+++ b/web/app/access.js
@@ -66,12 +66,13 @@ function gotoCredential(name,sshRemote){
}
// Personal credential fields and the errors they cause. Keep the rules in
// sync with chatbot/src/credentials.js.
-const CREDENTIAL_FIELDS={codeBuddyApiKey:'CodeBuddy API Key',codexApiKey:'Codex API Key',claudeCodeApiKey:'Claude Code API Key',gitToken:'GitHub Git Token',gitSshKey:'Git SSH 密钥',gitHttpCredentials:'Git 访问令牌'};
+const CREDENTIAL_FIELDS={codeBuddyApiKey:'CodeBuddy API Key',codexApiKey:'Codex API Key',claudeCodeApiKey:'Claude Code API Key',gitToken:'GitHub Git Token',codeupToken:'云效 Codeup 仓库授权',gitSshKey:'Git SSH 密钥',gitHttpCredentials:'Git 访问令牌'};
const CREDENTIAL_RULES=[
['codexApiKey',/Codex[^。\n]{0,16}API Key/i],
['claudeCodeApiKey',/Claude Code[^。\n]{0,16}API Key/i],
['codeBuddyApiKey',/CodeBuddy[^。\n]{0,20}(API Key|Key|凭据)|拒绝了你的 API Key/i],
['gitSshKey',/Git SSH (?:密钥|私钥)/i],
+ ['codeupToken',/Codeup|云效[^。\n]{0,12}(令牌|授权|凭据|克隆账号)/i],
['gitToken',/Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]/i],
];
function credentialHint(text){
diff --git a/web/app/codeup-connect.js b/web/app/codeup-connect.js
new file mode 100644
index 000000000..b5ea0162e
--- /dev/null
+++ b/web/app/codeup-connect.js
@@ -0,0 +1,152 @@
+// 云效 Codeup 仓库授权:PAT + HTTPS 克隆账号校验 → 组织选择 → 仓库选择器。
+// Mirrors github-connect.js, but Codeup has no OAuth device flow: the personal
+// access token is verified and saved as the per-host Git HTTPS credential for
+// codeup.aliyun.com (platform=codeup) before repositories can be listed.
+const CODEUP_HOST='codeup.aliyun.com';
+
+function codeupCredentialRecordForPicker(){
+ const user=state.currentUser;
+ if(!user?.id||user.isGuest)return null;
+ if(typeof codeupCredentialRecord==='function')return codeupCredentialRecord(user);
+ const cached=state.codeupCredential;
+ return cached&&Number(cached.userId)===Number(user.id)?cached.record||null:null;
+}
+function codeupPickerConfigured(){
+ return !!(userById(state.currentUser?.id)?.codeupCredentialConfigured||codeupCredentialRecordForPicker());
+}
+function codeupOrganizationKey(){return 'agentflow.codeup.organization.'+(state.currentUser?.id||'')}
+function codeupStoredOrganization(){try{return localStorage.getItem(codeupOrganizationKey())||''}catch{return ''}}
+function codeupRememberOrganization(id){try{id?localStorage.setItem(codeupOrganizationKey(),id):localStorage.removeItem(codeupOrganizationKey())}catch{}}
+
+function codeupConnectHTML(){
+ return `
+ 使用云效 Codeup 的个人访问令牌(PAT)与 HTTPS 克隆账号连接,即可选择组织内的仓库。令牌在「个人设置 → 个人访问令牌」创建,克隆账号在「个人设置 → HTTPS 密码」查看。
+
+
+
+
+ `;
+}
+
+function mountCodeupRepoPicker(host,onSelect){
+ if(!host)return;
+ const connected=codeupPickerConfigured();
+ host.innerHTML=(connected?'':codeupConnectHTML())
+ +``
+ +``
+ +`连接后可选择组织内的仓库;也可以直接粘贴 https://codeup.aliyun.com/组织ID/仓库.git 地址。
`
+ +'';
+ const orgRow=host.querySelector('[data-codeup-org-row]'),orgSelect=host.querySelector('[data-codeup-org]'),orgStatus=host.querySelector('[data-codeup-org-status]');
+ const load=host.querySelector('[data-codeup-load]'),list=host.querySelector('[data-codeup-repo-list]');
+ let repositories=[],page=1,busy=false,organizationId='';
+
+ // The Codeup OpenAPI returns pathWithNamespace/webUrl/httpUrlToRepo; normalize
+ // to the GitHub-picker shape (full_name/html_url/clone_url/default_branch).
+ const normalize=repo=>{
+ let full=String(repo.full_name||repo.pathWithNamespace||repo.path||repo.name||'');
+ if(organizationId&&!full.startsWith(organizationId+'/'))full=organizationId+'/'+full;
+ return {...repo,full_name:full,html_url:repo.html_url||repo.webUrl||`https://${CODEUP_HOST}/${full}`,clone_url:repo.clone_url||repo.httpUrlToRepo||`https://${CODEUP_HOST}/${full}.git`,default_branch:repo.default_branch||repo.defaultBranch||'main'};
+ };
+ const paint=hasMore=>{
+ list.innerHTML='未找到仓库,可手动填写地址;请确认令牌有组织内仓库的读取权限。
'+(hasMore?'':'');
+ const select=list.querySelector('[data-codeup-repo]'),search=list.querySelector('[data-codeup-search]'),empty=list.querySelector('[data-codeup-repo-empty]');
+ const filter=()=>{
+ select.replaceChildren(new Option('请选择仓库',''));
+ const visible=repositories.filter(repo=>String(repo.full_name||'').toLowerCase().includes(search.value.toLowerCase()));
+ for(const repository of visible){const option=document.createElement('option');option.value=repository.full_name;option.textContent=repository.full_name+(repository.private?' · 私有':'');select.append(option)}
+ empty.hidden=visible.length>0;
+ };
+ search.oninput=filter;
+ select.onchange=()=>{
+ const repository=repositories.find(repo=>repo.full_name===select.value);
+ if(repository)onSelect({...repository,clone_url:repository.clone_url||`https://${CODEUP_HOST}/${repository.full_name}.git`});
+ };
+ const more=list.querySelector('[data-codeup-more]');if(more)more.onclick=()=>fetchPage(page+1);
+ filter();
+ };
+ const fetchPage=async requested=>{
+ if(busy||!organizationId)return;
+ busy=true;load.disabled=true;
+ const actor=Number(state.currentUser?.id);
+ const more=list.querySelector('[data-codeup-more]');if(more)more.disabled=true;
+ try{
+ const result=await api(`/api/auth/codeup/repositories?organizationId=${encodeURIComponent(organizationId)}&page=`+requested);
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ const rows=(Array.isArray(result?.repositories)?result.repositories:[]).map(normalize);
+ page=requested;repositories=requested===1?rows:repositories.concat(rows);
+ paint(!!result?.hasMore);
+ }catch(error){list.textContent=error.message}
+ finally{busy=false;load.disabled=false;if(more)more.disabled=false}
+ };
+ const chooseOrganization=id=>{
+ organizationId=String(id||'').trim();
+ codeupRememberOrganization(organizationId);
+ repositories=[];page=1;list.innerHTML='';
+ if(organizationId)fetchPage(1);
+ };
+ const orgManualHTML=message=>`${escapeHTML(message||'')}
`;
+ const bindManualOrg=()=>{
+ const input=orgRow.querySelector('[data-codeup-org-manual]'),apply=orgRow.querySelector('[data-codeup-org-apply]');
+ if(!input||!apply)return;
+ const status=orgRow.querySelector('[data-codeup-org-status]');
+ apply.onclick=()=>{
+ const id=input.value.trim();
+ if(!id){if(status)status.textContent='请填写组织 ID';return}
+ chooseOrganization(id);
+ };
+ };
+ const fetchOrganizations=async()=>{
+ const actor=Number(state.currentUser?.id);
+ orgStatus.textContent='正在读取组织…';
+ try{
+ const result=await api('/api/auth/codeup/organizations',{silent:true});
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ const organizations=Array.isArray(result)?result:(Array.isArray(result?.organizations)?result.organizations:[]);
+ if(!organizations.length)throw new Error('没有可用的组织');
+ orgSelect.replaceChildren(new Option('请选择组织',''));
+ for(const organization of organizations){
+ const id=String(organization.id??organization.organizationId??'');
+ if(!id)continue;
+ orgSelect.append(new Option(organization.name?`${organization.name}(${id})`:id,id));
+ }
+ orgStatus.textContent='';
+ const stored=codeupStoredOrganization();
+ if(stored&&[...orgSelect.options].some(option=>option.value===stored)){orgSelect.value=stored;chooseOrganization(stored)}
+ orgSelect.onchange=()=>chooseOrganization(orgSelect.value);
+ }catch(error){
+ if(!host.isConnected||Number(state.currentUser?.id)!==actor)return;
+ // The organization listing may be unavailable; a manually pasted organization ID keeps the picker usable.
+ orgRow.innerHTML=orgManualHTML(`组织列表暂不可用(${error.message}),可手动填写组织 ID。`);
+ bindManualOrg();
+ }
+ };
+ load.onclick=()=>{if(organizationId)fetchPage(1);else fetchOrganizations()};
+
+ const connect=host.querySelector('[data-codeup-connect]');
+ if(connect){
+ const button=connect.querySelector('[data-codeup-start]'),status=connect.querySelector('[data-codeup-status]');
+ const username=connect.querySelector('[data-codeup-username]'),token=connect.querySelector('[data-codeup-token]');
+ button.onclick=async()=>{
+ if(button.disabled)return;
+ const account=username.value.trim(),pat=token.value.trim();
+ if(!account||!pat){status.textContent='请填写 HTTPS 克隆账号和个人访问令牌';return}
+ button.disabled=true;status.textContent='正在校验令牌…';
+ try{
+ const outcome=typeof verifyAndSaveCodeupToken==='function'
+ ?await verifyAndSaveCodeupToken(pat,account)
+ :{saved:false,result:{error:'凭据模块尚未加载'}};
+ if(!outcome?.saved){status.textContent=(outcome?.result&&(outcome.result.error||gitTokenFailure(outcome.result)))||'云效令牌校验未通过';button.disabled=false;return}
+ token.value='';
+ connect.remove();
+ host.querySelector('[data-codeup-repo-hint]').hidden=true;
+ orgRow.hidden=false;load.hidden=false;
+ status.textContent='';
+ toast('云效 Codeup 授权已保存','ok');
+ host.dispatchEvent(new CustomEvent('codeup-connected',{bubbles:true}));
+ fetchOrganizations();
+ }catch(error){status.textContent=error.message;button.disabled=false}
+ };
+ }else if(connected){
+ fetchOrganizations();
+ }
+}
\ No newline at end of file
diff --git a/web/app/git-http-credentials.js b/web/app/git-http-credentials.js
index 082b0b2f7..3c40b7aec 100644
--- a/web/app/git-http-credentials.js
+++ b/web/app/git-http-credentials.js
@@ -1,4 +1,4 @@
-const GIT_HTTP_PLATFORMS = [['github', 'GitHub / GitHub Enterprise'], ['gitlab', 'GitLab'], ['other', '其他平台']];
+const GIT_HTTP_PLATFORMS = [['github', 'GitHub / GitHub Enterprise'], ['gitlab', 'GitLab'], ['codeup', '云效 Codeup'], ['other', '其他平台']];
// Mirrors gitwork.HTTPSHostScope closely enough to prefill the form; the server
// remains the authority on what a host scope is.
@@ -9,6 +9,9 @@ function gitHTTPHostScope(raw) {
}
function gitHTTPDefaultUsername(platform) {
+ // Codeup authenticates with the personal HTTPS clone account; there is no
+ // shared placeholder username like x-access-token / oauth2.
+ if (platform === 'codeup') return '';
return platform === 'gitlab' ? 'oauth2' : 'x-access-token';
}
@@ -48,7 +51,7 @@ function openGitHTTPCredentials() {
${GIT_HTTP_PLATFORMS.map(([value, label]) => ``).join('')}
- GitHub 和 GitLab 支持 gh / glab 认证和 PR/MR 合并状态同步。其他平台也可由 Agent 创建 PR/MR,合并状态请到托管平台查看。
+ GitHub 和 GitLab 支持 gh / glab 认证和 PR/MR 合并状态同步。云效 Codeup 使用个人访问令牌(PAT)与 HTTPS 克隆账号。其他平台也可由 Agent 创建 PR/MR,合并状态请到托管平台查看。
${credentialFieldHTML({label:'名称', name:'name', type:'text', placeholder:'例如 公司 GitLab', hint:null})}
${credentialFieldHTML({label:'Git 认证用户名', name:'username', type:'text', placeholder:'x-access-token', hint:'按托管平台要求填写;这是 HTTPS 认证用户名,不是提交作者名,通常无法从 Token 推导。'})}
@@ -77,6 +80,16 @@ function openGitHTTPCredentials() {
status.hidden = !message;
}
+ // Codeup names its two secrets differently: the HTTPS clone account and the PAT.
+ function syncPlatformLabels() {
+ const codeup = platform.value === 'codeup';
+ const labelOf = input => input.closest('.credential-field')?.querySelector('span');
+ const usernameLabel = labelOf(username), tokenLabel = labelOf(token);
+ if (usernameLabel) usernameLabel.textContent = codeup ? 'HTTPS 克隆账号' : 'Git 认证用户名';
+ if (tokenLabel) tokenLabel.textContent = codeup ? '个人访问令牌 PAT' : '个人访问令牌';
+ username.placeholder = codeup ? '云效「个人设置 → HTTPS 密码」中的克隆账号' : gitHTTPDefaultUsername(platform.value);
+ }
+
function credentialSummary(cred) {
const platformLabel = (GIT_HTTP_PLATFORMS.find(([value]) => value === cred.platform) || [, cred.platform])[1];
const tags = [platformLabel, cred.managed ? '平台托管' : ''].filter(Boolean);
@@ -109,7 +122,7 @@ function openGitHTTPCredentials() {
platform.value = cred?.platform || 'github';
name.value = cred?.name || '';
username.value = cred?.username || '';
- username.placeholder = gitHTTPDefaultUsername(platform.value);
+ syncPlatformLabels();
token.required = !cred;
token.placeholder = cred ? '留空保留现有令牌' : '粘贴个人访问令牌';
(cred ? name : host).focus();
@@ -137,7 +150,9 @@ function openGitHTTPCredentials() {
creds = await api(id ? `${endpoint}/${encodeURIComponent(id)}` : endpoint, {
method, silent:true, ...(body ? {body:JSON.stringify(body)} : {}),
});
- storeCredentialUser({...credentialUser(), id:user.id, gitHttpCredentialsConfigured:creds.length > 0, gitHubCredentialConfigured:creds.some(credential=>credential.host==='github.com')});
+ const codeupRecord = creds.find(credential => credential.host === 'codeup.aliyun.com') || null;
+ state.codeupCredential = {userId:user.id, record:codeupRecord};
+ storeCredentialUser({...credentialUser(), id:user.id, gitHttpCredentialsConfigured:creds.length > 0, gitHubCredentialConfigured:creds.some(credential=>credential.host==='github.com'), codeupCredentialConfigured:!!codeupRecord});
renderCredentialPanel();
notifyCredentialsChanged();
deleting = '';
@@ -186,13 +201,25 @@ function openGitHTTPCredentials() {
if (editing) return;
const scope = gitHTTPHostScope(host.value);
if (scope === 'github.com') platform.value = 'github';
+ else if (scope === 'codeup.aliyun.com') platform.value = 'codeup';
else if (/(^|\.)gitlab\./.test(scope)) platform.value = 'gitlab';
- username.placeholder = gitHTTPDefaultUsername(platform.value);
- if (!name.value.trim()) name.value = scope;
+ syncPlatformLabels();
+ if (!name.value.trim()) name.value = platform.value === 'codeup' ? '云效 Codeup' : scope;
+ });
+ platform.addEventListener('change', () => {
+ if (!editing && platform.value === 'codeup') {
+ if (!host.value.trim()) host.value = 'codeup.aliyun.com';
+ if (!name.value.trim()) name.value = '云效 Codeup';
+ }
+ syncPlatformLabels();
});
- platform.addEventListener('change', () => { username.placeholder = gitHTTPDefaultUsername(platform.value); });
form.onsubmit = event => {
event.preventDefault();
+ if (platform.value === 'codeup' && !username.value.trim()) {
+ setStatus('请填写云效 HTTPS 克隆账号', true);
+ username.focus();
+ return;
+ }
const body = {
host:host.value, platform:platform.value, name:name.value,
username:username.value.trim() || gitHTTPDefaultUsername(platform.value),
diff --git a/web/app/git-ssh.js b/web/app/git-ssh.js
index 01ba6ebd3..89384ed8c 100644
--- a/web/app/git-ssh.js
+++ b/web/app/git-ssh.js
@@ -38,13 +38,36 @@ globalThis.LoopForgeGitSSH = function parseSSHRepository(raw) {
return { provider: 'ssh', host: endpoint, project: `${host.toLowerCase()}${port === '22' ? '' : ':' + port}/${segments.join('/')}`, name, cloneUrl, webUrl: '' };
};
+// Yunxiao Codeup keeps the organization in the first path segment:
+// https://codeup.aliyun.com/{orgId}/{group}/{repo}.git. Mirrors the server's
+// parseCodeupRepositoryURL: the codeup: shorthand and git@/ssh:// clone forms
+// normalize to the HTTPS identity, authenticated with the per-host Codeup
+// PAT + clone account.
+globalThis.LoopForgeCodeupRepo = function parseCodeupRepository(raw) {
+ let s = String(raw || '').trim().replace(/^git\s+clone\s+/i, '').trim().replace(/^['"]+|['"]+$/g, '');
+ if (!s) return null;
+ if (/^codeup:/i.test(s)) s = 'https://codeup.aliyun.com/' + s.slice('codeup:'.length);
+ s = s.replace(/^(?:git@codeup\.aliyun\.com:|ssh:\/\/git@codeup\.aliyun\.com(?::22)?\/)/i, 'https://codeup.aliyun.com/');
+ if (/^codeup\.aliyun\.com\//i.test(s)) s = 'https://' + s;
+ let u;
+ try { u = new URL(s); } catch { return null; }
+ if (u.hostname.toLowerCase() !== 'codeup.aliyun.com' || u.username || u.password || !['https:', 'http:'].includes(u.protocol)) return null;
+ const parts = u.pathname.replace(/^\/+|\/+$/g, '').split('/');
+ if (parts.length < 3) return null;
+ parts[parts.length - 1] = parts[parts.length - 1].replace(/\.git$/i, '');
+ const path = parts.join('/');
+ if (!/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+){2,}$/.test(path) || parts.some(seg => seg === '.' || seg === '..')) return null;
+ const name = parts[parts.length - 1];
+ return { provider: 'codeup', host: 'codeup.aliyun.com', organizationId: parts[0], project: 'codeup:' + path, name, webUrl: 'https://codeup.aliyun.com/' + path, cloneUrl: 'https://codeup.aliyun.com/' + path + '.git' };
+};
+
// Unknown HTTPS hosts use Git transport without identifying the hosting product.
globalThis.LoopForgeGitHTTPS = function parseHTTPSRepository(raw) {
const address=String(raw||'').trim().replace(/^git clone\s+/i,'');
if(!/^https:\/\//i.test(address)||/[\s\\]/.test(address))return null;
try{
const u=new URL(address),host=u.host.toLowerCase();
- if(u.username||u.password||u.search||u.hash||['github.com','git.example.com'].includes(u.hostname.toLowerCase()))return null;
+ if(u.username||u.password||u.search||u.hash||['github.com','git.example.com','codeup.aliyun.com'].includes(u.hostname.toLowerCase()))return null;
if(!/^[a-z0-9][a-z0-9.-]*(?::[0-9]+)?$/i.test(host)||u.hostname.includes('..')||/^\d+(?:\.\d+){3}$/.test(u.hostname))return null;
const parts=u.pathname.replace(/^\/+|\/+$/g,'').split('/');
if(parts.some(part=>!part||decodeURIComponent(part)==='.'||decodeURIComponent(part)==='..'))return null;
diff --git a/web/app/issues.js b/web/app/issues.js
index ec57b47bd..0be8b4c3b 100644
--- a/web/app/issues.js
+++ b/web/app/issues.js
@@ -544,8 +544,9 @@ function issueFromForm(){
// 就能完成仓库配置。
// repoDisplayPath shows host/path for a parsed repository, e.g. github.com/owner/name.
function repoDisplayPath(info,fallback=''){return info?.provider==='ssh'?(info.project||info.cloneUrl||fallback):info?.webUrl?String(info.webUrl).replace(/^https?:\/\//,''):String(fallback||'')}
-function repoProviderLabel(info){return info?.provider==='ssh'?'Git SSH':info?.provider==='github'?'GitHub':'工蜂'}
+function repoProviderLabel(info){return info?.provider==='ssh'?'Git SSH':info?.provider==='github'?'GitHub':info?.provider==='codeup'?'云效 Codeup':'工蜂'}
function parseGongfengRepoURL(raw){
+ const codeupInfo=globalThis.LoopForgeCodeupRepo?.(raw);if(codeupInfo)return codeupInfo;
const httpsInfo=globalThis.LoopForgeGitHTTPS?.(raw);if(httpsInfo)return httpsInfo;
const sshInfo=globalThis.LoopForgeGitSSH?.(raw);if(sshInfo)return sshInfo;
let publicURL=String(raw||'').trim().replace(/^git clone /,'').replace(/^github:/,'https://github.com/').replace(/^(?:git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/)/,'https://github.com/');
@@ -601,13 +602,18 @@ function renderRepositoryCredentialHint(){
host.sshHintVersion=(host.sshHintVersion||0)+1;
host.hidden=false;
host.removeAttribute('role');
- const configured=!!user.gitHttpCredentialsConfigured;
- const title=configured?'已配置 Git 访问令牌':'仓库可以先保存,代码任务还需要 Token';
- const message=configured?'请确认 Token 已获得目标仓库的访问和写入权限。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。':'使用仓库进行需求分析、访问私有代码或提交 PR 前,请先配置 Git 访问令牌。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。';
+ const codeup=remote?.provider==='codeup';
+ const configured=codeup?!!(user.codeupCredentialConfigured||(typeof codeupCredentialRecord==='function'&&codeupCredentialRecord(user))):!!user.gitHttpCredentialsConfigured;
+ const title=codeup
+ ?(configured?'已配置云效仓库授权':'仓库可以先保存,代码任务还需要云效授权')
+ :(configured?'已配置 Git 访问令牌':'仓库可以先保存,代码任务还需要 Token');
+ const message=codeup
+ ?(configured?'请确认令牌已获得目标仓库的读写权限。SOP 使用需求责任人的令牌,未指定时使用项目 Owner 的令牌。':'使用云效仓库进行需求分析、访问私有代码或提交合并请求前,请先配置云效仓库授权(个人访问令牌 PAT + HTTPS 克隆账号)。SOP 使用需求责任人的凭据,未指定时使用项目 Owner 的凭据。')
+ :(configured?'请确认 Token 已获得目标仓库的访问和写入权限。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。':'使用仓库进行需求分析、访问私有代码或提交 PR 前,请先配置 Git 访问令牌。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。');
host.dataset.configured=String(configured);
- host.innerHTML=`${escapeHTML(title)}${escapeHTML(message)}
`;
+ host.innerHTML=`${escapeHTML(title)}${escapeHTML(message)}
`;
host.querySelector('[data-repository-configure-token]').onclick=()=>{
- $('#repositoryModal').classList.remove('open');gotoCredential('gitHttpCredentials');
+ $('#repositoryModal').classList.remove('open');gotoCredential(codeup?'codeupToken':'gitHttpCredentials');
};
}
function renderRepositoryList(){renderRepositoryCredentialHint();const project=(state.data.projects||[]).find(p=>p.id===state.projectFilter),repos=(state.data.repositories||[]).filter(r=>r.projectId===state.projectFilter);$('#repositoryProjectHint').textContent=`当前项目:${project?.name||'—'}。粘贴 GitHub 链接或 Git SSH 地址;集成分支用于检查多个 SOP 执行后是否存在合并冲突,可留空。`;$('#repositoryList').innerHTML=repos.map(r=>``).join('')||'当前项目还没有绑定代码仓库。
';$('#repositoryList').querySelectorAll('[data-edit-repo]').forEach(b=>b.onclick=()=>fillRepositoryForm((state.data.repositories||[]).find(r=>r.id===b.dataset.editRepo)))}
diff --git a/web/app/project-wizard.js b/web/app/project-wizard.js
index 8c2ef2e55..b7610e07f 100644
--- a/web/app/project-wizard.js
+++ b/web/app/project-wizard.js
@@ -3,7 +3,7 @@
// and can be skipped. Progress lives only in memory.
const PROJECT_WIZARD_STEPS=[
{id:'basic',title:'基本信息',desc:'名称与默认 SOP'},
- {id:'repos',title:'代码仓库',desc:'绑定 GitHub 仓库'},
+ {id:'repos',title:'代码仓库',desc:'绑定 GitHub / 云效仓库'},
{id:'members',title:'项目成员',desc:'Owner 与协作成员'},
{id:'tapd',title:'TAPD 集成',desc:'可选,导入 TAPD 需求'},
{id:'done',title:'完成',desc:'开始使用新项目'},
@@ -104,7 +104,7 @@ async function projectWizardCreate(){
async function projectWizardAddRepo(){
const w=projectWizard,project=projectWizardProject();if(!w||w.saving||!project)return false;
const url=String(w.repo.url||'').trim(),info=parseGongfengRepoURL(url);
- if(!info)return projectWizardFail(url?'请输入 GitHub 链接或有效的 Git SSH 地址。CNB 只支持 HTTPS + 访问令牌。':'请先粘贴 GitHub 链接或 Git SSH 地址','repoUrl');
+ if(!info)return projectWizardFail(url?'请输入 GitHub 链接或有效的 Git SSH 地址。云效 Codeup 仓库请粘贴 HTTPS 链接;CNB 只支持 HTTPS + 访问令牌。':'请先粘贴 GitHub、云效 Codeup 链接或 Git SSH 地址','repoUrl');
if(projectWizardRepos().some(r=>info.provider==='ssh'?r.cloneUrl===info.cloneUrl:r.gongfengProjectId===info.project))return projectWizardFail(`仓库 ${info.project} 已经绑定到这个项目`,'repoUrl');
const payload={projectId:project.id,provider:info.provider||'gongfeng',name:info.name,gongfengProjectId:info.project,webUrl:info.webUrl,cloneUrl:info.cloneUrl,defaultBranch:String(w.repo.branch||'').trim()||'main',integrateBranch:String(w.repo.integrate||'').trim(),localPath:'',repoUrl:url};
const makeDefault=projectNeedsDefaultRepository(project);
@@ -244,16 +244,18 @@ function projectWizardBasicHTML(w){
}
function projectWizardRepoHint(url){
const raw=String(url||'').trim(),info=raw?parseGongfengRepoURL(raw):null;
- if(!raw)return '例如 https://github.com/owner/repo 或 git@gitlab.com:group/repo.git';
+ if(!raw)return '例如 https://github.com/owner/repo、https://codeup.aliyun.com/组织ID/仓库.git 或 git@gitlab.com:group/repo.git';
if(info?.provider==='ssh')return `识别为 Git SSH · ${escapeHTML(info.name)}。请管理员信任该主机,并在个人配置中添加 Git SSH 密钥。`;
- return info?`识别为 ${escapeHTML(info.name)} · ${escapeHTML(repoDisplayPath(info,info.project))}`:'请输入 GitHub 链接或 Git SSH 地址';
+ if(info?.provider==='codeup')return `识别为云效 Codeup · ${escapeHTML(info.name)}。克隆与推送使用个人配置中的云效仓库授权(PAT + HTTPS 克隆账号)。`;
+ return info?`识别为 ${escapeHTML(info.name)} · ${escapeHTML(repoDisplayPath(info,info.project))}`:'请输入 GitHub、云效 Codeup 链接或 Git SSH 地址';
}
function projectWizardReposHTML(w){
const project=projectWizardProject()||{},repos=projectWizardRepos();
const list=repos.map(r=>{const path=r.cloneUrl||r.gongfengProjectId||'',name=r.name||path||r.id,shown=repoDisplayPath(parseGongfengRepoURL(r.provider==='ssh'?r.cloneUrl:r.webUrl||path),path);return `${pwIcon('repo',14,1.9)}${escapeHTML(name)}${escapeHTML(shown)}${escapeHTML(r.defaultBranch||'main')}${r.integrateBranch?`${escapeHTML(r.integrateBranch)}`:''}${r.id===project.defaultRepositoryId?'默认':''}`}).join('');
const body=(list?`${list}`:'')
+''
- +pwField('GitHub 链接或 Git SSH 地址',``,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})
+ +''
+ +pwField('GitHub / 云效链接或 Git SSH 地址',``,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})
+`${pwField('主分支',``,{for:'pwRepoBranch'})}${pwField('集成分支',``,{for:'pwRepoIntegrate'})}`
+``;
return projectWizardHeadHTML(w,'代码仓库','Agent 执行 SOP 时会克隆这些仓库并在工作分支上提交。第一个仓库会自动设为默认。')
@@ -342,6 +344,11 @@ function renderProjectWizard(){
const url=host.querySelector('[name="repoUrl"]'),branch=host.querySelector('[name="repoBranch"]');
url.value=w.repo.url;branch.value=w.repo.branch;syncProjectWizardField(url);
});
+ if(w.step==='repos'&&typeof mountCodeupRepoPicker==='function')mountCodeupRepoPicker(host.querySelector('[data-codeup-repositories]'),repository=>{
+ w.repo.url=repository.html_url||repository.clone_url;w.repo.branch=repository.default_branch||'main';
+ const url=host.querySelector('[name="repoUrl"]'),branch=host.querySelector('[name="repoBranch"]');
+ url.value=w.repo.url;branch.value=w.repo.branch;syncProjectWizardField(url);
+ });
focusProjectWizard();
}
function focusProjectWizard(){
diff --git a/web/app/repo_drawer.js b/web/app/repo_drawer.js
index b36393301..94b0baecb 100644
--- a/web/app/repo_drawer.js
+++ b/web/app/repo_drawer.js
@@ -53,6 +53,11 @@ function openRepoDrawer(repoId=''){
f.elements.defaultBranch.value=repository.default_branch||'main';
syncRepoDrawerDetect();
});
+ if(typeof mountCodeupRepoPicker==='function')mountCodeupRepoPicker(drawer.querySelector('[data-codeup-repositories]'),repository=>{
+ f.elements.repoUrl.value=repository.html_url||repository.clone_url;
+ f.elements.defaultBranch.value=repository.default_branch||'main';
+ syncRepoDrawerDetect();
+ });
setTimeout(()=>f.elements.repoUrl.focus(),120);
}
function closeRepoDrawer(opt){
diff --git a/web/app/workbench.js b/web/app/workbench.js
index 099ecbd09..5f01fa0f8 100644
--- a/web/app/workbench.js
+++ b/web/app/workbench.js
@@ -62,6 +62,13 @@ const CREDENTIAL_KINDS=[
guide:[['打开 GitHub「Settings → Developer settings → Personal access tokens」','https://github.com/settings/tokens','前往 GitHub 申请个人访问令牌'],['新建令牌,为目标仓库授予 Contents 和 Pull requests 的读写权限'],['复制令牌粘贴到下方,保存前会自动校验权限']],
placeholder:'请输入个人访问令牌(PAT)',hint:'保存前会先校验令牌有效性与权限',
impact:'依赖私有仓库的 SOP 将无法克隆或推送仓库。'},
+ {key:'codeupToken',group:'platform',name:'云效 Codeup',short:'云效仓库授权',logo:'codeup',monochrome:true,
+ use:'克隆云效私有仓库、创建任务分支、推送交付产物',
+ description:'用于克隆云效 Codeup 私有仓库、创建任务分支及推送交付产物,使用个人访问令牌(PAT)与 HTTPS 克隆账号认证。',
+ guide:[['打开云效 Codeup「个人设置 → 个人访问令牌」,新建令牌并授予代码读写权限','https://help.aliyun.com/zh/yunxiao/user-guide/personal-authentication-settings/','查看云效认证设置说明'],['在「个人设置 → HTTPS 密码」查看 HTTPS 克隆账号'],['填写克隆账号并粘贴令牌,保存前会自动校验']],
+ placeholder:'请输入云效个人访问令牌(PAT)',hint:'保存前会先校验令牌有效性与权限',
+ extra:{name:'codeupCloneUsername',label:'HTTPS 克隆账号',placeholder:'云效「HTTPS 密码」页的克隆账号',required:()=>true,requiredMessage:'请填写 HTTPS 克隆账号'},
+ impact:'依赖云效私有仓库的 SOP 将无法克隆或推送仓库。'},
{key:'gitSshKey',group:'platform',name:'Git SSH',short:'Git SSH 密钥',icon:'key',
use:'SSH 密钥用于克隆和推送;创建 PR/MR 需要访问令牌',dialog:()=>openGitSSHKeys(),action:'管理密钥'},
{key:'gitHttpCredentials',group:'platform',name:'Git HTTPS',short:'Git 访问令牌',icon:'lock',
@@ -496,7 +503,12 @@ const CREDENTIAL_PAT_WARNING='请填写 GitHub 个人访问令牌(PAT)kind.key===key)||null}
// Kinds with a dialog manage several entries there instead of the inline editor.
function credentialDialog(key){return credentialKind(key)?.dialog||null}
-function credentialConfigured(kind,user){if(kind.key==='gitToken')return !!user.gitHubCredentialConfigured;return !!credentialValue(user,kind.agentCli?kind.key+'.apiKeyConfigured':kind.key+'Configured')}
+// The Codeup card reuses the per-host Git HTTPS credential for codeup.aliyun.com.
+// The user summary only carries a GitHub boolean, so the Codeup record is cached
+// from the credential list (and the flag is computed client-side after saves).
+function codeupCredentialRecord(user){const cached=state.codeupCredential;return cached&&Number(cached.userId)===Number(user?.id)?cached.record||null:null}
+function codeupVerifyFor(user){return state.codeupVerify&&Number(state.codeupVerify.userId)===Number(user?.id)?state.codeupVerify:null}
+function credentialConfigured(kind,user){if(kind.key==='gitToken')return !!user.gitHubCredentialConfigured;if(kind.key==='codeupToken')return !!user.codeupCredentialConfigured||!!codeupCredentialRecord(user);return !!credentialValue(user,kind.agentCli?kind.key+'.apiKeyConfigured':kind.key+'Configured')}
function credentialUser(){return userById(state.currentUser?.id)||{}}
function credentialUI(){return state.credentialUI||(state.credentialUI={open:null,filter:'all',closed:{}})}
function credentialGlyph(name,size=16,cls=''){return ``}
@@ -544,7 +556,7 @@ function refreshCredentialEnvironmentLinks(scope,value){
}
function credentialExtraError(kind,value,protocol){
const text=String(value||'').trim();
- if(!text&&kind.extra?.required?.(protocol))return '请填写 Base URL';
+ if(!text&&kind.extra?.required?.(protocol))return kind.extra.requiredMessage||'请填写 Base URL';
if(!kind.extra?.url||!text)return '';
try{const url=new URL(text);if(url.protocol==='http:'||url.protocol==='https:')return ''}catch{}
return '请填写以 http:// 或 https:// 开头的地址';
@@ -584,8 +596,8 @@ function gitTokenFailure(result){
}
function credentialStatus(kind,user){
if(!credentialConfigured(kind,user))return 'empty';
- if(kind.key!=='gitToken')return 'ok';
- const verify=gitTokenVerifyFor({id:state.currentUser?.id});
+ if(kind.key!=='gitToken'&&kind.key!=='codeupToken')return 'ok';
+ const verify=kind.key==='codeupToken'?codeupVerifyFor({id:state.currentUser?.id}):gitTokenVerifyFor({id:state.currentUser?.id});
if(verify?.busy)return 'busy';
return gitTokenFailure(verify?.result)?'err':'ok';
}
@@ -606,6 +618,15 @@ function credentialSubline(kind,user){
if(!result.valid)return source+dot+`缺少权限 ${escapeHTML((result.missing||[]).join('、'))}`;
return source+dot+'令牌有效'+(result.scopes?.length?dot+`${escapeHTML(result.scopes.join(' · '))}`:'');
}
+ if(kind.key==='codeupToken'){
+ const verify=codeupVerifyFor({id:state.currentUser?.id}),result=verify?.result,record=codeupCredentialRecord(user);
+ const source='个人访问令牌'+(record?.username?dot+`${escapeHTML(record.username)}`:'');
+ if(verify?.busy)return source+dot+'正在校验…';
+ if(!result)return source+dot+use;
+ if(result.error)return source+dot+`${escapeHTML(result.error)}`;
+ if(!result.valid)return source+dot+`缺少权限 ${escapeHTML((result.missing||[]).join('、'))}`;
+ return source+dot+'令牌有效';
+ }
if(kind.key==='codeBuddyApiKey'){
const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw);
return `网络环境${env?`${escapeHTML(env.label)}`:`「${escapeHTML(raw)}」无法识别,按国际站连接`}${dot}${use}`;
@@ -626,8 +647,9 @@ function credentialFieldHTML({label,note='',name,type='password',value='',placeh
function credentialOAuthHTML(label,note){
return (typeof githubConnectHTML==='function'?githubConnectHTML():'')+``;
}
-function credentialPatWarningHTML(show){return `${credentialGlyph('alert',14)}${CREDENTIAL_PAT_WARNING}`}
+function credentialPatWarningHTML(show,text=CREDENTIAL_PAT_WARNING){return `${credentialGlyph('alert',14)}${text}`}
const GIT_TOKEN_REPLACE_HINT='保存后替换当前的令牌,对下一次任务生效';
+const CODEUP_PAT_WARNING='请填写云效 个人访问令牌(PAT) 并授予代码读写权限;令牌权限不足会导致克隆 / 推送仓库失败。';
function credentialAgo(at){
const seconds=Math.max(0,Math.round((Date.now()-at)/1000));
if(seconds<60)return '刚刚';
@@ -663,8 +685,38 @@ function gitTokenEditorHTML(kind,user){
下一次运行你负责的任务时生效,可随时在列表中展开编辑。
${credentialGlyph('alert',13)}${escapeHTML(wizard.error)}
` - :wizard.saving&&kind.key==='gitToken'?`${credentialSpinner(13)}正在校验令牌有效性与权限…
` - :kind.key==='gitToken'?`${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限
` + :wizard.saving&&verifyFirst?`${credentialSpinner(13)}正在校验令牌有效性与权限…
` + :verifyFirst?`${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限
` :warning?`${credentialGlyph('alert',13)}${escapeHTML(warning)}
`:''; return `