From ae93f7fe9ff5bbc52ee93baca8044f20fb7c3eca Mon Sep 17 00:00:00 2001 From: promise <1397862207@qq.com> Date: Fri, 20 Nov 2026 00:10:45 +0800 Subject: [PATCH 1/4] feat(executor): add Qoder CN (qodercn) as a first-class agent CLI Register qodercn across domain, runtime, catalog, runner detection, model catalog and sandbox/on-demand install (npm @qodercn-ai/qoderclicn). Bind the responsible user's personal access token via QODERCN_PERSONAL_ACCESS_TOKEN in a private HOME, merge mcpServers/model/hooks into .qoder-cn/settings.json, and reject custom Base URLs (official endpoint only). Treat its stream-json as Claude-Code-compatible NDJSON. Surface Qoder CN in web and chatbot executor lists, PAT-only credential card, i18n and dark-theme invert, using the official brand mark extracted from the Qoder CN client. Document it in both READMEs and the native-cli guide. --- README.md | 3 +- README.zh-CN.md | 7 +- chatbot/src/ModelProviderIcon.jsx | 1 + chatbot/src/assets/provider-logos/README.md | 4 + chatbot/src/assets/provider-logos/SOURCE.md | 6 +- chatbot/src/assets/provider-logos/qoder.svg | 1 + chatbot/src/engines.js | 3 +- chatbot/src/useChat.js | 1 + docs/conversation-native-cli.md | 2 + internal/domain/agent.go | 2 +- internal/httpapi/cli_models_probe.go | 12 ++ internal/httpapi/cli_models_probe_test.go | 29 +++ internal/httpapi/executor_models.go | 8 + internal/repo/catalog.go | 1 + internal/runner/detect.go | 3 + internal/runtime/agent_cli.go | 20 ++- internal/runtime/agent_cli_qodercn.go | 103 +++++++++++ internal/runtime/agent_cli_qodercn_test.go | 184 ++++++++++++++++++++ internal/runtime/agent_cli_stream.go | 14 ++ internal/runtime/cli_ondemand.go | 1 + internal/runtime/conversation_approval.go | 15 ++ internal/runtime/conversation_process.go | 4 +- internal/runtime/conversation_sandbox.go | 1 + internal/runtime/provider_agentcli.go | 15 ++ web/app/agents.js | 2 +- web/app/flow-canvas.css | 2 +- web/app/runners.js | 5 +- web/app/sops.js | 4 +- web/app/workbench.js | 8 +- web/i18n-en.js | 12 +- web/images/credentials/qoder.svg | 1 + web/orchestrate.js | 2 +- web/product-v4.css | 2 +- web/syntax_test.go | 17 +- 34 files changed, 465 insertions(+), 30 deletions(-) create mode 100644 chatbot/src/assets/provider-logos/qoder.svg create mode 100644 internal/runtime/agent_cli_qodercn.go create mode 100644 internal/runtime/agent_cli_qodercn_test.go create mode 100644 web/images/credentials/qoder.svg diff --git a/README.md b/README.md index 8141eec35..23b42ccf1 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ https://github.com/user-attachments/assets/8af401d9-1aae-427c-b4bc-455c12d17beb **LoopForge** is a self-hosted workspace where your team ships software with coding agents. Describe what you need to **Main Bot** in chat: it opens a Docker sandbox, checks out your repositories, delegates to project roles, and opens the PR. When a way of working proves itself, save it as an **SOP** (a standard workflow of agents, scripts and human gates) so the next requirement is delivered the same way, with review and approval built in. -Coding-agent CLIs do the work: CodeBuddy, Codex, Claude Code, OpenCode, Cursor CLI, Antigravity, Kimi Code, Pi, DeepSeek Harness and ZCode. LoopForge adds the roles, sandboxes, checkpoints and history around them, all on your own infrastructure under the MIT license. +Coding-agent CLIs do the work: CodeBuddy, Codex, Claude Code, OpenCode, Cursor CLI, Antigravity, Kimi Code, Pi, DeepSeek Harness, ZCode and Qoder CN. LoopForge adds the roles, sandboxes, checkpoints and history around them, all on your own infrastructure under the MIT license. ## Two ways to work @@ -123,6 +123,7 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl | **DeepSeek Harness** | Personal key only | In the Docker image | | **Cursor CLI · Antigravity** | Personal key only | Provider installer on first chat use; not installed into SOP sandboxes | | **ZCode** | Personal key only | Not bundled; install it on the service or execution machine PATH | + | **Qoder CN** | Personal access token (PAT) | npm `@qodercn-ai/qoderclicn` or the official install script | The seven agent CLIs after Claude Code keep their model and MCP configuration in a private home directory per run, so they always use the responsible user's own key and Base URL from personal settings, even on a connected execution machine. When rolling them out to a team, each member configures their own credentials. First-use installs need npm or provider access; [native deployments](docs/deployment.md#workers-and-runners) need the CLI for the executor you choose. - **GitHub is optional.** All built-in generic SOPs run without a repository: product SOPs deliver documents, and new frontend/backend projects deliver source files in the task workspace. Bug fixes still need source code and reproduction details. Connect a repository when you work on existing code or want PRs. diff --git a/README.zh-CN.md b/README.zh-CN.md index d70bf45ea..0f0489799 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -37,7 +37,7 @@ https://github.com/user-attachments/assets/10b8ae2e-d7e7-4b78-8876-c45818d4a08f **LoopForge** 是一个可自主部署的团队工作台,让你和编程 Agent 一起交付软件。在对话里把需求告诉 **Main Bot**:它会按需打开 Docker 沙箱、检出项目仓库、把任务分派给项目角色,最后提交 PR。某种做法被验证有效后,把它存成 **SOP**(由 Agent、脚本和人工关口组成的标准交付流程),下一个需求就按同样的方式交付,评审和验收都在流程里。 -干活的是编程 Agent CLI:CodeBuddy、Codex、Claude Code、OpenCode、Cursor CLI、Antigravity、Kimi Code、Pi、DeepSeek Harness 和 ZCode;LoopForge 负责它们外面的角色、沙箱、检查点和留痕,全部运行在你自己的环境里,MIT 开源。 +干活的是编程 Agent CLI:CodeBuddy、Codex、Claude Code、OpenCode、Cursor CLI、Antigravity、Kimi Code、Pi、DeepSeek Harness、ZCode 和 Qoder CN;LoopForge 负责它们外面的角色、沙箱、检查点和留痕,全部运行在你自己的环境里,MIT 开源。 ## 两种工作方式 @@ -67,7 +67,7 @@ https://github.com/user-attachments/assets/10b8ae2e-d7e7-4b78-8876-c45818d4a08f - **角色分离。** 方案、实现、评审、测试各有独立的角色提示词、执行器、模型、规则、Skills 和 MCP 工具;同一个角色既能做 SOP 节点,也能在对话中作为子 Agent 调用。 - **人在回路。** 在关键节点设置人工审批:看完报告再放行,或打回到指定环节返工。 - **可观测、可续跑。** 节点状态、工具轨迹、日志和产物集中呈现;支持暂停、重试失败步骤、从任意节点重跑。 -- **技术栈和服务器都是你的。** 执行器支持 10 种编程 Agent CLI,从 CodeBuddy、Codex、Claude Code 到 OpenCode、Cursor CLI 等;工具接入 GitHub、Skills、MCP;运行环境可选 Docker 沙箱或你自己的机器。 +- **技术栈和服务器都是你的。** 执行器支持 11 种编程 Agent CLI,从 CodeBuddy、Codex、Claude Code 到 OpenCode、Cursor CLI 等;工具接入 GitHub、Skills、MCP;运行环境可选 Docker 沙箱或你自己的机器。 ## 快速开始 @@ -112,7 +112,7 @@ GitLab、Gitea、Gogs 等托管可[配置 Git SSH](docs/deployment.md#git-reposi
-- **执行器。** 在首页输入框旁从 10 种 CLI 中选择一种,再选择模型。每个 SOP 角色都可以独立选择执行器(内置角色默认 CodeBuddy)。需求澄清、通知 AI 汇总、Bot 回复和运行评测目前使用 CodeBuddy,这些入口的模型列表只列 CodeBuddy 模型,服务端收到其他 CLI 的模型会直接拒绝并说明原因,不会悄悄换成 CodeBuddy;定时助手任务使用任务所选的执行器。 +- **执行器。** 在首页输入框旁从 11 种 CLI 中选择一种,再选择模型。每个 SOP 角色都可以独立选择执行器(内置角色默认 CodeBuddy)。需求澄清、通知 AI 汇总、Bot 回复和运行评测目前使用 CodeBuddy,这些入口的模型列表只列 CodeBuddy 模型,服务端收到其他 CLI 的模型会直接拒绝并说明原因,不会悄悄换成 CodeBuddy;定时助手任务使用任务所选的执行器。 | 执行器 | 凭据 | 安装方式 | | --- | --- | --- | @@ -123,6 +123,7 @@ GitLab、Gitea、Gogs 等托管可[配置 Git SSH](docs/deployment.md#git-reposi | **DeepSeek Harness** | 仅个人 Key | Docker 镜像内置 | | **Cursor CLI · Antigravity** | 仅个人 Key | 首次在对话中使用时通过厂商安装脚本安装;不会装进 SOP 沙箱 | | **ZCode** | 仅个人 Key | 未内置,需安装到服务或执行机器的 PATH 中 | + | **Qoder CN** | 个人访问令牌(PAT) | npm `@qodercn-ai/qoderclicn` 或官方安装脚本 | Claude Code 之后的 7 种 Agent CLI 每次运行都在私有 HOME 目录里生成模型和 MCP 配置,因此始终使用需求责任人在个人设置中填写的 Key 和 Base URL,即使在已连接的执行机器上也一样。团队推广时,每位成员需要各自配置凭据。首次安装需要能访问 npm 或对应厂商;[原生部署](docs/deployment.md#workers-and-runners)需安装所选执行器的 CLI。 - **GitHub 可选。** 所有内置通用 SOP 都可以不绑定仓库运行:产品方案交付文档,前后端新项目在任务工作区交付源码;缺陷修复仍需提供待修代码和复现材料。需要修改已有代码或提交 PR 时再绑定仓库。 diff --git a/chatbot/src/ModelProviderIcon.jsx b/chatbot/src/ModelProviderIcon.jsx index 48c5463d0..f2cac2a78 100644 --- a/chatbot/src/ModelProviderIcon.jsx +++ b/chatbot/src/ModelProviderIcon.jsx @@ -26,6 +26,7 @@ const modelBrands = [ [/^(?:doubao|seed|seedream|bytedance)(?:$|[-_.\s:\d])/i, "doubao"], [/^(?:ernie|wenxin|baidu|qianfan)(?:$|[-_.\s:\d])/i, "qianfan"], [/^(?:zai|z\.ai)(?:$|[-_.\s:\d])/i, "zai"], + [/^qoder(?:cn)?(?:$|[-_.\s:\d])/i, "qoder"], ]; const fallbackBrands = new Set([ "codebuddy", "cursor", "opencode", "openrouter", "siliconflow", "trae", diff --git a/chatbot/src/assets/provider-logos/README.md b/chatbot/src/assets/provider-logos/README.md index bdf305b0a..ac1f0a411 100644 --- a/chatbot/src/assets/provider-logos/README.md +++ b/chatbot/src/assets/provider-logos/README.md @@ -13,6 +13,10 @@ requests to an image host. - `pi.svg` is a plain π glyph drawn locally, not from Grasp. It is the same mark as `web/images/credentials/pi.svg`, bundled here for the chat CLI selector. +- `qoder.svg` is the official Qoder CN brand mark, extracted from the installed + Qoder CN client's `qoderCnIdeLogo` vector asset and recolored to a monochrome + glyph (background removed). It is the same mark as + `web/images/credentials/qoder.svg`, bundled here for the chat CLI selector. - `openai.svg` comes from the [OpenAI 2025 logo package](https://cdn.openai.com/brand/OpenAI-Logos-2025.zip). `codex.svg` uses the same official OpenAI blossom because OpenAI does not publish a separate Codex mark in that package or in the official Codex CLI diff --git a/chatbot/src/assets/provider-logos/SOURCE.md b/chatbot/src/assets/provider-logos/SOURCE.md index 5d1994e7a..48927a453 100644 --- a/chatbot/src/assets/provider-logos/SOURCE.md +++ b/chatbot/src/assets/provider-logos/SOURCE.md @@ -1,9 +1,11 @@ # Bundled model brand artwork -Except for `pi.svg`, these SVGs and the accompanying README.md and +Except for `pi.svg` and `qoder.svg`, these SVGs and the accompanying README.md and LICENSE.lobe-icons were originally copied from the Grasp repository, web/src/assets/provider-logos. `pi.svg` reuses the local π glyph from -`web/images/credentials/pi.svg`; README.md records this addition. The original Grasp +`web/images/credentials/pi.svg`; `qoder.svg` reuses the official Qoder CN brand +mark (monochrome, background removed) from +`web/images/credentials/qoder.svg`; README.md records these additions. The original Grasp MIT notice is retained as LICENSE.grasp. README.md records each artwork's own source and applicable license, including official brand artwork and Simple Icons. diff --git a/chatbot/src/assets/provider-logos/qoder.svg b/chatbot/src/assets/provider-logos/qoder.svg new file mode 100644 index 000000000..b6bd4484c --- /dev/null +++ b/chatbot/src/assets/provider-logos/qoder.svg @@ -0,0 +1 @@ +Qoder CN diff --git a/chatbot/src/engines.js b/chatbot/src/engines.js index d0bf0943f..3bff1c443 100644 --- a/chatbot/src/engines.js +++ b/chatbot/src/engines.js @@ -6,6 +6,7 @@ export const defaultEngine = "codebuddy"; const brands = { codebuddy: "codebuddy", codex: "codex", "claude-code": "claude", opencode: "opencode", cursor: "cursor", agy: "gemini", kimi: "kimi", pi: "pi", dsh: "deepseek", zcode: "zhipu", + qodercn: "qoder", }; export const engineBrand = (id) => brands[id] || ""; @@ -30,7 +31,7 @@ export function engineMissingKeyMessage(engine) { } // CLIs a session Executor can name when the reply was saved before model prefixes. -const legacyEngines = new Set(["codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"]); +const legacyEngines = new Set(["codex", "claude-code", "opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode", "qodercn"]); function modelHasEnginePrefix(id) { const prefix = /^([a-z][a-z0-9-]*):./.exec(id || "")?.[1]; diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 50c626aed..1b7ee37bb 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -39,6 +39,7 @@ export const EXECUTORS = [ { id: "pi", icon: "terminal", label: "Pi", detail: "使用 Pi 与个人 API Key。" }, { id: "dsh", icon: "terminal", label: "DeepSeek Harness", detail: "使用 DeepSeek Harness 与个人 API Key。" }, { id: "zcode", icon: "terminal", label: "ZCode", detail: "使用 ZCode 与个人 API Key。" }, + { id: "qodercn", icon: "terminal", label: "Qoder CN", detail: "使用 Qoder CN 与个人访问令牌(PAT)。" }, ]; const EXECUTOR_KEY = "loopforge.assistant.executor"; function knownExecutor(id) { diff --git a/docs/conversation-native-cli.md b/docs/conversation-native-cli.md index f5c490273..b6f9031c3 100644 --- a/docs/conversation-native-cli.md +++ b/docs/conversation-native-cli.md @@ -34,6 +34,8 @@ CLI 菜单中的「模型列表」与个人配置共用当前用户的模型目 ZCode 可通过 GLM Coding Plan 的 API Key 和套餐专用端点使用订阅额度。Start Plan 的额度需要登录 ZCode 账号,无法通过 API Key 使用。详见 [ZCode 模型配置](https://zcode.z.ai/cn/docs/configuration)。 +Qoder CN 使用个人配置中保存的个人访问令牌(PAT),运行时经 `QODERCN_PERSONAL_ACCESS_TOKEN` 注入私有 HOME,配置目录隔离在 `QODERCN_CONFIG_DIR`;仅支持官方端点,不支持自定义 Base URL,本机 `/login` 登录态不被沙箱复用。模型可留空(CLI 默认)或指定后经 `QODERCN_MODEL` 传入。详见 [Qoder CN CLI 认证](https://docs.qoder.cn/cli/authentication)。 + 原生会话的工具回调在执行机器上中继。宿主进程使用 Docker host gateway;通过 docker.sock 管理工作区的容器进程自动识别自身容器网络,工作区加入相同网络并访问该地址。自定义路由可通过 `AGENTFLOW_CONVERSATION_RELAY_HOST` 和 `AGENTFLOW_CONVERSATION_DOCKER_NETWORK` 显式指定工作区能访问的执行进程地址与 Docker 网络。会话目录会以相同路径挂进工作区,而 docker.sock 背后的 Docker 守护进程按自己所在主机解析挂载源,因此容器内的平台进程须把 `AGENTFLOW_CONVERSATION_DIR` 设在与宿主机同路径挂载的目录中;`compose.yaml` 将其设为 `${LOOPFORGE_DATA_DIR}/conversations`。Runner 不读该变量,原生会话目录固定在其工作区根目录的 `.conversations` 下,容器内运行 Runner 时须同路径挂载该工作区目录。未设置时会话目录位于 `AGENTFLOW_ASSISTANT_SESSION_DIR` 下,该目录在命名卷里时打开工作区会报 `mkdirat ... read-only file system`。附件等按用户保存的助手数据仍在 `AGENTFLOW_ASSISTANT_SESSION_DIR`,不挂进工作区。Docker 工作区直接在主容器中运行 SOP 脚本和 CLI。历史容器存在指令遮蔽挂载时,工作区下次取得执行权后会重建容器并保留工作区文件。标记为重建时运行的准备脚本随后在新容器补跑。 模式交接时,交接工具要求模型只回复一句「好的。」再结束旧阶段,交接之后的展示由平台隐藏;不要求“不输出任何内容”,否则模型可能只产出推理、没有正文的回合,该回合写入原生日志后,续接时会被模型服务拒绝(如 `the conversation must end with a user message`)。交接工具成功后,旧阶段即使未输出 `type=result` 或异常退出,也继续完成交接。续接原生会话时,如果原生日志缺失,或模型服务在本阶段产生任何输出或工具调用之前就拒绝了续接(400/422、会话结构无效、无结果退出),平台用完整对话上下文新建一次原生会话重试;已有输出或工具调用的中断,以及鉴权、限流、额度、网络、执行机器不可用等原因,仍续接原会话或直接报错,不重复执行副作用。 diff --git a/internal/domain/agent.go b/internal/domain/agent.go index bca6dcb59..eb9eb556f 100644 --- a/internal/domain/agent.go +++ b/internal/domain/agent.go @@ -22,7 +22,7 @@ var ExecutorEffortLevels = map[string][]string{ // AgentCLIExecutorKinds are the agent CLIs beyond CodeBuddy / Codex / Claude // Code. Their model and MCP configuration lives in a private HOME, so they // only run with the responsible user's personal credentials. -var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"} +var AgentCLIExecutorKinds = []string{"opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode", "qodercn"} func IsAgentCLIKind(kind string) bool { kind = strings.TrimSpace(kind) diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.go index 398bb685c..62c86539b 100644 --- a/internal/httpapi/cli_models_probe.go +++ b/internal/httpapi/cli_models_probe.go @@ -117,6 +117,18 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { h.probeCursorModels(c, apiKey) return } + if engine == runtime.AgentCLIQoderCN { + // Qoder CN only reaches its official endpoint with a personal access + // token and publishes no model list, so the CLI default is the catalog. + if baseURL != "" { + c.JSON(http.StatusOK, cliModelProbeResult{Error: "Qoder CN 仅支持官方端点(个人访问令牌),不支持自定义 Base URL"}) + return + } + if apiKey != "" { + c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(engine)), Source: "official"}) + return + } + } if baseURL == "" && apiKey == "" { c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(engine)), Source: "builtin"}) return diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.go index 447e17708..3a7c19460 100644 --- a/internal/httpapi/cli_models_probe_test.go +++ b/internal/httpapi/cli_models_probe_test.go @@ -93,3 +93,32 @@ gemini-4-argon-high - Gemini 4 Argon High t.Fatalf("families:\n got %v\nwant %v", got, want) } } + +// Qoder CN only reaches its official endpoint with a PAT and publishes no +// model list, so the probe returns the built-in CLI default and never calls a +// Base URL; a custom Base URL is rejected. +func TestProbeCLIModelsQoderCNOfficialOnly(t *testing.T) { + h, owner := workbenchFixture(t) + original := assistantEngineDiscover + t.Cleanup(func() { assistantEngineDiscover = original }) + assistantEngineDiscover = func(context.Context, bool, string, string) ([]assistantDiscoveredModel, error) { + t.Fatal("qodercn must not probe a model endpoint") + return nil, nil + } + handlers := &usersHandlers{deps: h.deps} + probe := func(body string) string { + c, w := workbenchContext(owner, http.MethodPost, "/", bytes.NewBufferString(body)) + c.Params = gin.Params{{Key: "id", Value: strconv.FormatInt(owner.ID, 10)}} + handlers.probeCLIModels(c) + if w.Code != http.StatusOK { + t.Fatalf("code %d: %s", w.Code, w.Body.String()) + } + return w.Body.String() + } + if out := probe(`{"engine":"qodercn","apiKey":"pat","baseUrl":""}`); !strings.Contains(out, `"source":"official"`) || !strings.Contains(out, `"id":"default"`) { + t.Fatalf("official catalog: %s", out) + } + if out := probe(`{"engine":"qodercn","apiKey":"pat","baseUrl":"https://gw.example"}`); !strings.Contains(out, "官方端点") { + t.Fatalf("custom Base URL must be rejected: %s", out) + } +} diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index f59dba1f8..52f02ff18 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -148,6 +148,14 @@ func executorModelCatalogs() map[string]executorModelCatalog { {ID: "glm-5.3-flash", Name: "GLM-5.3 Flash"}, }, }, + // Qoder CN picks its own model on the official endpoint; "default" + // keeps that choice, and a custom ID is passed through QODERCN_MODEL. + "qodercn": { + CustomModel: true, + Models: []executorModelInfo{ + {ID: "default", Name: "CLI 默认"}, + }, + }, } } diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go index 369eb6c85..eae69bfd2 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -244,6 +244,7 @@ func BuiltInExecutors() []domain.ExecutorDefinition { {ID: "pi", Name: "Pi", Kind: "pi", Binary: "pi", Protocol: "stream-json"}, {ID: "dsh", Name: "DeepSeek Harness", Kind: "dsh", Binary: "dsh", Protocol: "stream-json"}, {ID: "zcode", Name: "ZCode", Kind: "zcode", Binary: "zcode", Protocol: "stream-json"}, + {ID: "qodercn", Name: "Qoder CN", Kind: "qodercn", Binary: "qodercn", Protocol: "stream-json"}, } } diff --git a/internal/runner/detect.go b/internal/runner/detect.go index de5864a9c..b7842890f 100644 --- a/internal/runner/detect.go +++ b/internal/runner/detect.go @@ -47,6 +47,9 @@ var defaultProviders = []providerSpec{ // The official ZCode has no npm package and its --help omits // --output-format, so compatibility is probed with the flags we pass. {Kind: "zcode", Binary: "zcode", VersionFlags: []string{"--output-format", "stream-json", "--mode", "yolo"}}, + // Qoder CN ships an npm package and is found on PATH; it has no reliable + // non-interactive update subcommand. + {Kind: "qodercn", Binary: "qodercn"}, } // terminalProviderKind is the built-in remote-terminal capability: the diff --git a/internal/runtime/agent_cli.go b/internal/runtime/agent_cli.go index d91a032aa..22212133e 100644 --- a/internal/runtime/agent_cli.go +++ b/internal/runtime/agent_cli.go @@ -26,6 +26,7 @@ const ( AgentCLIPi = "pi" AgentCLIDeepSeek = "dsh" AgentCLIZCode = "zcode" + AgentCLIQoderCN = "qodercn" ) // AgentCLIKinds is the display order of the agent CLIs. @@ -66,8 +67,9 @@ func AgentCLINeedsBaseURL(kind, protocol string) bool { // can, DeepSeek Harness on the official endpoint. func agentCLIModelOptional(kind, baseURL string) bool { switch kind { - case AgentCLICursor, AgentCLIZCode: - // ZCode resolves an unset model itself (applyZCodeCredential). + case AgentCLICursor, AgentCLIZCode, AgentCLIQoderCN: + // ZCode resolves an unset model itself (applyZCodeCredential); Qoder CN + // falls back to the CLI's own model on its official endpoint. return true case AgentCLIAntigravity, AgentCLIDeepSeek: return baseURL == "" @@ -103,6 +105,8 @@ var agentCLIHostEnv = append([]string{ "KIMI_MODEL_NAME", "KIMI_MODEL_API_KEY", "KIMI_MODEL_BASE_URL", "KIMI_MODEL_PROVIDER_TYPE", "OPENCODE_CONFIG", "OPENCODE_CONFIG_CONTENT", "OPENCODE_CONFIG_DIR", "PI_CODING_AGENT_DIR", "ZCODE_DATA_BASE_DIR", zcodePersonalFileEnv, + "QODERCN_PERSONAL_ACCESS_TOKEN", "QODERCN_CONFIG_DIR", "QODERCN_MODEL", "QODERCN_PERMISSION_MODE", + "QODERCN_SESSION_ID", "QODERCN_SESSION_NAME", "QODERCN_WORKING_DIR", "QODERCN_SUBAGENT_MODEL", }, zcodeHostEnv...) // agentCLIConfigPaths are the HOME-relative files an agent CLI reads its MCP @@ -115,6 +119,7 @@ var agentCLIMCPPaths = map[string]string{ AgentCLIPi: ".pi/agent/mcp.json", AgentCLIDeepSeek: ".dsh/agentflow-mcp.json", AgentCLIZCode: zcodeConfigPath, + AgentCLIQoderCN: qoderCNConfigPath, } // AgentCLIMCPOptions shapes the MCP configuration of one invocation. @@ -184,6 +189,13 @@ func WriteAgentCLIMCPConfig(kind string, home AgentCLIHome, entries map[string]a } } } + if kind == AgentCLIQoderCN { + // Qoder CN keeps model, permissions and hooks beside mcpServers in one + // settings.json, so merge instead of replacing the whole document. + return mergeQoderCNSettings(home, func(document map[string]any) { + document["mcpServers"] = servers + }) + } var document any switch kind { case AgentCLIOpenCode: @@ -480,6 +492,8 @@ func ApplyAgentCLICredential(kind string, cred ProviderCredential, options Agent return applyDeepSeekCredential(home, homeEnv, key, baseURL, protocol, model, argv) case AgentCLIZCode: return applyZCodeCredential(home, homeEnv, key, baseURL, protocol, model, argv) + case AgentCLIQoderCN: + return applyQoderCNCredential(home, homeEnv, key, baseURL, protocol, model, argv) default: return nil, nil, fmt.Errorf("unknown agent CLI %q", kind) } @@ -579,6 +593,8 @@ func AgentCLILabel(kind string) string { return "DeepSeek Harness" case AgentCLIZCode: return "ZCode" + case AgentCLIQoderCN: + return "Qoder CN" } return kind } diff --git a/internal/runtime/agent_cli_qodercn.go b/internal/runtime/agent_cli_qodercn.go new file mode 100644 index 000000000..a58972b31 --- /dev/null +++ b/internal/runtime/agent_cli_qodercn.go @@ -0,0 +1,103 @@ +package runtime + +import ( + "encoding/json" + "errors" + "fmt" + "io/fs" + "slices" + "strings" +) + +const ( + // qoderCNConfigPath is Qoder CN's user-level settings file below HOME. It + // keeps mcpServers beside model, permissions and hooks, so every writer + // (MCP, credential, native approval) merges into it instead of replacing + // the whole document. + qoderCNConfigPath = ".qoder-cn/settings.json" + + // qoderCNSOPDisallowedTools are the tools that wait for a person. + qoderCNSOPDisallowedTools = "AskUserQuestion EnterPlanMode ExitPlanMode" + // qoderCNChatDisallowedTools adds what acts outside the chat's MCP gateway: + // shell, edits, web, sub-agents and background tasks. Qoder CN is a + // Claude-Code-family CLI, so the tool names are the capitalized ones + // (Read, Write, Edit, Bash, WebFetch, Agent, ...). + qoderCNChatDisallowedTools = qoderCNSOPDisallowedTools + " Bash Edit Write WebFetch WebSearch Agent TaskOutput TaskStop" +) + +// applyQoderCNCredential binds the responsible user's personal access token. +// Qoder CN only reaches its official endpoint with a PAT: a custom Base URL is +// rejected, and the model is optional (the CLI picks its own when unset or +// "default"). The key stays in the environment; settings.json only names the +// model, never the token. +func applyQoderCNCredential(home AgentCLIHome, homeEnv, key, baseURL, protocol, model string, argv []string) ([]string, map[string]string, error) { + if baseURL != "" { + return nil, nil, errors.New("Qoder CN 仅支持官方端点(个人访问令牌),不支持自定义 Base URL") + } + if key == "" { + return nil, nil, fmt.Errorf("需求责任人未配置 %s 个人访问令牌(PAT),请在个人配置中配置", AgentCLILabel(AgentCLIQoderCN)) + } + env := map[string]string{ + "QODERCN_PERSONAL_ACCESS_TOKEN": key, + "QODERCN_CONFIG_DIR": homeEnv + "/.qoder-cn", + } + // An unset or "default" model keeps the CLI's own choice; a named one + // travels both as QODERCN_MODEL and as settings.json model.name. + model = strings.TrimSpace(model) + named := model != "" && model != "default" + if named { + env["QODERCN_MODEL"] = model + } + if err := mergeQoderCNSettings(home, func(document map[string]any) { + if !named { + return + } + settings, _ := document["model"].(map[string]any) + if settings == nil { + settings = map[string]any{} + } + settings["name"] = model + document["model"] = settings + }); err != nil { + return nil, nil, err + } + // AgentCLICommand supplies -p and the read-only / --yolo tool + // policy; guarantee the print format here so a minimal argv still emits + // Claude-Code-compatible stream-json. + argv = append([]string{}, argv...) + if i := slices.Index(argv, "--output-format"); i >= 0 && i+1 < len(argv) { + argv[i+1] = "stream-json" + } else { + argv = append(argv, "--output-format", "stream-json") + } + return argv, env, nil +} + +// mergeQoderCNSettings reads the existing settings.json (when present), applies +// mutate and writes it back, so MCP servers, the model selection and the native +// approval hooks never clobber one another. +func mergeQoderCNSettings(home AgentCLIHome, mutate func(map[string]any)) error { + root, err := openAgentCLIHome(home) + if err != nil { + return err + } + data, err := root.ReadFile(qoderCNConfigPath) + root.Close() + document := map[string]any{} + if err == nil { + if err = json.Unmarshal(data, &document); err != nil { + return err + } + } else if !errors.Is(err, fs.ErrNotExist) { + return err + } + if document == nil { + document = map[string]any{} + } + mutate(document) + out, err := json.MarshalIndent(document, "", " ") + if err != nil { + return err + } + return writeAgentCLIFile(home, qoderCNConfigPath, out) +} \ No newline at end of file diff --git a/internal/runtime/agent_cli_qodercn_test.go b/internal/runtime/agent_cli_qodercn_test.go new file mode 100644 index 000000000..d6c5d6531 --- /dev/null +++ b/internal/runtime/agent_cli_qodercn_test.go @@ -0,0 +1,184 @@ +package runtime + +import ( + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestQoderCNCommand(t *testing.T) { + sop := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Prompt: "do it", SystemPrompt: "SYS", Model: "m"}).Argv + if sop[0] != "qodercn" || sop[1] != "-p" || !strings.Contains(sop[2], "SYS") || !strings.HasSuffix(sop[2], "do it") { + t.Fatalf("sop argv: %q", sop) + } + for _, arg := range []string{"--output-format", "stream-json", "--yolo", "--disallowed-tools", qoderCNSOPDisallowedTools} { + if !slices.Contains(sop, arg) { + t.Errorf("sop argv misses %q: %q", arg, sop) + } + } + if strings.Contains(qoderCNSOPDisallowedTools, "Bash") { + t.Errorf("SOP keeps native tools: %q", qoderCNSOPDisallowedTools) + } + + chat := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Prompt: "hi", SystemPrompt: "SYS", Chat: true, Resume: "sess_1"}) + if !chat.AgentCLI.ReadOnly || chat.Provider != AgentCLIQoderCN { + t.Fatalf("chat spec: %+v", chat) + } + i := slices.Index(chat.Argv, "--disallowed-tools") + if i < 0 || chat.Argv[i+1] != qoderCNChatDisallowedTools { + t.Fatalf("chat argv: %q", chat.Argv) + } + if slices.Contains(chat.Argv, "--yolo") { + t.Errorf("chat must not bypass permissions: %q", chat.Argv) + } + for _, tool := range strings.Fields("Bash Edit Write WebFetch WebSearch Agent AskUserQuestion EnterPlanMode ExitPlanMode") { + if !slices.Contains(strings.Fields(chat.Argv[i+1]), tool) { + t.Errorf("chat does not disallow %s", tool) + } + } + if j := slices.Index(chat.Argv, "--resume"); j < 0 || chat.Argv[j+1] != "sess_1" { + t.Fatalf("chat resume: %q", chat.Argv) + } + // A resumed chat session keeps the system prompt of its first turn. + if chat.Argv[2] != "hi" { + t.Fatalf("resumed prompt: %q", chat.Argv[2]) + } + workspace := AgentCLICommand(AgentCLIQoderCN, AgentCLICommandOptions{Chat: true, Workspace: true, Prompt: "edit", Resume: "sess_1"}) + i = slices.Index(workspace.Argv, "--disallowed-tools") + if workspace.AgentCLI.ReadOnly || i < 0 || workspace.Argv[i+1] != qoderCNSOPDisallowedTools || !slices.Contains(workspace.Argv, "--yolo") { + t.Fatalf("workspace retains native tools: %q", workspace.Argv) + } +} + +func TestApplyQoderCNCredential(t *testing.T) { + home := t.TempDir() + if err := os.MkdirAll(filepath.Join(home, ".qoder-cn"), 0o700); err != nil { + t.Fatal(err) + } + seed := `{"mcpServers":{"gw":{"url":"http://127.0.0.1:1/mcp"}},"permissions":{"allow":["mcp__gw"]},"hooks":{"PreToolUse":[]},"general":{"defaultPermissionMode":"bypass_permissions"}}` + if err := os.WriteFile(filepath.Join(home, ".qoder-cn", "settings.json"), []byte(seed), 0o600); err != nil { + t.Fatal(err) + } + argv := []string{"qodercn", "-p", "do it", "--output-format", "stream-json", "--yolo"} + bound, env, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: " pat-secret "}, AgentCLIOptions{Model: "qoder-model"}, HostAgentCLIHome(home), "/w/home", argv) + if err != nil { + t.Fatal(err) + } + if env["QODERCN_PERSONAL_ACCESS_TOKEN"] != "pat-secret" || env["QODERCN_CONFIG_DIR"] != "/w/home/.qoder-cn" || env["QODERCN_MODEL"] != "qoder-model" { + t.Fatalf("env: %v", env) + } + if !slices.Equal(bound, argv) { + t.Fatalf("argv changed: %q", bound) + } + doc := readJSONFile(t, filepath.Join(home, ".qoder-cn", "settings.json")) + if doc["model"].(map[string]any)["name"] != "qoder-model" { + t.Fatalf("model not written: %v", doc) + } + // The merge keeps every other top-level key the CLI relies on. + if doc["mcpServers"].(map[string]any)["gw"] == nil || doc["permissions"] == nil || doc["hooks"] == nil || doc["general"] == nil { + t.Fatalf("merge lost keys: %v", doc) + } + data, _ := os.ReadFile(filepath.Join(home, ".qoder-cn", "settings.json")) + if strings.Contains(string(data), "pat-secret") { + t.Fatalf("PAT leaked into settings.json:\n%s", data) + } + + // An unset or "default" model keeps the CLI's own choice. + for _, model := range []string{"", "default"} { + h := t.TempDir() + _, env, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: model}, HostAgentCLIHome(h), "/h", []string{"qodercn", "-p", "x"}) + if err != nil { + t.Fatal(err) + } + if _, ok := env["QODERCN_MODEL"]; ok { + t.Errorf("model %q must keep the CLI default: %v", model, env) + } + if doc := readJSONFile(t, filepath.Join(h, ".qoder-cn", "settings.json")); doc["model"] != nil { + t.Errorf("model %q wrote a selection: %v", model, doc) + } + } + + // A custom Base URL is rejected: Qoder CN only reaches its official endpoint. + if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k", BaseURL: "https://gw.example"}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "官方端点") { + t.Fatalf("baseURL must be rejected: %v", err) + } + // A missing PAT is rejected. + if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{}, AgentCLIOptions{Model: "m"}, HostAgentCLIHome(t.TempDir()), "/h", nil); err == nil || !strings.Contains(err.Error(), "Qoder CN") { + t.Fatalf("missing PAT must be rejected: %v", err) + } + if _, _, err := applyQoderCNCredential(HostAgentCLIHome(t.TempDir()), "/h", "", "", "", "m", nil); err == nil || !strings.Contains(err.Error(), "PAT") { + t.Fatalf("direct missing PAT: %v", err) + } +} + +func TestWriteAgentCLIMCPConfigQoderCN(t *testing.T) { + home := t.TempDir() + if err := os.MkdirAll(filepath.Join(home, ".qoder-cn"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, ".qoder-cn", "settings.json"), []byte(`{"model":{"name":"keep"},"permissions":{"deny":["Bash"]},"hooks":{"Stop":[]}}`), 0o600); err != nil { + t.Fatal(err) + } + entries := map[string]any{"gw": map[string]any{"type": "http", "url": "https://m.example/mcp", "headers": map[string]any{"Authorization": "Bearer t"}}} + if err := WriteAgentCLIMCPConfig(AgentCLIQoderCN, HostAgentCLIHome(home), entries, AgentCLIMCPOptions{}); err != nil { + t.Fatal(err) + } + doc := readJSONFile(t, filepath.Join(home, ".qoder-cn", "settings.json")) + servers := doc["mcpServers"].(map[string]any) + if servers["gw"].(map[string]any)["url"] != "https://m.example/mcp" { + t.Fatalf("mcp server: %v", servers) + } + if doc["model"].(map[string]any)["name"] != "keep" || doc["permissions"] == nil || doc["hooks"] == nil { + t.Fatalf("MCP write clobbered other keys: %v", doc) + } +} + +func TestQoderCNConversationApprovalPreservesMCPAndModel(t *testing.T) { + root := t.TempDir() + home := AgentCLIHome{Base: root, Rel: "home"} + if err := WriteAgentCLIMCPConfig(AgentCLIQoderCN, home, map[string]any{"agentflow_session": map[string]any{"type": "http", "url": "http://127.0.0.1/mcp"}}, AgentCLIMCPOptions{}); err != nil { + t.Fatal(err) + } + if _, err := InstallConversationApproval(root, AgentCLIQoderCN, CommandSpec{Argv: []string{"qodercn"}}); err != nil { + t.Fatal(err) + } + doc := readJSONFile(t, filepath.Join(root, "home", ".qoder-cn", "settings.json")) + if doc["hooks"].(map[string]any)["PreToolUse"] == nil || doc["mcpServers"] == nil { + t.Fatalf("lost approval or MCP: %v", doc) + } + // Credential binding happens after approval and must retain the guard. + if _, _, err := ApplyAgentCLICredential(AgentCLIQoderCN, ProviderCredential{APIKey: "k"}, AgentCLIOptions{Model: "m"}, home, filepath.Join(root, "home"), []string{"qodercn"}); err != nil { + t.Fatal(err) + } + doc = readJSONFile(t, filepath.Join(root, "home", ".qoder-cn", "settings.json")) + if doc["hooks"].(map[string]any)["PreToolUse"] == nil || doc["mcpServers"] == nil || doc["model"].(map[string]any)["name"] != "m" { + t.Fatalf("binding replaced approval/MCP/model: %v", doc) + } +} + +func TestQoderCNTranslatorPassthrough(t *testing.T) { + translate := NewAgentCLITranslator(AgentCLIQoderCN) + if translate == nil { + t.Fatal("no translator for qodercn") + } + samples := []string{ + `{"type":"system","subtype":"init","session_id":"sess_1","model":"qoder"}`, + `{"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"done"}]},"session_id":"sess_1"}`, + `{"type":"result","subtype":"success","is_error":false,"result":"done","session_id":"sess_1"}`, + } + for _, line := range samples { + if out := translate(line); len(out) != 1 || out[0] != line { + t.Fatalf("passthrough changed line: %q -> %q", line, out) + } + } + if out := translate(" " + samples[0] + " "); len(out) != 1 || out[0] != samples[0] { + t.Fatalf("trim: %q", out) + } + for _, bad := range []string{"", "not json", "[1,2]", `{"broken":`} { + if out := translate(bad); out != nil { + t.Fatalf("garbage %q -> %q", bad, out) + } + } +} \ No newline at end of file diff --git a/internal/runtime/agent_cli_stream.go b/internal/runtime/agent_cli_stream.go index 079798cac..989fe28db 100644 --- a/internal/runtime/agent_cli_stream.go +++ b/internal/runtime/agent_cli_stream.go @@ -176,6 +176,20 @@ func NewAgentCLITranslator(kind string) func(string) []string { translate = (&dshStream{}).translate case AgentCLIZCode: translate = (&zcodeStream{}).translate + case AgentCLIQoderCN: + // Qoder CN already prints Claude-Code-compatible stream-json NDJSON, so + // every well-formed line passes through unchanged. + return func(line string) []string { + line = strings.TrimSpace(line) + if line == "" || line[0] != '{' { + return nil + } + var raw map[string]any + if json.Unmarshal([]byte(line), &raw) != nil { + return nil + } + return []string{line} + } default: return nil } diff --git a/internal/runtime/cli_ondemand.go b/internal/runtime/cli_ondemand.go index b6b18fcb6..da207d9a1 100644 --- a/internal/runtime/cli_ondemand.go +++ b/internal/runtime/cli_ondemand.go @@ -50,6 +50,7 @@ func onDemandCLICatalog() map[string]onDemandCLI { "kimi": {Engine: "kimi", Binary: "kimi", Package: "@moonshot-ai/kimi-code"}, "pi": {Engine: "pi", Binary: "pi", Package: "@earendil-works/pi-coding-agent"}, "dsh": {Engine: "dsh", Binary: "dsh", Package: "@deepseek-ai/dsh@" + DeepSeekHarnessVersion, RelaxEngines: true, Bundled: true}, + "qodercn": {Engine: "qodercn", Binary: "qodercn", Package: "@qodercn-ai/qoderclicn"}, } } diff --git a/internal/runtime/conversation_approval.go b/internal/runtime/conversation_approval.go index 9de5b7051..1760c7156 100644 --- a/internal/runtime/conversation_approval.go +++ b/internal/runtime/conversation_approval.go @@ -78,6 +78,21 @@ func InstallConversationApproval(root, provider string, command CommandSpec) (Co if err := writeAgentCLIFile(home, zcodeConfigPath, data); err != nil { return command, err } + case AgentCLIQoderCN: + // Qoder CN reads Claude-Code-style hooks from settings.json. Merge the + // PreToolUse guard so the MCP servers and model selection survive. + if err := mergeQoderCNSettings(home, func(document map[string]any) { + configured, _ := document["hooks"].(map[string]any) + if configured == nil { + configured = map[string]any{} + } + for event, entry := range hooks { + configured[event] = entry + } + document["hooks"] = configured + }); err != nil { + return command, err + } case "codex": entry := "hooks.PreToolUse=[{hooks=[{type=\"command\",command=" + strconv.Quote(launch) + ",timeout=" + strconv.Itoa(conversationApprovalHookWatchdog) + "}]}]" command.Argv = append(command.Argv[:len(command.Argv)-1], "-c", "features.hooks=true", "-c", entry, command.Argv[len(command.Argv)-1]) diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index 813bcdb2a..99a0276dc 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -572,7 +572,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str } // Some CLIs continue after a hook interpreter cannot be spawned. Both // the platform guard and the native approval hook must fail closed. - if (spec == nil || spec.Profile.Driver != domain.SandboxDriverDocker) && (command.Provider == AgentCLIKimi || command.Provider == "codex" || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode) { + if (spec == nil || spec.Profile.Driver != domain.SandboxDriverDocker) && (command.Provider == AgentCLIKimi || command.Provider == "codex" || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode || command.Provider == AgentCLIQoderCN) { check := exec.CommandContext(procCtx, "python3", "-c", "import json,urllib.request") if err = check.Run(); err != nil { return ConversationProcessResult{}, fmt.Errorf("原生工具审批需要 Python3:%w", err) @@ -581,7 +581,7 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str // These providers load hooks/extensions from persistent HOME in platform // mode too. Refresh them on every start so returning from a workspace never // runs a stale hook (Pi's codemode wrapper must reach its concrete tools). - if spec != nil || command.Provider == AgentCLIKimi || command.Provider == AgentCLIPi || command.Provider == AgentCLIOpenCode || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode { + if spec != nil || command.Provider == AgentCLIKimi || command.Provider == AgentCLIPi || command.Provider == AgentCLIOpenCode || command.Provider == AgentCLICursor || command.Provider == AgentCLIAntigravity || command.Provider == AgentCLIZCode || command.Provider == AgentCLIQoderCN { command, err = InstallConversationApproval(root, command.Provider, command) if err != nil { return ConversationProcessResult{}, err diff --git a/internal/runtime/conversation_sandbox.go b/internal/runtime/conversation_sandbox.go index c6ecf56af..e16da2a33 100644 --- a/internal/runtime/conversation_sandbox.go +++ b/internal/runtime/conversation_sandbox.go @@ -215,6 +215,7 @@ func conversationCLISetup(provider, binary string) (string, error) { packages := map[string]string{ "codebuddy": "@tencent-ai/codebuddy-code", "codex": "@openai/codex", "claude-code": "@anthropic-ai/claude-code", AgentCLIOpenCode: "opencode-ai", AgentCLIKimi: "@moonshot-ai/kimi-code", AgentCLIPi: "@earendil-works/pi-coding-agent", AgentCLIDeepSeek: "@deepseek-ai/dsh@" + DeepSeekHarnessVersion, + AgentCLIQoderCN: "@qodercn-ai/qoderclicn", } installer := "" if pkg := packages[provider]; pkg != "" { diff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.go index a728d0131..df94740f6 100644 --- a/internal/runtime/provider_agentcli.go +++ b/internal/runtime/provider_agentcli.go @@ -223,6 +223,21 @@ func AgentCLICommand(kind string, o AgentCLICommandOptions) CommandSpec { argv = append(argv, "--resume", resume) } argv = append(argv, extra...) + case AgentCLIQoderCN: + disallowed := qoderCNSOPDisallowedTools + if readOnly { + disallowed = qoderCNChatDisallowedTools + } + argv = []string{binary, "-p", prompt, "--output-format", "stream-json", "--disallowed-tools", disallowed} + if !readOnly { + // SOP and workspace turns bypass permissions; AI 对话 keeps the + // native approval hook and denies the chat tool set instead. + argv = append(argv, "--yolo") + } + if resume != "" { + argv = append(argv, "--resume", resume) + } + argv = append(argv, extra...) } return CommandSpec{Argv: argv, Provider: kind, AgentCLI: options} } diff --git a/web/app/agents.js b/web/app/agents.js index 1371913d7..59c3c1568 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -117,7 +117,7 @@ function syncAgentTabIndicators(){$$('#agentsView .agent-tabs, #agentModal .agen if(typeof document!=='undefined'&&document.fonts?.ready)document.fonts.ready.then(()=>syncAgentTabIndicators()).catch(()=>{}); function pickerHTML(items,selected,prefix){return `${(items||[]).map(x=>``).join('')||'暂无可用资产,请先到对应的资产管理页面添加'}`} function bindPickerFilters(root){(root||document).querySelectorAll('[data-picker-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.parentElement.querySelectorAll('.asset-check').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))})} -function executorOptions(selected){const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')} +function executorOptions(selected){const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode','qodercn']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')} const AGENT_CUSTOM_MODEL='__custom__'; let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0; function executorModelCatalogs(){ diff --git a/web/app/flow-canvas.css b/web/app/flow-canvas.css index 32ba62c74..6c306ab8f 100644 --- a/web/app/flow-canvas.css +++ b/web/app/flow-canvas.css @@ -437,7 +437,7 @@ html[data-theme="dark"] #flowView .fd-toast button{background:rgba(0,0,0,.06);co #aiOrchestrator .ai-model-toggle .ai-model-caret{flex:none;margin-left:auto;border-top-color:var(--hui-tertiary)} #aiOrchestrator .ai-model-toggle:disabled{opacity:.45;cursor:default} #aiOrchestrator #aiOrchestratorCLIPicker .ai-model-icon{background:transparent;color:var(--hui-muted)} -html[data-theme="dark"] #aiOrchestrator :is([data-cli="codex"],[data-cli="claude-code"],[data-cli="opencode"],[data-cli="cursor"],[data-cli="pi"]) img{filter:invert(1)} +html[data-theme="dark"] #aiOrchestrator :is([data-cli="codex"],[data-cli="claude-code"],[data-cli="opencode"],[data-cli="cursor"],[data-cli="pi"],[data-cli="qodercn"]) img{filter:invert(1)} #aiOrchestrator .ai-model-menu{position:fixed;right:auto;z-index:var(--hui-z-popover);max-width:calc(100vw - 16px);overflow:auto;border:1px solid var(--hui-border);border-radius:12px;background:var(--hui-surface);color:var(--hui-text);box-shadow:var(--hui-popover-shadow)} #aiOrchestrator .ai-model-menu [data-model-search]{position:sticky;top:0;z-index:1;box-sizing:border-box;width:100%;height:38px;margin:0;padding:0 12px;border:0;border-bottom:1px solid var(--hui-border);border-radius:0;outline:0;background:var(--hui-surface);color:var(--hui-text);font:inherit;font-size:13px;box-shadow:none} #aiOrchestrator .ai-model-menu [role=listbox]{padding:4px} diff --git a/web/app/runners.js b/web/app/runners.js index b9d70c4ca..bc7e59d97 100644 --- a/web/app/runners.js +++ b/web/app/runners.js @@ -56,14 +56,15 @@ function runnerStatusLabel(status,lastSeen){ const style=status==='online'?' online':status==='offline'?' offline':''; return `${escapeHTML(label)}`; } -const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'}; -const runnerCLIIcons={'claude-code':'claude',codex:'codex',codebuddy:'codebuddy',opencode:'opencode',cursor:'cursor',agy:'gemini',kimi:'kimi',pi:'pi',dsh:'deepseek',zcode:'glm'}; +const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode',qodercn:'Qoder CN'}; +const runnerCLIIcons={'claude-code':'claude',codex:'codex',codebuddy:'codebuddy',opencode:'opencode',cursor:'cursor',agy:'gemini',kimi:'kimi',pi:'pi',dsh:'deepseek',zcode:'glm',qodercn:'qoder'}; const runnerAuthLabel={local:'账号登录',personal:'API Key'}; const runnerAuthDescription={local:'Claude Code 和 Codex 可以使用运行 Runner 的系统账号在这台机器上的已有登录。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,SOP 使用运行责任人的 Key。'}; const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'}; function runnerKeyDescription(provider){ if(provider==='agy')return 'LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。'; if(provider==='zcode')return 'GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。'; + if(provider==='qodercn')return 'Qoder CN 使用个人访问令牌(PAT),请在「个人配置」中填写。模型可选,未选择时使用 CLI 默认模型。'; return '该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。'; } function runnerPersonalCredentialConfigured(provider){ diff --git a/web/app/sops.js b/web/app/sops.js index e59d38b9f..eb4c6edee 100644 --- a/web/app/sops.js +++ b/web/app/sops.js @@ -99,9 +99,9 @@ function sopRunRequirements(w){ const role=(state.data?.agents||[]).find(a=>a.id===node.agentId); const id=role?.executorId||node.executorId||'codebuddy'; const kind=(state.data?.executors||[]).find(e=>e.id===id)?.kind||id; - if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode'].includes(kind))providers.add(kind==='claude'?'claude-code':kind); + if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode','qodercn'].includes(kind))providers.add(kind==='claude'?'claude-code':kind); } - const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'}; + const agentLabels={opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode',qodercn:'Qoder CN'}; for(const kind of providers){ const known={codebuddy:['CodeBuddy','codeBuddyApiKey','codeBuddyApiKeyConfigured'],codex:['Codex','codexApiKey','codexApiKeyConfigured'],'claude-code':['Claude Code','claudeCodeApiKey','claudeCodeApiKeyConfigured']}[kind]; const [label,field,flag]=known||[agentLabels[kind]||kind,'agentCli.'+kind,'agentCliConfigured']; diff --git a/web/app/workbench.js b/web/app/workbench.js index eea4f23ce..a8e452773 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -105,14 +105,18 @@ const CREDENTIAL_KINDS=[ note:'未填写 Base URL 时连接 DeepSeek 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}), agentCliCredentialKind('zcode',{name:'ZCode',logo:'glm',baseUrl:'https://open.bigmodel.cn/api/anthropic', note:'未填写 Base URL 时连接智谱 BigModel 的 Anthropic 兼容服务(Messages)。',protocols:[['messages','Messages(Anthropic)'],['chat','Chat Completions'],['responses','Responses']]}), + agentCliCredentialKind('qodercn',{name:'Qoder CN',logo:'qoder',monochrome:true, + short:'Qoder CN Personal Access Token',placeholder:'请输入 Qoder CN 个人访问令牌(PAT)', + note:'使用个人访问令牌(PAT)认证;模型可选,未选择时使用 CLI 默认模型。', + guide:[['在 Qoder CN 的个人设置中创建个人访问令牌(PAT)'],['复制令牌粘贴到下方保存']]}), ]; function agentCliCredentialKind(cli,o){ const field=`agentCli.${cli}.`,configurable=!!o.protocols; - return {key:`agentCli.${cli}`,agentCli:cli,group:'model',name:o.name,short:`${o.name} API Key`,logo:o.logo,monochrome:!!o.monochrome, + return {key:`agentCli.${cli}`,agentCli:cli,group:'model',name:o.name,short:o.short||`${o.name} API Key`,logo:o.logo,monochrome:!!o.monochrome, use:`AI 对话的 ${o.name} 模型与以 ${o.name} 运行的 SOP 节点`, description:`AI 对话切换到 ${o.name} 后可选用它的模型,SOP 在执行机器上以 ${o.name} 运行的节点也使用它。${o.note||''}`, guide:o.guide||[['在模型服务商控制台创建 API Key'],['记下服务地址和它提供的接口协议'],['粘贴 Key,按需填写 Base URL 并选择协议;保存后可在模型目录里挑选 AI 对话的模型']], - placeholder:`请输入 ${o.name} API Key`, + placeholder:o.placeholder||`请输入 ${o.name} API Key`, ...(configurable?{ extra:{name:field+'baseUrl',label:'Base URL',placeholder:o.baseUrl,url:true,clearWithKey:true,required:o.required,note:o.extraNote||(o.required?'必填':'')}, protocol:{name:field+'protocol',options:o.protocols}, diff --git a/web/i18n-en.js b/web/i18n-en.js index 1f7e2c37f..9c7fb3a0d 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -52,7 +52,8 @@ Object.assign(window.LF_I18N_EN,{ "AI 对话的 Kimi Code 模型与以 Kimi Code 运行的 SOP 节点":"Kimi Code models in AI chat, and SOP steps that run on Kimi Code", "AI 对话的 Pi 模型与以 Pi 运行的 SOP 节点":"Pi models in AI chat, and SOP steps that run on Pi", "AI 对话的 DeepSeek Harness 模型与以 DeepSeek Harness 运行的 SOP 节点":"DeepSeek Harness models in AI chat, and SOP steps that run on DeepSeek Harness", -"AI 对话的 ZCode 模型与以 ZCode 运行的 SOP 节点":"ZCode models in AI chat, and SOP steps that run on ZCode" +"AI 对话的 ZCode 模型与以 ZCode 运行的 SOP 节点":"ZCode models in AI chat, and SOP steps that run on ZCode", +"AI 对话的 Qoder CN 模型与以 Qoder CN 运行的 SOP 节点":"Qoder CN models in AI chat, and SOP steps that run on Qoder CN" }); Object.assign(window.LF_I18N_EN,{ "继续回答关键问题,进度已经保存;不影响直接触发 SOP":"Keep answering the key questions. Progress is saved and does not block starting the SOP", @@ -187,6 +188,15 @@ Object.assign(window.LF_I18N_EN,{ "API Key 说明":"API Key help", "LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。":"LoopForge sandboxes cannot currently access Antigravity's login in the system credential store. Enter a Gemini API Key in Personal Settings. Gemini API usage is billed separately.", "GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。":"Enter the GLM Coding Plan API key and its dedicated endpoint in Personal Settings to use your subscription allowance. Start Plan allowance requires signing in to ZCode.", + "Qoder CN 使用个人访问令牌(PAT),请在「个人配置」中填写。模型可选,未选择时使用 CLI 默认模型。":"Qoder CN uses a personal access token (PAT). Enter it in Personal Settings. Choosing a model is optional; the CLI default model is used otherwise.", "该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。":"This CLI supports API keys. With a key included in your provider's subscription, usage counts toward that plan's allowance. Enter the API key in Personal Settings." }); +Object.assign(window.LF_I18N_EN,{ + "AI 对话切换到 Qoder CN 后可选用它的模型,SOP 在执行机器上以 Qoder CN 运行的节点也使用它。使用个人访问令牌(PAT)认证;模型可选,未选择时使用 CLI 默认模型。":"Switch AI chat to Qoder CN to pick its models; SOP steps that run on Qoder CN on a runner use the same token. It authenticates with a personal access token (PAT). Choosing a model is optional; the CLI default model is used otherwise.", + "使用个人访问令牌(PAT)认证;模型可选,未选择时使用 CLI 默认模型。":"Authenticates with a personal access token (PAT). Choosing a model is optional; the CLI default model is used otherwise.", + "在 Qoder CN 的个人设置中创建个人访问令牌(PAT)":"Create a personal access token (PAT) in your Qoder CN personal settings", + "复制令牌粘贴到下方保存":"Copy the token, paste it below, and save", + "请输入 Qoder CN 个人访问令牌(PAT)":"Enter your Qoder CN personal access token (PAT)", + "AI 对话将不能再切换到 Qoder CN,以 Qoder CN 运行的 SOP 节点将无法执行。":"AI chat can no longer switch to Qoder CN, and SOP steps that run on Qoder CN will fail." +}); Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"}); diff --git a/web/images/credentials/qoder.svg b/web/images/credentials/qoder.svg new file mode 100644 index 000000000..b6bd4484c --- /dev/null +++ b/web/images/credentials/qoder.svg @@ -0,0 +1 @@ +Qoder CN diff --git a/web/orchestrate.js b/web/orchestrate.js index aa718bfbd..c73691543 100644 --- a/web/orchestrate.js +++ b/web/orchestrate.js @@ -3,7 +3,7 @@ let aiBuild = null; let aiAbort = null; const aiHistory = {}; -const aiOrchestratorCLIBrands = {codebuddy:'codebuddy', codex:'codex', 'claude-code':'claude', opencode:'opencode', cursor:'cursor', agy:'gemini', kimi:'kimi', pi:'pi', dsh:'deepseek', zcode:'glm'}; +const aiOrchestratorCLIBrands = {codebuddy:'codebuddy', codex:'codex', 'claude-code':'claude', opencode:'opencode', cursor:'cursor', agy:'gemini', kimi:'kimi', pi:'pi', dsh:'deepseek', zcode:'glm', qodercn:'qoder'}; function aiOrchestratorEngine(model) { const listed = window.AgentFlowAssistantModels?.catalog().models.find(item => item.id === model); diff --git a/web/product-v4.css b/web/product-v4.css index 0c216dad8..9e56a1b69 100644 --- a/web/product-v4.css +++ b/web/product-v4.css @@ -2782,7 +2782,7 @@ html[data-theme="dark"] #runnersView{--rv-term:#0a0a0b;--rv-codex:#3f3f46} #runnersView .runner-runtime-label input{flex:none;margin:0;cursor:pointer} #runnersView .runner-runtime-icon{flex:none;display:grid;place-items:center;width:26px;height:26px;border-radius:7px;background:var(--rv-fill);transition:opacity .16s} #runnersView .runner-runtime-icon img{display:block;width:17px;height:17px;object-fit:contain} -html[data-theme="dark"] #runnersView .runner-runtime-icon:is(.codex,.claude-code,.cursor,.opencode,.pi) img{filter:invert(1)} +html[data-theme="dark"] #runnersView .runner-runtime-icon:is(.codex,.claude-code,.cursor,.opencode,.pi,.qodercn) img{filter:invert(1)} #runnersView .runner-runtime-name{min-width:0;display:grid;gap:3px;transition:opacity .16s} #runnersView .runner-runtime-name :is(b,small){display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} #runnersView .runner-runtime-name b{font-size:13px;font-weight:600;line-height:1.15} diff --git a/web/syntax_test.go b/web/syntax_test.go index 404d38b92..926718cb7 100644 --- a/web/syntax_test.go +++ b/web/syntax_test.go @@ -502,18 +502,18 @@ const count = (html, needle) => html.split(needle).length - 1; // Groups list credentials in a fixed order. assert.deepEqual(cred.CREDENTIAL_GROUPS.map(g => g.id), ['platform', 'model']); assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'platform').map(k => k.key), ['gitToken', 'gitSshKey']); -assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh', 'agentCli.zcode']); +assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh', 'agentCli.zcode', 'agentCli.qodercn']); // Progress, next-step hint, filter counts and per-group counts. const html = credentialPanelHTML(user); -assert.ok(html.includes('2 / 12 已配置')); +assert.ok(html.includes('2 / 13 已配置')); assert.ok(html.includes('data-credential-setup="codeBuddyApiKey"'), 'next step follows Git → CodeBuddy'); -assert.ok(html.includes('1 / 2') && html.includes('1 / 10')); -assert.ok(html.includes('已配置2') && html.includes('未配置10')); -assert.equal(count(html, 'data-credential-row='), 12); +assert.ok(html.includes('1 / 2') && html.includes('1 / 11')); +assert.ok(html.includes('已配置2') && html.includes('未配置11')); +assert.equal(count(html, 'data-credential-row='), 13); assert.ok(!html.includes('credential-grid') && !html.includes('credential-savebar') && !html.includes('userCredentialForm')); // Unconfigured rows only offer 去配置; configured rows carry an inline editor with delete. -assert.equal(count(html, 'data-credential-act="setup"'), 10); +assert.equal(count(html, 'data-credential-act="setup"'), 11); assert.equal(count(html, 'credential-editor-form'), 2); assert.equal(count(html, 'data-credential-act="delete"'), 2); for (const key of ['codeBuddyApiKey', 'claudeCodeApiKey']) { @@ -541,6 +541,8 @@ assert.deepEqual(credentialSavePayload(cred.kind('codexApiKey'), {secret: '', ex assert.deepEqual(credentialSavePayload(cred.kind('agentCli.opencode'), {secret: 'k', extra: 'https://gw.example/v1', protocol: 'messages', models: [{id: 'a', name: 'A'}]}), {agentCliCredentials: {opencode: {apiKey: 'k', baseUrl: 'https://gw.example/v1', protocol: 'messages', models: [{id: 'a', name: 'A'}]}}}); assert.equal(cred.kind('agentCli.cursor').models.engine, 'cursor', 'Cursor keeps a per-account model catalog'); assert.equal(cred.kind('agentCli.zcode').models.engine, 'zcode'); +assert.equal(cred.kind('agentCli.qodercn').models.engine, 'qodercn'); +assert.ok(!cred.kind('agentCli.qodercn').extra && !cred.kind('agentCli.qodercn').protocol, 'Qoder CN only takes a personal access token'); assert.ok(credentialSubline(cred.kind('codexApiKey'), {codexApiKeyConfigured: true, codexModels: [{id: 'hy4'}, {id: 'gpt-5.5'}]}).includes('2 个自定义模型')); assert.deepEqual(credentialClearPayload(cred.kind('codexApiKey')), {codexApiKeyClear: true, codexBaseUrl: '', codexModels: []}); assert.deepEqual(credentialClearPayload(cred.kind('claudeCodeApiKey')), {claudeCodeApiKeyClear: true, claudeCodeBaseUrl: '', claudeCodeModels: []}); @@ -836,10 +838,11 @@ global.state = {data: {executors: [ {id: 'pi', name: 'Pi'}, {id: 'dsh', name: 'DeepSeek Harness'}, {id: 'zcode', name: 'ZCode'}, + {id: 'qodercn', name: 'Qoder CN'}, {id: 'mock', name: '演示执行器'} ]}}; eval(code.slice(code.indexOf('function executorOptions('), code.indexOf('function selectAgent('))); -for (const id of ['opencode', 'cursor', 'agy', 'kimi', 'pi', 'dsh', 'zcode']) { +for (const id of ['opencode', 'cursor', 'agy', 'kimi', 'pi', 'dsh', 'zcode', 'qodercn']) { assert.ok(executorOptions(id).includes('value="' + id + '" selected'), id); } assert.ok(!executorOptions('codex').includes('value="mock"')); From ed920cd157d312f8365d4e67c3f3c3a2034eb3fc Mon Sep 17 00:00:00 2001 From: promise <1397862207@qq.com> Date: Fri, 20 Nov 2026 02:40:09 +0800 Subject: [PATCH 2/4] feat(codeup): add Yunxiao Codeup as a first-class repository hosting Mirror the GitHub hosting integration for Codeup: provider/identity codeup:{orgId}/{group}/{repo}, GitPlatform codeup (openapi-rdc.aliyuncs.com, x-yunxiao-token), per-host HTTPS Git credential (clone username + PAT) for clone/push, and a tracker client over the changeRequests API to create, list and merge merge requests with status sync. Expose organization/repository listing and PAT verification under /api/auth/codeup, and surface a Codeup repository-authorization card, connect wizard and repo picker in web and chatbot. Baseline conflict checks remain pure Git and are reused unchanged. --- chatbot/src/QuickAccessWizard.jsx | 241 +++++++++++- chatbot/src/assets/provider-logos/README.md | 5 + chatbot/src/assets/provider-logos/SOURCE.md | 3 + chatbot/src/assets/provider-logos/codeup.svg | 5 + chatbot/src/changes.js | 16 + chatbot/src/credentials.js | 15 + chatbot/tests/conversation-runs.test.mjs | 23 +- chatbot/tests/credentials.test.mjs | 12 + chatbot/tests/quick-access-wizard.test.jsx | 51 ++- internal/domain/codeup_test.go | 69 ++++ internal/domain/delivery_mr.go | 3 + internal/domain/mr.go | 22 +- internal/domain/project.go | 5 + internal/domain/public_repository.go | 71 ++++ internal/domain/user.go | 15 +- internal/httpapi/catalog.go | 12 +- internal/httpapi/codeup_auth.go | 190 +++++++++ internal/httpapi/git_http_credentials.go | 10 +- internal/httpapi/server.go | 4 + internal/tracker/codeup.go | 388 +++++++++++++++++++ internal/tracker/codeup_test.go | 195 ++++++++++ internal/tracker/merge_mr.go | 9 + internal/tracker/mr_delivery_sync.go | 12 +- internal/tracker/service.go | 1 + web/app/access.js | 3 +- web/app/codeup-connect.js | 152 ++++++++ web/app/git-http-credentials.js | 41 +- web/app/git-ssh.js | 25 +- web/app/issues.js | 18 +- web/app/project-wizard.js | 17 +- web/app/repo_drawer.js | 5 + web/app/workbench.js | 219 +++++++++-- web/app_bundle_test.go | 4 +- web/i18n-en.js | 69 ++++ web/images/credentials/README.md | 5 + web/images/credentials/codeup.svg | 5 + web/index.html | 6 +- web/syntax_test.go | 121 +++++- 38 files changed, 1982 insertions(+), 85 deletions(-) create mode 100644 chatbot/src/assets/provider-logos/codeup.svg create mode 100644 internal/domain/codeup_test.go create mode 100644 internal/httpapi/codeup_auth.go create mode 100644 internal/tracker/codeup.go create mode 100644 internal/tracker/codeup_test.go create mode 100644 web/app/codeup-connect.js create mode 100644 web/images/credentials/codeup.svg diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index e4570b359..9957ce211 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -48,12 +48,12 @@ const STEPS = [ { id: "auth", title: "凭据与授权", - desc: "GitHub 访问与模型密钥", + desc: "GitHub / 云效访问与模型密钥", }, { id: "project", title: "项目与仓库", - desc: "选择或新建项目,绑定 GitHub 仓库", + desc: "选择或新建项目,绑定代码仓库", }, { id: "workflow", @@ -581,6 +581,8 @@ function parseGitHubRepo(raw) { // SSH preview first (it leaves github.com to the GitHub parser, matching the // server); self-hosted legacy repositories keep the git.example.com form. export function parseGongfengRepo(raw) { + const codeupInfo = globalThis.LoopForgeCodeupRepo?.(raw); + if (codeupInfo) return codeupInfo; const httpsInfo = globalThis.LoopForgeGitHTTPS(raw); if (httpsInfo) return httpsInfo; const sshInfo = globalThis.LoopForgeGitSSH(raw); @@ -793,6 +795,11 @@ export default function QuickAccessWizard({ const [saving, setSaving] = useState(false); const [error, setError] = useState(""); const [gitToken, setGitToken] = useState(""); + const [codeupToken, setCodeupToken] = useState(""); + const [codeupUsername, setCodeupUsername] = useState(""); + const [codeupCredential, setCodeupCredential] = useState({ configured: false, username: "", id: "" }); + const [verifyingCodeup, setVerifyingCodeup] = useState(false); + const [codeupVerify, setCodeupVerify] = useState(null); const [codeBuddyApiKey, setCodeBuddyApiKey] = useState(""); // null follows the saved setting until the user picks an environment here. const [codeBuddyEnvChoice, setCodeBuddyEnvChoice] = useState(null); @@ -947,6 +954,9 @@ export default function QuickAccessWizard({ setPhase("wizard"); setError(""); setGitToken(""); + setCodeupToken(""); + setCodeupUsername(""); + setCodeupVerify(null); setCodeBuddyApiKey(""); setCodeBuddyEnvChoice(null); setGitVerify(null); @@ -978,19 +988,45 @@ export default function QuickAccessWizard({ [user?.id], ); + // The Codeup card is driven by the per-host Git HTTPS credential list; the + // user summary only carries a GitHub boolean. + const refreshCodeupCredential = useCallback(async () => { + if (!user?.id) return null; + try { + const list = await api( + `/api/users/${encodeURIComponent(user.id)}/git-http-credentials`, + ); + const record = + (Array.isArray(list) ? list : []).find( + (credential) => credential.host === "codeup.aliyun.com", + ) || null; + setCodeupCredential({ + configured: !!record, + username: record?.username || "", + id: record?.id || "", + }); + return record; + } catch { + return null; + } + }, [user?.id]); + useEffect(() => { if (!open) return undefined; let active = true; async function load() { setLoading(true); try { - const [usersRes, projectsRes, reposRes, workflowsRes, agentsRes] = + const [usersRes, projectsRes, reposRes, workflowsRes, agentsRes, codeupCredsRes] = await Promise.all([ api("/api/users").catch(() => []), api("/api/projects").catch(() => projects), api("/api/repositories").catch(() => []), api("/api/workflows").catch(() => []), api("/api/agents").catch(() => []), + user?.id + ? api(`/api/users/${encodeURIComponent(user.id)}/git-http-credentials`).catch(() => []) + : Promise.resolve([]), ]); if (!active) return; const freshUser = @@ -998,6 +1034,15 @@ export default function QuickAccessWizard({ (item) => Number(item.id) === Number(user?.id), ) || user; setStoredUser(mergeFreshUser(user, freshUser)); + const codeupRecord = + (Array.isArray(codeupCredsRes) ? codeupCredsRes : []).find( + (credential) => credential.host === "codeup.aliyun.com", + ) || null; + setCodeupCredential({ + configured: !!codeupRecord, + username: codeupRecord?.username || "", + id: codeupRecord?.id || "", + }); if (freshUser?.gitHubCredentialConfigured && freshUser?.id) { void verifyStoredGitToken(freshUser.id); } @@ -1102,6 +1147,7 @@ export default function QuickAccessWizard({ useEffect(() => { if (!open) return undefined; const refreshUser = () => { + void refreshCodeupCredential(); api("/api/users") .then((usersRes) => { const fresh = (usersRes || []).find( @@ -1125,7 +1171,7 @@ export default function QuickAccessWizard({ window.removeEventListener("focus", refreshUser); window.removeEventListener("message", credentialsChanged); }; - }, [open, user?.id, verifyStoredGitToken]); + }, [open, user?.id, verifyStoredGitToken, refreshCodeupCredential]); useEffect(() => { if (!open) return undefined; @@ -1186,6 +1232,7 @@ export default function QuickAccessWizard({ const activeStep = STEPS[activeStepIndex] || STEPS[0]; const wizardStepCount = STEPS.length - 1; const gitReady = Boolean(storedUser?.gitHubCredentialConfigured || gitToken.trim()); + const codeupReady = Boolean(codeupCredential.configured || codeupToken.trim()); const hasSSHKeys = Boolean(storedUser?.gitSshKeyConfigured); const selectedSSHRepo = parsedRepo || parseGongfengRepo(defaultRepo?.cloneUrl); const sshKeysLoaded = sshCredentials.userId === user?.id && sshCredentials.keys !== null; @@ -1194,6 +1241,7 @@ export default function QuickAccessWizard({ ); const sshReady = hasSSHKey(selectedSSHRepo); const sshRepository = (parsedRepo || defaultRepo)?.provider === "ssh"; + const codeupRepository = (parsedRepo || defaultRepo)?.provider === "codeup"; const codeBuddyReady = Boolean( storedUser?.codeBuddyApiKeyConfigured || codeBuddyApiKey.trim(), ); @@ -1223,6 +1271,7 @@ export default function QuickAccessWizard({ if (!user?.id) return storedUser; const payload = {}; let savedGit = false; + let savedCodeup = false; if (gitToken.trim()) { const endpoint = `/api/users/${encodeURIComponent(user.id)}/git-http-credentials`; const credentials = await api(endpoint); @@ -1230,12 +1279,23 @@ export default function QuickAccessWizard({ await write(endpoint, { ...(existing ? {id:existing.id} : {}), host:"github.com", platform:"github", name:"GitHub", username:"x-access-token", token:gitToken.trim() }, "PUT"); savedGit = true; } + if (codeupToken.trim()) { + const username = codeupUsername.trim() || codeupCredential.username; + if (!username) throw new Error("请填写云效 HTTPS 克隆账号(个人设置 → HTTPS 密码)。"); + const endpoint = `/api/users/${encodeURIComponent(user.id)}/git-http-credentials`; + const credentials = await api(endpoint); + const existing = (Array.isArray(credentials) ? credentials : []).find(credential => credential.host === "codeup.aliyun.com"); + const listed = await write(endpoint, { ...(existing ? {id:existing.id} : {}), host:"codeup.aliyun.com", platform:"codeup", name:"云效 Codeup", username, token:codeupToken.trim() }, "PUT"); + const record = (Array.isArray(listed) ? listed : []).find(credential => credential.host === "codeup.aliyun.com"); + setCodeupCredential({ configured: true, username, id: record?.id || existing?.id || "" }); + savedCodeup = true; + } if (codeBuddyApiKey.trim()) payload.codeBuddyApiKey = codeBuddyApiKey.trim(); // A key is always saved with the environment it was issued for. if (codeBuddyApiKey.trim() || codeBuddyEnv !== storedCodeBuddyEnvRaw) payload.codeBuddyInternetEnvironment = codeBuddyEnv; - if (!Object.keys(payload).length && !savedGit) return storedUser; + if (!Object.keys(payload).length && !savedGit && !savedCodeup) return storedUser; const saved = await write( `/api/users/${encodeURIComponent(user.id)}/credentials`, payload, @@ -1248,6 +1308,7 @@ export default function QuickAccessWizard({ saved?.codeBuddyInternetEnvironment || ""; setStoredUser(merged); setGitToken(""); + setCodeupToken(""); setCodeBuddyApiKey(""); setCodeBuddyEnvChoice(null); void onCredentialsSaved?.(); @@ -1283,12 +1344,66 @@ export default function QuickAccessWizard({ } } + // Codeup verifies the typed PAT + clone account before saving. Instances + // without /api/auth/codeup/verify fall back to save → per-credential verify + // → roll back on failure, so an invalid token still leaves nothing stored. + async function verifyCodeup() { + if (!user?.id || verifyingCodeup) return; + const typed = codeupToken.trim(); + const username = codeupUsername.trim() || codeupCredential.username; + if (typed && !username) { + setCodeupVerify({ valid: false, error: "请填写云效 HTTPS 克隆账号(个人设置 → HTTPS 密码)。" }); + return; + } + if (!typed && !codeupCredential.configured) return; + setVerifyingCodeup(true); + setCodeupVerify(null); + setError(""); + try { + let result; + if (typed) { + try { + result = await write("/api/auth/codeup/verify", { token: typed, username }); + } catch (err) { + if (err.status !== 404) throw err; + const previous = codeupCredential; + await saveTypedCredentials(); + const record = await refreshCodeupCredential(); + result = record?.id + ? await write(`/api/users/${encodeURIComponent(user.id)}/git-http-credentials/${encodeURIComponent(record.id)}/verify`, {}) + : { valid: false, error: "令牌保存失败" }; + if (!result?.valid) { + const endpoint = `/api/users/${encodeURIComponent(user.id)}/git-http-credentials`; + try { + if (previous.id) + await write(endpoint, { id: previous.id, name: "云效 Codeup", platform: "codeup", host: "codeup.aliyun.com", username: previous.username || "", token: "" }, "PUT"); + else if (record?.id) + await write(`${endpoint}/${encodeURIComponent(record.id)}`, {}, "DELETE"); + } catch {} + await refreshCodeupCredential(); + } + } + } else { + result = await write( + `/api/users/${encodeURIComponent(user.id)}/git-http-credentials/${encodeURIComponent(codeupCredential.id)}/verify`, + {}, + ); + } + setCodeupVerify(result); + if (result?.valid && typed && codeupToken.trim()) await saveTypedCredentials(); + } catch (err) { + setCodeupVerify({ valid: false, error: err.message }); + } finally { + setVerifyingCodeup(false); + } + } + async function nextStep() { if (saving) return; setError(""); if (activeStep.id === "auth") { - if (!gitReady && !hasSSHKeys && !codeBuddyReady && !sponsoredModel) { - setError("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key。"); + if (!gitReady && !codeupReady && !hasSSHKeys && !codeBuddyReady && !sponsoredModel) { + setError("请先配置 GitHub Git Token、云效 Codeup 令牌、Git SSH 密钥或 CodeBuddy API Key。"); return; } setSaving(true); @@ -1518,7 +1633,13 @@ export default function QuickAccessWizard({ repository: boundRepo, workflow: provisionedWorkflow || activeWorkflow, rolesCount: roles.length, - gitReady: Boolean(boundRepo?.provider === "ssh" ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) : latestUser?.gitHubCredentialConfigured), + gitReady: Boolean( + boundRepo?.provider === "ssh" + ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) + : boundRepo?.provider === "codeup" + ? codeupCredential.configured || codeupToken.trim() + : latestUser?.gitHubCredentialConfigured, + ), codeBuddyReady: Boolean( latestUser?.codeBuddyApiKeyConfigured || storedUser?.codeBuddyApiKeyConfigured, @@ -1693,7 +1814,11 @@ export default function QuickAccessWizard({ size={14} /> - {completedSummary?.repository?.provider === "ssh" ? "Git SSH 访问:" : "GitHub 访问:"} + {completedSummary?.repository?.provider === "ssh" + ? "Git SSH 访问:" + : completedSummary?.repository?.provider === "codeup" + ? "云效 Codeup 访问:" + : "GitHub 访问:"} {completedSummary?.gitReady ? "已就绪" : "未配置,克隆/推送私有仓库前可在个人配置补齐"} @@ -1894,6 +2019,92 @@ export default function QuickAccessWizard({ +
+
+
+ 云效 Codeup 仓库授权 + + 用于克隆云效私有仓库、创建分支、推送代码与发起合并请求 + +
+ +
+
+ +

在个人配置中填写个人访问令牌(PAT)与 HTTPS 克隆账号,返回后继续。

+
+ 直接填写令牌(高级) +
+ setCodeupUsername(e.target.value)} + placeholder={ + codeupCredential.configured && codeupCredential.username + ? `克隆账号 ${codeupCredential.username}(留空保持不变)` + : "HTTPS 克隆账号(个人设置 → HTTPS 密码)" + } + aria-label="云效 HTTPS 克隆账号" + autoComplete="off" + spellCheck={false} + /> +
+
+ setCodeupToken(e.target.value)} + placeholder={ + codeupCredential.configured + ? "已配置,留空保持不变" + : "云效个人访问令牌(PAT,授予代码读写权限)" + } + aria-label="云效个人访问令牌" + autoComplete="new-password" + /> + + + 令牌说明 ↗ + +
+ {codeupVerify ? ( + + ) : null} +
+
+
+
@@ -2021,7 +2232,7 @@ export default function QuickAccessWizard({ {repo.name} - {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){
`; } +// 云效 Codeup opens on the same read-only detail as GitHub; replacing the token +// also takes the HTTPS clone account, which Codeup requires for Git auth. +function codeupTokenDetailHTML(kind,user){ + const verify=codeupVerifyFor({id:state.currentUser?.id}),result=verify?.result,record=codeupCredentialRecord(user),missing=result?.missing||[]; + const ago=verify?.checkedAt?` · ${credentialAgo(verify.checkedAt)}`:''; + const checked=verify?.busy?`${credentialSpinner(13)}校验中…` + :!result?'尚未校验' + :result.error?`${escapeHTML(result.error)}${ago}` + :!result.valid?`令牌有效但缺少权限 ${escapeHTML(missing.join('、'))}${ago}` + :`令牌有效${ago}`; + return `
来源
个人访问令牌(PAT)
HTTPS 克隆账号
${record?.username?`${escapeHTML(record.username)}`:'保存后显示'}
最近校验
${checked}
用于
${escapeHTML(kind.description)}
`; +} +function codeupTokenEditorHTML(kind,user){ + const failure=gitTokenFailure(codeupVerifyFor({id:state.currentUser?.id})?.result),record=codeupCredentialRecord(user); + return `
+ ${credentialPatWarningHTML(!!failure,CODEUP_PAT_WARNING)} + ${codeupTokenDetailHTML(kind,user)} +
+
+
+ ${credentialFieldHTML({label:'HTTPS 克隆账号',name:'extra',type:'text',value:record?.username||'',placeholder:'云效「个人设置 → HTTPS 密码」中的克隆账号',hint:'与令牌一起用于 HTTPS 认证'})} + ${credentialFieldHTML({label:'新的个人访问令牌(PAT)',note:'保存前会校验有效性',name:'secret',placeholder:'粘贴云效个人访问令牌(PAT)',hint:GIT_TOKEN_REPLACE_HINT})} +
+

+
+ +
+
`; +} function credentialEditorHTML(kind,user){ if(kind.key==='gitToken')return gitTokenEditorHTML(kind,user); + if(kind.key==='codeupToken')return codeupTokenEditorHTML(kind,user); const extraStored=kind.extra?credentialValue(user,kind.extra.name):''; const extraValue=kind.extra?credentialExtraValue(kind,extraStored):''; const extraField=!kind.extra?'' @@ -687,7 +739,7 @@ function credentialEditorHTML(kind,user){ function credentialRowMainHTML(kind,user){ const managed=!!kind.dialog,on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key,status=credentialStatus(kind,user); const end=on&&!managed - ?`${credentialBadgeHTML(status)}${kind.key==='gitToken'?``:''}${credentialGlyph('chevron-down',16)}` + ?`${credentialBadgeHTML(status)}${kind.key==='gitToken'||kind.key==='codeupToken'?``:''}${credentialGlyph('chevron-down',16)}` :`${credentialBadgeHTML(status)}`; const interaction=managed?'':` role="button" tabindex="0"${on?` aria-expanded="${open}"`:''}`; return `
${credentialLogo(kind,on?'':'is-dim')}
${escapeHTML(kind.name)}${escapeHTML(kind.short)}${credentialSubline(kind,user)}
${end}
`; @@ -747,10 +799,11 @@ function repaintCredentialRow(key){ const user=credentialUser(),holder=document.createElement('div'); holder.innerHTML=credentialRowMainHTML(kind,user); row.querySelector('.credential-row-main').replaceWith(holder.firstElementChild); - if(key==='gitToken'){ + if(key==='gitToken'||key==='codeupToken'){ // Only the read-only parts are replaced: an open replace form keeps what was typed. - const failure=gitTokenFailure(gitTokenVerifyFor({id:state.currentUser?.id})?.result),detail=row.querySelector('[data-git-detail]'),warning=row.querySelector('.git-token-pat-warning'),replace=row.querySelector('[data-credential-act="replace"]'); - if(detail){holder.innerHTML=gitTokenDetailHTML(kind,user);detail.replaceWith(holder.firstElementChild)} + const codeup=key==='codeupToken'; + const failure=gitTokenFailure((codeup?codeupVerifyFor({id:state.currentUser?.id}):gitTokenVerifyFor({id:state.currentUser?.id}))?.result),detail=row.querySelector(codeup?'[data-codeup-detail]':'[data-git-detail]'),warning=row.querySelector('.git-token-pat-warning'),replace=row.querySelector('[data-credential-act="replace"]'); + if(detail){holder.innerHTML=codeup?codeupTokenDetailHTML(kind,user):gitTokenDetailHTML(kind,user);detail.replaceWith(holder.firstElementChild)} if(warning)warning.hidden=!failure; if(replace){replace.classList.toggle('primary',!!failure);replace.classList.toggle('secondary',!failure)} } @@ -778,8 +831,8 @@ function resetCredentialEditor(row){ if(extra?.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,extra.value); const protocol=form.querySelector('select[name="protocol"]');if(protocol)protocol.value=form.dataset.originalProtocol||''; resetCredentialCatalog(row); - if(row.dataset.credentialRow==='gitToken'){ - const line=form.querySelector('[data-git-verify-line]');if(line){line.classList.remove('is-err');line.innerHTML=''} + if(row.dataset.credentialRow==='gitToken'||row.dataset.credentialRow==='codeupToken'){ + const line=form.querySelector(row.dataset.credentialRow==='gitToken'?'[data-git-verify-line]':'[data-codeup-verify-line]');if(line){line.classList.remove('is-err');line.innerHTML=''} setCredentialHint(form,'secret',GIT_TOKEN_REPLACE_HINT); }else setCredentialHint(form,'secret',credentialKind(row.dataset.credentialRow)?.hint||''); updateCredentialEditorDirty(form); @@ -790,7 +843,7 @@ function toggleCredentialRow(key,open){ ui.open=next?key:null; setCredentialRowOpen(key,next); // 代码仓库 opens on its read-only detail; the token input only appears after 手动更换令牌. - if(next&&key!=='gitToken')setTimeout(()=>$(`#credentialPanel [data-credential-row="${key}"] [name="secret"]`)?.focus({preventScroll:true}),200); + if(next&&key!=='gitToken'&&key!=='codeupToken')setTimeout(()=>$(`#credentialPanel [data-credential-row="${key}"] [name="secret"]`)?.focus({preventScroll:true}),200); } const CREDENTIAL_PANE_FOCUS={form:'[name="secret"]',confirm:'[data-credential-act="undelete"]'}; // 代码仓库 swaps bar / form / confirm; the other kinds swap foot / confirm. Unknown names fall back to the first pane. @@ -826,8 +879,16 @@ async function saveCredential(key,values={},options={}){ const endpoint=`/api/users/${user.id}/git-http-credentials`,credentials=await api(endpoint),existing=credentials.find(credential=>credential.host==='github.com'); const listed=await api(endpoint,{method:'PUT',body:JSON.stringify({...(existing?{id:existing.id}:{}),name:'GitHub',platform:'github',host:'github.com',username:'x-access-token',token:values.secret})}); saved={...credentialUser(),id:user.id,gitHubCredentialConfigured:listed.some(item=>item.host==='github.com'),gitHttpCredentialsConfigured:listed.length>0}; + }else if(key==='codeupToken'){ + const endpoint=`/api/users/${user.id}/git-http-credentials`,credentials=await api(endpoint),existing=credentials.find(credential=>credential.host==='codeup.aliyun.com'); + const username=String(values.username||'').trim()||existing?.username||''; + const listed=await api(endpoint,{method:'PUT',body:JSON.stringify({...(existing?{id:existing.id}:{}),name:'云效 Codeup',platform:'codeup',host:'codeup.aliyun.com',username,token:values.secret})}); + const items=Array.isArray(listed)?listed:[],record=items.find(credential=>credential.host==='codeup.aliyun.com')||null; + state.codeupCredential={userId:user.id,record}; + saved={...credentialUser(),id:user.id,codeupCredentialConfigured:!!record,gitHttpCredentialsConfigured:items.length>0}; }else saved=await api(`/api/users/${user.id}/credentials`,{method:'PUT',body:JSON.stringify(credentialSavePayload(kind,values))}); if(key==='gitToken'&&!options.verified)state.gitTokenVerify=null; + if(key==='codeupToken'&&!options.verified)state.codeupVerify=null; storeCredentialUser(saved); notifyCredentialsChanged(); return saved; @@ -839,8 +900,15 @@ async function deleteCredential(key){ const endpoint=`/api/users/${user.id}/git-http-credentials`,credentials=await api(endpoint),existing=credentials.find(credential=>credential.host==='github.com'); const listed=existing?await api(`${endpoint}/${encodeURIComponent(existing.id)}`,{method:'DELETE'}):credentials; saved={...credentialUser(),id:user.id,gitHubCredentialConfigured:listed.some(item=>item.host==='github.com'),gitHttpCredentialsConfigured:listed.length>0}; + }else if(key==='codeupToken'){ + const endpoint=`/api/users/${user.id}/git-http-credentials`,credentials=await api(endpoint),existing=credentials.find(credential=>credential.host==='codeup.aliyun.com'); + const listed=existing?await api(`${endpoint}/${encodeURIComponent(existing.id)}`,{method:'DELETE'}):credentials; + const items=Array.isArray(listed)?listed:[],record=items.find(credential=>credential.host==='codeup.aliyun.com')||null; + state.codeupCredential={userId:user.id,record}; + saved={...credentialUser(),id:user.id,codeupCredentialConfigured:!!record,gitHttpCredentialsConfigured:items.length>0}; }else saved=await api(`/api/users/${user.id}/credentials`,{method:'PUT',body:JSON.stringify(credentialClearPayload(kind))}); if(key==='gitToken')state.gitTokenVerify=null; + if(key==='codeupToken')state.codeupVerify=null; storeCredentialUser(saved); notifyCredentialsChanged(); return saved; @@ -854,6 +922,87 @@ async function verifyAndSaveGitToken(token){ state.gitTokenVerify={userId:user.id,result,checkedAt:Date.now()}; return {saved:true,result,user:saved}; } +// 云效令牌同样先校验再保存。首选 /api/auth/codeup/verify(PAT + 克隆账号); +// 实例尚未提供该路由(404)时,退化为「保存 → 按凭据校验 → 失败回滚」, +// 校验不通过最终不落库。 +async function verifyAndSaveCodeupToken(token,username){ + const user=state.currentUser; + let result; + try{ + result=await api('/api/auth/codeup/verify',{method:'POST',body:JSON.stringify({token,username}),silent:true}); + }catch(err){ + if(/404/.test(err.message))return verifyAndSaveCodeupTokenViaCredential(token,username); + return {saved:false,result:{valid:false,error:err.message}}; + } + if(!result?.valid)return {saved:false,result}; + const saved=await saveCredential('codeupToken',{secret:token,username},{verified:true}); + state.codeupVerify={userId:user.id,result,checkedAt:Date.now()}; + return {saved:true,result,user:saved}; +} +async function verifyAndSaveCodeupTokenViaCredential(token,username){ + const user=state.currentUser,endpoint=`/api/users/${user.id}/git-http-credentials`; + const credentials=await api(endpoint,{silent:true}); + const existing=(Array.isArray(credentials)?credentials:[]).find(credential=>credential.host==='codeup.aliyun.com'); + const listed=await api(endpoint,{method:'PUT',silent:true,body:JSON.stringify({...(existing?{id:existing.id}:{}),name:'云效 Codeup',platform:'codeup',host:'codeup.aliyun.com',username,token})}); + const items=Array.isArray(listed)?listed:[],record=items.find(credential=>credential.host==='codeup.aliyun.com'); + let result; + try{result=record?await api(`${endpoint}/${encodeURIComponent(record.id)}/verify`,{method:'POST',silent:true}):{valid:false,error:'令牌保存失败'}} + catch(err){result={valid:false,error:err.message}} + if(!result?.valid){ + // Roll back so a failed verification leaves no new credential behind; an + // edited entry keeps its previous token (the server keeps it when blank). + try{ + if(existing)await api(endpoint,{method:'PUT',silent:true,body:JSON.stringify({id:existing.id,name:existing.name||'云效 Codeup',platform:'codeup',host:'codeup.aliyun.com',username:existing.username||'',token:''})}); + else if(record)await api(`${endpoint}/${encodeURIComponent(record.id)}`,{method:'DELETE',silent:true}); + }catch{} + let final=items; + try{final=await api(endpoint,{silent:true})}catch{} + const finalItems=Array.isArray(final)?final:[],finalRecord=finalItems.find(credential=>credential.host==='codeup.aliyun.com')||null; + state.codeupCredential={userId:user.id,record:finalRecord}; + storeCredentialUser({...credentialUser(),id:user.id,codeupCredentialConfigured:!!finalRecord,gitHttpCredentialsConfigured:finalItems.length>0}); + return {saved:false,result}; + } + state.codeupCredential={userId:user.id,record}; + const saved={...credentialUser(),id:user.id,codeupCredentialConfigured:true,gitHttpCredentialsConfigured:items.length>0}; + storeCredentialUser(saved); + notifyCredentialsChanged(); + state.codeupVerify={userId:user.id,result,checkedAt:Date.now()}; + return {saved:true,result,user:saved}; +} +// The cached credential list drives the Codeup card: the user summary has no +// per-host detail, so the record (id + clone account) is read from the same +// git-http-credentials endpoint the dialog manages. +async function refreshCodeupCredentialRecord(){ + const user=state.currentUser;if(!user||user.isGuest)return null; + let list; + try{list=await api(`/api/users/${encodeURIComponent(user.id)}/git-http-credentials`,{silent:true})}catch{return null} + if(Number(state.currentUser?.id)!==Number(user.id))return null; + const items=Array.isArray(list)?list:[],record=items.find(credential=>credential.host==='codeup.aliyun.com')||null; + state.codeupCredential={userId:user.id,record}; + const stored=credentialUser(),configured=!!record; + if(!!stored.codeupCredentialConfigured!==configured||!!stored.gitHttpCredentialsConfigured!==(items.length>0)){ + storeCredentialUser({...stored,id:user.id,codeupCredentialConfigured:configured,gitHttpCredentialsConfigured:items.length>0}); + if($('#credentialPanel'))renderCredentialPanel(); + } + return record; +} +async function refreshCodeupStatus(options={}){ + const user=state.currentUser;if(!user||user.isGuest)return null; + const record=codeupCredentialRecord(user);if(!record?.id)return null; + const previous=codeupVerifyFor(user); + state.codeupVerify={userId:user.id,busy:true,result:previous?.result,checkedAt:previous?.checkedAt}; + repaintCredentialRow('codeupToken'); + let result; + try{result=await api(`/api/users/${user.id}/git-http-credentials/${encodeURIComponent(record.id)}/verify`,{method:'POST',silent:true})} + catch(err){result={valid:false,error:err.message}} + if(Number(state.currentUser?.id)!==Number(user.id))return result; + state.codeupVerify={userId:user.id,result,checkedAt:Date.now()}; + repaintCredentialRow('codeupToken'); + const announce=options.announce||state.codeupAnnounceVerify; + state.codeupAnnounceVerify=false; + if(announce){const failure=gitTokenFailure(result);toast(failure||'云效令牌校验通过',failure?'err':'ok')} + return result; +} async function refreshGitTokenStatus(options={}){ const user=state.currentUser;if(!user||user.isGuest)return null; // The previous answer stays alongside busy so the detail keeps its scopes while re-checking. @@ -885,7 +1034,7 @@ async function submitCredentialEditor(row,button){ if(extraError){toast(extraError,'err');extra.focus();return} const catalog=form.querySelector('[data-credential-catalog]'),models=credentialCatalogPayload(catalog); if(!validateCredentialCatalog(catalog,models))return; - setCredentialButtonBusy(button,key==='gitToken'?'校验中':'保存中'); + setCredentialButtonBusy(button,key==='gitToken'||key==='codeupToken'?'校验中':'保存中'); try{ if(key==='gitToken'){ const outcome=await verifyAndSaveGitToken(secret); @@ -899,6 +1048,18 @@ async function submitCredentialEditor(row,button){ credentialSaved(key,'Git Token 校验通过,已保存'); return; } + if(key==='codeupToken'){ + const outcome=await verifyAndSaveCodeupToken(secret,extra?.value.trim()||''); + if(!outcome.saved){ + setCredentialButtonBusy(button,''); + const line=row.querySelector('[data-codeup-verify-line]'),warning=row.querySelector('.git-token-pat-warning'); + if(line){line.classList.add('is-err');line.innerHTML=credentialGlyph('alert',13)+escapeHTML(`${gitTokenFailure(outcome.result)||'云效令牌校验未通过'}(未保存)`);hydrateCredentialIcons(line)} + if(warning)warning.hidden=false; + return; + } + credentialSaved(key,'云效令牌校验通过,已保存'); + return; + } await saveCredential(key,{secret,...(extra?{extra:extra.value}:{}),...(protocol?{protocol:protocol.value}:{}),...(models?{models}:{})}); credentialSaved(key,`${kind.short} 已保存`); }catch(err){toast(err.message,'err');setCredentialButtonBusy(button,'')} @@ -919,16 +1080,16 @@ function toggleCredentialSecret(button){ function credentialRowAction(action,row,button){ const key=row.dataset.credentialRow; if(action==='setup')return openCredentialWizard(key); - if(action==='verify')return refreshGitTokenStatus({announce:true}); - const gongfeng=key==='gitToken'; + if(action==='verify')return key==='codeupToken'?refreshCodeupStatus({announce:true}):refreshGitTokenStatus({announce:true}); + const detailPanes=key==='gitToken'||key==='codeupToken'; if(action==='replace')return showCredentialPane(row,'form'); if(action==='cancel'){ - if(!gongfeng)return toggleCredentialRow(key,false); + if(!detailPanes)return toggleCredentialRow(key,false); resetCredentialEditor(row); return showCredentialPane(row,'bar','[data-credential-act="replace"]'); } if(action==='delete')return showCredentialPane(row,'confirm'); - if(action==='undelete')return showCredentialPane(row,'bar',gongfeng?'[data-credential-act="delete"]':''); + if(action==='undelete')return showCredentialPane(row,'bar',detailPanes?'[data-credential-act="delete"]':''); if(action==='confirm-delete')return confirmDeleteCredential(row,button); if(action==='save')return submitCredentialEditor(row,button); } @@ -1001,7 +1162,7 @@ function revealCredentialRow(key){ const group=row.closest('[data-credential-group]'),head=group?.querySelector('.credential-group-head'); if(head&&credentialUI().closed[group.dataset.credentialGroup])toggleCredentialGroup(head); if(credentialUI().open!==key)toggleCredentialRow(key,true); - else if(key!=='gitToken')setTimeout(()=>row.querySelector('[name="secret"]')?.focus({preventScroll:true}),200); + else if(key!=='gitToken'&&key!=='codeupToken')setTimeout(()=>row.querySelector('[name="secret"]')?.focus({preventScroll:true}),200); row.scrollIntoView({block:'center',behavior:'smooth'}); row.classList.add('credential-highlight'); setTimeout(()=>row.classList.remove('credential-highlight'),2400); @@ -1009,7 +1170,7 @@ function revealCredentialRow(key){ // ---- 添加凭证向导 ---- let credentialWizard=null; -function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraValue(kind,credentialValue(user,kind.extra.name)):''} +function credentialWizardDefaults(kind,user){if(kind?.key==='codeupToken')return codeupCredentialRecord(user)?.username||'';return kind?.extra?credentialExtraValue(kind,credentialValue(user,kind.extra.name)):''} function openCredentialWizard(key){ const user=credentialUser(); if(!state.currentUser||state.currentUser.isGuest||!$('#credentialPanel'))return; @@ -1086,7 +1247,7 @@ function credentialWizardStepTwoHTML(kind){ if(github&&!manual)return `
${credentialLogo(kind,'is-mini')}连接 GitHub连接后可选择仓库,用于克隆代码、创建分支和推送交付产物。
${methods}${credentialOAuthHTML('用工蜂授权','')}`; const validity=credentialWizardValid(); const {text:secretHint,tone:secretTone}=credentialWizardSecretHint(kind,wizard,validity); - const secretField=credentialFieldHTML({label:github?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint,hintTone:secretTone}); + const secretField=credentialFieldHTML({label:github||kind.key==='codeupToken'?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint,hintTone:secretTone}); const extraField=!kind.extra?'' :kind.extra.options?credentialSelectFieldHTML(kind,wizard.extra) :credentialFieldHTML({label:kind.extra.label,note:kind.extra.note||(kind.extra.url?'可选 · 留空使用官方地址':''),name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''}); @@ -1101,9 +1262,10 @@ function credentialWizardStepThreeHTML(kind){ if(wizard.done)return `

${escapeHTML(kind.short)} 已保存

下一次运行你负责的任务时生效,可随时在列表中展开编辑。

`; const extra=kind.extra?`
${escapeHTML(kind.extra.label)}
${escapeHTML(credentialExtraLabel(kind,wizard.extra))}`:''; const warning=credentialSecretWarning(kind,wizard.secret); + const verifyFirst=kind.key==='gitToken'||kind.key==='codeupToken'; const line=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 `
${credentialGlyph('check',16)}确认并保存密钥只在任务运行时注入,不写入 Agent 资产
${credentialGlyph('key',14)}${escapeHTML(kind.name)}
凭证
${escapeHTML(kind.short)}
密钥
已填写 ••••••••
${extra}
生效
下一次任务
${line}`; } @@ -1118,7 +1280,7 @@ function credentialWizardFootHTML(){ const ok=wizard.step===1?!!wizard.kind&&(!!credentialDialog(wizard.kind)||!credentialConfigured(credentialKind(wizard.kind),credentialUser())):credentialWizardValid().ok; return `${back}`; } - const gongfeng=wizard.kind==='gitToken'; + const gongfeng=wizard.kind==='gitToken'||wizard.kind==='codeupToken'; return `${back}`; } function credentialWizardPaneHTML(){ @@ -1242,10 +1404,13 @@ async function advanceCredentialWizard(){ if(kind.key==='gitToken'){ const outcome=await verifyAndSaveGitToken(secret); if(!outcome.saved){wizard.error=`${gitTokenFailure(outcome.result)||'Git Token 校验未通过'}(未保存)`;return} + }else if(kind.key==='codeupToken'){ + const outcome=await verifyAndSaveCodeupToken(secret,String(wizard.extra||'').trim()); + if(!outcome.saved){wizard.error=`${gitTokenFailure(outcome.result)||'云效令牌校验未通过'}(未保存)`;return} }else await saveCredential(kind.key,{secret,...(kind.extra?{extra:wizard.extra}:{}),...(kind.protocol?{protocol:wizard.protocol}:{})}); wizard.done=true;wizard.secret=''; renderCredentialPanel(); - toast(kind.key==='gitToken'?'Git Token 校验通过,已保存':`${kind.short} 已保存`,'ok'); + toast(kind.key==='gitToken'?'Git Token 校验通过,已保存':kind.key==='codeupToken'?'云效令牌校验通过,已保存':`${kind.short} 已保存`,'ok'); }catch(err){wizard.error=err.message} finally{ if(credentialWizard===wizard){wizard.saving=false;paintCredentialWizard(0);focusCredentialWizard()} @@ -1320,6 +1485,12 @@ async function renderPersonalSettings(){ const cached=gitTokenVerifyFor(user); if(!cached||(cached.busy&&!state.gitTokenVerifyInFlight)){state.gitTokenVerifyInFlight=true;refreshGitTokenStatus().finally(()=>{state.gitTokenVerifyInFlight=false})} } + // The Codeup card is driven by the per-host credential list, not the user summary. + refreshCodeupCredentialRecord().then(record=>{ + if(!record)return; + const cached=codeupVerifyFor(user); + if(!cached||(cached.busy&&!state.codeupVerifyInFlight)){state.codeupVerifyInFlight=true;refreshCodeupStatus().finally(()=>{state.codeupVerifyInFlight=false})} + }); } // 谁能改通用模板是平台级权限,不属于任何一个项目,也不属于个人凭据; // 只有平台管理员能看到「平台管理」入口。 diff --git a/web/app_bundle_test.go b/web/app_bundle_test.go index 63a3f2b27..f65bf4b9c 100644 --- a/web/app_bundle_test.go +++ b/web/app_bundle_test.go @@ -64,7 +64,9 @@ func appBundlePath(t testing.TB) string { if err := os.WriteFile(path, data, 0o644); err != nil { t.Fatal(err) } - return path + // The path is interpolated into node -e source; backslashes on Windows + // would be read as JS string escapes, so always hand node a slash path. + return filepath.ToSlash(path) } func TestAppBundleFilesAreEmbeddedAndListed(t *testing.T) { diff --git a/web/i18n-en.js b/web/i18n-en.js index 47308eaad..dab5a6b0b 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -248,3 +248,72 @@ Object.assign(window.LF_I18N_EN,{ "AI 对话将不能再切换到 Qoder CN,以 Qoder CN 运行的 SOP 节点将无法执行。":"AI chat can no longer switch to Qoder CN, and SOP steps that run on Qoder CN will fail." }); Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"}); +Object.assign(window.LF_I18N_EN,{ + "云效 Codeup":"Yunxiao Codeup", + "云效仓库授权":"Codeup repository access", + "云效 Codeup 仓库授权":"Yunxiao Codeup repository access", + "克隆云效私有仓库、创建任务分支、推送交付产物":"Clone private Codeup repositories, create task branches, push deliverables", + "用于克隆云效 Codeup 私有仓库、创建任务分支及推送交付产物,使用个人访问令牌(PAT)与 HTTPS 克隆账号认证。":"Clones private Yunxiao Codeup repositories, creates task branches and pushes deliverables. Authenticates with a personal access token (PAT) plus the HTTPS clone account.", + "打开云效 Codeup「个人设置 → 个人访问令牌」,新建令牌并授予代码读写权限":"In Yunxiao Codeup, open Personal Settings → Personal Access Tokens and create a token with code read/write access", + "查看云效认证设置说明":"Read the Codeup authentication guide", + "在「个人设置 → HTTPS 密码」查看 HTTPS 克隆账号":"Find the HTTPS clone account under Personal Settings → HTTPS Password", + "填写克隆账号并粘贴令牌,保存前会自动校验":"Enter the clone account and paste the token; it is verified before saving", + "请输入云效个人访问令牌(PAT)":"Enter your Codeup personal access token (PAT)", + "依赖云效私有仓库的 SOP 将无法克隆或推送仓库。":"SOPs that depend on private Codeup repositories will not be able to clone or push.", + "HTTPS 克隆账号":"HTTPS clone account", + "云效「HTTPS 密码」页的克隆账号":"The clone account from the Codeup HTTPS Password page", + "请填写 HTTPS 克隆账号":"Enter the HTTPS clone account", + "个人访问令牌(PAT)":"Personal access token (PAT)", + "个人访问令牌 PAT":"Personal access token (PAT)", + "保存后显示":"Shown after saving", + "云效「个人设置 → HTTPS 密码」中的克隆账号":"The clone account from Codeup Personal Settings → HTTPS Password", + "与令牌一起用于 HTTPS 认证":"Used together with the token for HTTPS authentication", + "新的个人访问令牌(PAT)":"New personal access token (PAT)", + "粘贴云效个人访问令牌(PAT)":"Paste the Codeup personal access token (PAT)", + "请填写云效":"Enter a Yunxiao Codeup", + "并授予代码读写权限;令牌权限不足会导致克隆 / 推送仓库失败。":"with code read/write access; insufficient scopes make repository clone/push fail.", + "云效令牌校验通过":"Codeup token verified", + "云效令牌校验通过,已保存":"Codeup token verified and saved", + "云效令牌校验未通过":"Codeup token verification failed", + "GitHub 和 GitLab 支持 gh / glab 认证和 PR/MR 合并状态同步。云效 Codeup 使用个人访问令牌(PAT)与 HTTPS 克隆账号。其他平台也可由 Agent 创建 PR/MR,合并状态请到托管平台查看。":"GitHub and GitLab support gh / glab authentication and automatic PR/MR merge status updates. Yunxiao Codeup uses a personal access token (PAT) plus the HTTPS clone account. Agents can also create PRs/MRs on other platforms, where you can check their merge status.", + "请填写云效 HTTPS 克隆账号":"Enter the Codeup HTTPS clone account", + "已配置云效仓库授权":"Codeup repository access configured", + "仓库可以先保存,代码任务还需要云效授权":"The repository can be saved now; code tasks still need Codeup access", + "请确认令牌已获得目标仓库的读写权限。SOP 使用需求责任人的令牌,未指定时使用项目 Owner 的令牌。":"Confirm the token can read and write the target repository. SOPs use the assignee's token, or the project owner's token when no assignee is set.", + "使用云效仓库进行需求分析、访问私有代码或提交合并请求前,请先配置云效仓库授权(个人访问令牌 PAT + HTTPS 克隆账号)。SOP 使用需求责任人的凭据,未指定时使用项目 Owner 的凭据。":"Configure Codeup repository access (personal access token PAT + HTTPS clone account) before analyzing a Codeup repository, accessing private code or opening merge requests. SOPs use the assignee's credentials, or the project owner's when no assignee is set.", + "配置云效仓库授权":"Configure Codeup repository access", + "绑定 GitHub / 云效仓库":"Bind GitHub / Codeup repositories", + "GitHub / 云效链接或 Git SSH 地址":"GitHub / Codeup link or Git SSH address", + "请输入 GitHub 链接或有效的 Git SSH 地址。云效 Codeup 仓库请粘贴 HTTPS 链接;CNB 只支持 HTTPS + 访问令牌。":"Enter a GitHub link or a valid Git SSH address. Paste the HTTPS link for Yunxiao Codeup repositories; CNB supports HTTPS with an access token.", + "请先粘贴 GitHub、云效 Codeup 链接或 Git SSH 地址":"Paste a GitHub or Yunxiao Codeup link, or a Git SSH address", + "请输入 GitHub、云效 Codeup 链接或 Git SSH 地址":"Enter a GitHub or Yunxiao Codeup link, or a Git SSH address", + "例如 https://github.com/owner/repo、https://codeup.aliyun.com/组织ID/仓库.git 或 git@gitlab.com:group/repo.git":"For example https://github.com/owner/repo, https://codeup.aliyun.com/orgId/repo.git or git@gitlab.com:group/repo.git", + "识别为云效 Codeup":"Recognized as Yunxiao Codeup", + "。克隆与推送使用个人配置中的云效仓库授权(PAT + HTTPS 克隆账号)。":". Clone and push use the Codeup repository access (PAT + HTTPS clone account) from Personal settings.", + "请输入有效的 GitHub、云效 Codeup 链接或 Git SSH 克隆地址。CNB 只支持 HTTPS + 访问令牌。":"Enter a valid GitHub or Yunxiao Codeup link, or a Git SSH clone address. CNB supports HTTPS with an access token.", + "使用云效 Codeup 的个人访问令牌(PAT)与 HTTPS 克隆账号连接,即可选择组织内的仓库。令牌在「个人设置 → 个人访问令牌」创建,克隆账号在「个人设置 → HTTPS 密码」查看。":"Connect with your Yunxiao Codeup personal access token (PAT) and HTTPS clone account to pick repositories in your organization. Create the token under Personal Settings → Personal Access Tokens; find the clone account under Personal Settings → HTTPS Password.", + "云效 HTTPS 克隆账号":"Codeup HTTPS clone account", + "粘贴云效个人访问令牌":"Paste the Codeup personal access token", + "校验并连接":"Verify and connect", + "组织":"Organization", + "请选择组织":"Select an organization", + "选择云效仓库":"Pick a Codeup repository", + "连接后可选择组织内的仓库;也可以直接粘贴 https://codeup.aliyun.com/组织ID/仓库.git 地址。":"Once connected you can pick repositories in the organization, or paste a https://codeup.aliyun.com/orgId/repo.git address directly.", + "仓库名 / 分组名":"Repository / group name", + "未找到仓库,可手动填写地址;请确认令牌有组织内仓库的读取权限。":"No repositories found; you can enter the address manually. Check that the token can read repositories in this organization.", + "正在读取组织…":"Loading organizations…", + "没有可用的组织":"No organizations available", + "组织 ID":"Organization ID", + "组织管理后台 → 基本信息中的组织 ID":"The organization ID from Organization Admin → Basic Information", + "加载仓库":"Load repositories", + "请填写组织 ID":"Enter the organization ID", + "请填写 HTTPS 克隆账号和个人访问令牌":"Enter the HTTPS clone account and the personal access token", + "正在校验令牌…":"Verifying token…", + "云效 Codeup 授权已保存":"Codeup access saved", + "组织列表暂不可用":"Organization list is unavailable", + "可手动填写组织 ID":"you can enter the organization ID manually", + "搜索已加载的仓库":"Search loaded repositories", + "加载更多仓库":"Load more repositories", + "请选择仓库":"Select a repository", + "选择仓库":"Select repository" +}); diff --git a/web/images/credentials/README.md b/web/images/credentials/README.md index 3415f9cd3..17861b643 100644 --- a/web/images/credentials/README.md +++ b/web/images/credentials/README.md @@ -11,3 +11,8 @@ respective owners. artwork as in `chatbot/src/assets/provider-logos/`. The [provider-logo README](../../../chatbot/src/assets/provider-logos/README.md) records the upstream sources and notices. + +`codeup.svg` is an original LoopForge monochrome placeholder glyph (cloud with +code brackets) for the Yunxiao Codeup credential card, mirroring +`chatbot/src/assets/provider-logos/codeup.svg`. It is not an official Alibaba +Cloud or Codeup mark. diff --git a/web/images/credentials/codeup.svg b/web/images/credentials/codeup.svg new file mode 100644 index 000000000..8c622714a --- /dev/null +++ b/web/images/credentials/codeup.svg @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/web/index.html b/web/index.html index 279e1a123..391cdcdbf 100644 --- a/web/index.html +++ b/web/index.html @@ -998,10 +998,11 @@

新建需求

仓库地址
+
@@ -1306,6 +1307,7 @@

确认操作

+ diff --git a/web/syntax_test.go b/web/syntax_test.go index bc5a4b461..756d017f4 100644 --- a/web/syntax_test.go +++ b/web/syntax_test.go @@ -10,7 +10,7 @@ import ( ) func TestCredentialBrandAssetsEmbedded(t *testing.T) { - for _, name := range []string{"gongfeng.svg", "codebuddy.svg", "codex.svg", "claude.svg"} { + for _, name := range []string{"gongfeng.svg", "codebuddy.svg", "codex.svg", "claude.svg", "codeup.svg"} { data, err := fs.ReadFile(Files, "images/credentials/"+name) if err != nil { t.Fatalf("credential logo %s is not embedded: %v", name, err) @@ -501,19 +501,19 @@ const count = (html, needle) => html.split(needle).length - 1; // Groups list credentials in a fixed order. assert.deepEqual(cred.CREDENTIAL_GROUPS.map(g => g.id), ['platform', 'model']); -assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'platform').map(k => k.key), ['gitToken', 'gitSshKey', 'gitHttpCredentials']); +assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'platform').map(k => k.key), ['gitToken', 'codeupToken', 'gitSshKey', 'gitHttpCredentials']); assert.deepEqual(cred.CREDENTIAL_KINDS.filter(k => k.group === 'model').map(k => k.key), ['codeBuddyApiKey', 'codexApiKey', 'claudeCodeApiKey', 'agentCli.opencode', 'agentCli.cursor', 'agentCli.agy', 'agentCli.kimi', 'agentCli.pi', 'agentCli.dsh', 'agentCli.zcode', 'agentCli.qodercn']); // Progress, next-step hint, filter counts and per-group counts. const html = credentialPanelHTML(user); -assert.ok(html.includes('2 / 14 已配置')); +assert.ok(html.includes('2 / 15 已配置')); assert.ok(html.includes('data-credential-setup="codeBuddyApiKey"'), 'next step follows Git → CodeBuddy'); -assert.ok(html.includes('1 / 3') && html.includes('1 / 11')); -assert.ok(html.includes('已配置2') && html.includes('未配置12')); -assert.equal(count(html, 'data-credential-row='), 14); +assert.ok(html.includes('1 / 4') && html.includes('1 / 11')); +assert.ok(html.includes('已配置2') && html.includes('未配置13')); +assert.equal(count(html, 'data-credential-row='), 15); assert.ok(!html.includes('credential-grid') && !html.includes('credential-savebar') && !html.includes('userCredentialForm')); // Unconfigured rows only offer 去配置; configured rows carry an inline editor with delete. -assert.equal(count(html, 'data-credential-act="setup"'), 12); +assert.equal(count(html, 'data-credential-act="setup"'), 13); assert.equal(count(html, 'credential-editor-form'), 2); assert.equal(count(html, 'data-credential-act="delete"'), 2); for (const key of ['codeBuddyApiKey', 'claudeCodeApiKey']) { @@ -536,6 +536,9 @@ assert.ok(!sshRow.includes('credential-editor-form')); const httpsRow = credentialRowHTML(cred.kind('gitHttpCredentials'), {...user, gitHttpCredentialsConfigured: true}); assert.match(httpsRow, /aria-haspopup="dialog">管理令牌/); assert.ok(!httpsRow.includes('credential-editor-form')); +const codeupRow = credentialRowHTML(cred.kind('codeupToken'), user); +assert.ok(codeupRow.includes('去配置') && !codeupRow.includes('is-configured'), 'Codeup starts unconfigured'); +assert.ok(credentialRowHTML(cred.kind('codeupToken'), {...user, codeupCredentialConfigured: true}).includes('data-credential-act="verify"'), 'a configured Codeup row keeps 重新校验'); assert.deepEqual(credentialSavePayload(cred.kind('codeBuddyApiKey'), {secret: '', extra: 'ioa'}), {codeBuddyApiKey: '', codeBuddyInternetEnvironment: 'ioa'}); assert.deepEqual(credentialSavePayload(cred.kind('codeBuddyApiKey'), {secret: '', extra: ''}), {codeBuddyApiKey: '', codeBuddyInternetEnvironment: ''}); assert.deepEqual(credentialSavePayload(cred.kind('codexApiKey'), {secret: 'sk-1'}), {codexApiKey: 'sk-1'}); @@ -682,6 +685,18 @@ assert.equal(calls.length, 0); assert.equal(calls.filter(c => c.method === 'PUT').length, before); assert.ok(cred.wizard.error.includes('令牌无效或已过期') && cred.wizard.error.includes('未保存')); assert.ok(!cred.wizard.done); + // A failed Codeup verification in the wizard saves nothing either, and the + // clone account is required before the wizard can continue. + const beforeCodeup = calls.filter(c => c.method === 'PUT').length; + cred.wizard = {step: 3, kind: 'codeupToken', direct: true, secret: 'pt-bad', extra: 'clone-account', guide: {}, error: ''}; + await advanceCredentialWizard(); + assert.equal(calls.filter(c => c.method === 'PUT').length, beforeCodeup); + assert.ok(cred.wizard.error.includes('未保存')); + cred.wizard = {step: 2, kind: 'codeupToken', direct: true, secret: 'pt-x', extra: '', guide: {}, error: ''}; + assert.equal(credentialWizardValid().ok, false); + assert.equal(credentialWizardValid().error, '请填写 HTTPS 克隆账号'); + cred.wizard.extra = 'clone-account'; + assert.equal(credentialWizardValid().ok, true); assert.ok(!code.includes('通常包含 /v1')); assert.ok(!code.includes('不含 /v1/messages')); })().catch(error => { console.error(error); process.exit(1); }); @@ -692,6 +707,77 @@ assert.equal(calls.length, 0); } } +func TestCodeupCredentialFlow(t *testing.T) { + node, err := exec.LookPath("node") + if err != nil { + t.Skip("node not installed; skipping Codeup credential check") + } + script := ` +const assert = require('node:assert/strict'); +const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8'); +const user = {id: 1}; +const state = {currentUser: {id: 1}, data: {users: [user]}}; +const userById = id => state.data.users.find(u => u.id === id); +const escapeHTML = v => String(v), toast = () => {}; +const calls = []; +let verifyResult = {valid: true, login: 'clone-account'}; +let list = []; +const api = async (path, options = {}) => { + calls.push({path, method: options.method || 'GET', body: options.body && JSON.parse(options.body)}); + if (path === '/api/auth/codeup/verify') return verifyResult; + if (path.endsWith('/git-http-credentials')) { + if (options.method === 'PUT') { + const body = JSON.parse(options.body); + list = [{id: 'c1', host: 'codeup.aliyun.com', platform: 'codeup', name: body.name, username: body.username}]; + return list; + } + return list; + } + if (path.endsWith('/verify')) return verifyResult; + return {}; +}; +const $ = () => null, setTimeout = () => {}, location = {origin: 'http://localhost'}; +const document = {activeElement: null, querySelectorAll: () => []}; +eval(code.slice(code.indexOf('const CREDENTIAL_GROUPS='), code.indexOf('// 谁能改通用模板')) + + ';globalThis.cred={kind:credentialKind,get wizard(){return credentialWizard},set wizard(v){credentialWizard=v}};'); +(async () => { + const kind = cred.kind('codeupToken'); + assert.equal(credentialConfigured(kind, user), false); + // A verified PAT is saved as the per-host Codeup credential with the clone account. + const outcome = await verifyAndSaveCodeupToken('pt-token', 'clone-account'); + assert.equal(outcome.saved, true); + const put = calls.filter(c => c.method === 'PUT').at(-1); + assert.equal(put.path, '/api/users/1/git-http-credentials'); + assert.deepEqual(put.body, {name: '云效 Codeup', platform: 'codeup', host: 'codeup.aliyun.com', username: 'clone-account', token: 'pt-token'}); + assert.equal(credentialConfigured(kind, userById(1)), true); + assert.equal(codeupCredentialRecord(userById(1)).username, 'clone-account'); + assert.ok(codeupTokenDetailHTML(kind, userById(1)).includes('clone-account')); + assert.ok(codeupTokenEditorHTML(kind, userById(1)).includes('data-codeup-detail')); + assert.equal(credentialStatus(kind, userById(1)), 'ok'); + // A failed verification saves nothing. + verifyResult = {valid: false, error: '令牌无效'}; + const before = calls.filter(c => c.method === 'PUT').length; + const failed = await verifyAndSaveCodeupToken('pt-bad', 'clone-account'); + assert.equal(failed.saved, false); + assert.equal(calls.filter(c => c.method === 'PUT').length, before); + // The save → per-credential verify fallback (used when the dedicated verify + // route answers 404) verifies the stored credential. + verifyResult = {valid: true, login: 'clone-account'}; + const viaCredential = await verifyAndSaveCodeupTokenViaCredential('pt-token', 'clone-account'); + assert.equal(viaCredential.saved, true); + assert.ok(calls.some(c => c.path === '/api/users/1/git-http-credentials/c1/verify' && c.method === 'POST')); + // Deleting removes the per-host credential and clears the card. + await deleteCredential('codeupToken'); + assert.equal(credentialConfigured(kind, userById(1)), false); + assert.equal(state.codeupCredential.record, null); +})().catch(error => { console.error(error); process.exit(1); }); +` + out, err := exec.Command(node, "-e", script).CombinedOutput() + if err != nil { + t.Fatalf("Codeup credential flow failed: %v\n%s", err, out) + } +} + func TestGotoCredentialBranches(t *testing.T) { node, err := exec.LookPath("node") if err != nil { @@ -994,21 +1080,38 @@ func TestRepositoryFormUsesSingleURL(t *testing.T) { script := ` const assert = require('node:assert/strict'); const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8'); +eval(require('node:fs').readFileSync('app/git-ssh.js', 'utf8')); +eval(code.slice(code.indexOf('function repoProviderLabel('), code.indexOf('function parseGongfengRepoURL('))); eval(code.slice(code.indexOf('function parseGongfengRepoURL(raw){'), code.indexOf('function fillRepositoryFromLink('))); const web = parseGongfengRepoURL('https://git.example.com/example/agent-flow'); assert.equal(web.project, 'example/agent-flow'); assert.equal(web.cloneUrl, 'https://git.example.com/example/agent-flow.git'); const ssh = parseGongfengRepoURL('git@git.example.com:example/agent-flow.git'); -assert.equal(ssh.project, 'example/agent-flow'); +// With the real SSH parser loaded, legacy SSH remotes keep the ssh provider +// and a host-qualified project, exactly as in the browser. +assert.equal(ssh.provider, 'ssh'); +assert.equal(ssh.project, 'git.example.com/example/agent-flow.git'); assert.equal(ssh.cloneUrl, 'git@git.example.com:example/agent-flow.git'); const cloned = parseGongfengRepoURL('git clone git@git.example.com:example/agent-flow.git'); -assert.equal(cloned.project, 'example/agent-flow'); +assert.equal(cloned.provider, 'ssh'); assert.equal(cloned.cloneUrl, 'git@git.example.com:example/agent-flow.git'); assert.equal(web.name, 'agent-flow'); const http = parseGongfengRepoURL('http://git.example.com/example/agent-flow.git'); assert.equal(http.project, 'example/agent-flow'); assert.equal(http.name, 'agent-flow'); assert.equal(ssh.name, 'agent-flow'); +// Codeup mirrors the server: orgId/group/repo, HTTPS identity, SSH and codeup: +// shorthand normalize to the HTTPS clone URL. +const codeup = parseGongfengRepoURL('https://codeup.aliyun.com/60de7a6852743a5162b5f957/ai/loopforge.git'); +assert.deepEqual(codeup, {provider:'codeup', host:'codeup.aliyun.com', organizationId:'60de7a6852743a5162b5f957', project:'codeup:60de7a6852743a5162b5f957/ai/loopforge', name:'loopforge', webUrl:'https://codeup.aliyun.com/60de7a6852743a5162b5f957/ai/loopforge', cloneUrl:'https://codeup.aliyun.com/60de7a6852743a5162b5f957/ai/loopforge.git'}); +assert.equal(parseGongfengRepoURL('git clone https://codeup.aliyun.com/org/group/repo').cloneUrl, 'https://codeup.aliyun.com/org/group/repo.git'); +assert.equal(parseGongfengRepoURL('git@codeup.aliyun.com:org/group/repo.git').provider, 'codeup'); +assert.equal(parseGongfengRepoURL('ssh://git@codeup.aliyun.com/org/group/repo.git').cloneUrl, 'https://codeup.aliyun.com/org/group/repo.git'); +assert.equal(parseGongfengRepoURL('codeup:org/group/repo').project, 'codeup:org/group/repo'); +assert.equal(parseGongfengRepoURL('codeup.aliyun.com/org/group/repo').name, 'repo'); +assert.equal(parseGongfengRepoURL('https://codeup.aliyun.com/org/repo'), null, 'org + repo without a group is not a Codeup repository'); +assert.equal(parseGongfengRepoURL('https://token@codeup.aliyun.com/org/group/repo'), null); +assert.equal(repoProviderLabel(codeup), '云效 Codeup'); const html = require('node:fs').readFileSync('index.html', 'utf8'); assert.ok(html.includes('集成分支用于检查多个 SOP 执行后工作分支之间是否存在合并冲突')); assert.ok(/]*name="integrateBranch"[^>]*>/.test(html)); From 34bbb786c8b167138bf2540a25e12ea540cd9ff4 Mon Sep 17 00:00:00 2001 From: promise <1397862207@qq.com> Date: Fri, 20 Nov 2026 16:26:20 +0800 Subject: [PATCH 3/4] feat(qodercn): real model catalog and reasoning effort Replace the placeholder-only Qoder CN catalog with the documented model set (Auto routing plus the frontier models from docs.qoder.cn/cli/models) and expose low..max reasoning effort, passed to the CLI as --reasoning-effort. --- internal/domain/agent.go | 1 + internal/httpapi/executor_models.go | 15 ++++++++++++++- internal/runtime/provider_agentcli.go | 3 +++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/internal/domain/agent.go b/internal/domain/agent.go index 29a404934..c46f0ea8b 100644 --- a/internal/domain/agent.go +++ b/internal/domain/agent.go @@ -16,6 +16,7 @@ var ExecutorEffortLevels = map[string][]string{ "opencode": {"low", "medium", "high"}, "cursor": {"none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"}, "agy": {"low", "medium", "high", "xhigh", "max"}, + "qodercn": {"low", "medium", "high", "xhigh", "max"}, "kimi": {"none", "thinking", "low", "high", "max"}, "pi": {"minimal", "low", "medium", "high", "xhigh", "max"}, "dsh": {"none", "low", "high", "max"}, diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index 8e55b898a..ef2e80bfe 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -180,9 +180,22 @@ func executorModelCatalogs(kimiBaseURL string) map[string]executorModelCatalog { // keeps that choice, and a custom ID is passed through QODERCN_MODEL. "qodercn": { CustomModel: true, + // Qoder CN's Default tab only offers Auto routing; the New tab lists + // frontier models. Names per docs.qoder.cn/cli/models; the live set + // is whatever `qodercn --list-models` reports for the account. Models: []executorModelInfo{ - {ID: "default", Name: "CLI 默认"}, + {ID: "auto", Name: "Auto 智能路由"}, + {ID: "Qwen3.8-Max", Name: "Qwen3.8-Max"}, + {ID: "Qwen3.7-Max", Name: "Qwen3.7-Max"}, + {ID: "Qwen3.7-Plus", Name: "Qwen3.7-Plus"}, + {ID: "Qwen3.6-Flash", Name: "Qwen3.6-Flash"}, + {ID: "DeepSeek-V4-Pro", Name: "DeepSeek-V4-Pro"}, + {ID: "DeepSeek-V4-Flash", Name: "DeepSeek-V4-Flash"}, + {ID: "GLM-5.2", Name: "GLM-5.2"}, + {ID: "Kimi-K2.7-Code", Name: "Kimi-K2.7-Code"}, + {ID: "MiniMax-M2.7", Name: "MiniMax-M2.7"}, }, + Efforts: effortOptions(domain.ExecutorEffortLevels["qodercn"]), }, } for engine, catalog := range catalogs { diff --git a/internal/runtime/provider_agentcli.go b/internal/runtime/provider_agentcli.go index 81abf3579..9d1c97a1c 100644 --- a/internal/runtime/provider_agentcli.go +++ b/internal/runtime/provider_agentcli.go @@ -242,6 +242,9 @@ func AgentCLICommand(kind string, o AgentCLICommandOptions) CommandSpec { if resume != "" { argv = append(argv, "--resume", resume) } + if options.Effort != "" { + argv = append(argv, "--reasoning-effort", options.Effort) + } argv = append(argv, extra...) } return CommandSpec{Argv: argv, Provider: kind, AgentCLI: options} From b0a2ea808e5366d17661e6d9c6740547a5435c9f Mon Sep 17 00:00:00 2001 From: promise <1397862207@qq.com> Date: Fri, 20 Nov 2026 17:02:23 +0800 Subject: [PATCH 4/4] feat(qodercn): sync model catalog with live --list-models output Replace the docs-based placeholder list with the account's live model set (Auto, Fast, Qwen4-Max, Qwen4-Max-Preview, Qwen3.8-*, DeepSeek-V4-*, GLM-5.3, Kimi-K3.1/K2.8, Step-5, MiniMax-M3.1, Qwen-4.0-Max) so specific models like Qwen4-Max are selectable instead of only Auto routing. --- internal/httpapi/executor_models.go | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index ef2e80bfe..830321dc4 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -180,20 +180,25 @@ func executorModelCatalogs(kimiBaseURL string) map[string]executorModelCatalog { // keeps that choice, and a custom ID is passed through QODERCN_MODEL. "qodercn": { CustomModel: true, - // Qoder CN's Default tab only offers Auto routing; the New tab lists - // frontier models. Names per docs.qoder.cn/cli/models; the live set - // is whatever `qodercn --list-models` reports for the account. + // Live account model set from `qodercn --list-models`; Auto is the + // CLI's smart-routing default. CustomModel lets users add ids the + // server-side list does not cover yet. Models: []executorModelInfo{ - {ID: "auto", Name: "Auto 智能路由"}, + {ID: "Auto", Name: "Auto 智能路由"}, + {ID: "Fast", Name: "Fast"}, + {ID: "Qwen4-Max", Name: "Qwen4-Max"}, + {ID: "Qwen4-Max-Preview", Name: "Qwen4-Max-Preview"}, {ID: "Qwen3.8-Max", Name: "Qwen3.8-Max"}, - {ID: "Qwen3.7-Max", Name: "Qwen3.7-Max"}, - {ID: "Qwen3.7-Plus", Name: "Qwen3.7-Plus"}, - {ID: "Qwen3.6-Flash", Name: "Qwen3.6-Flash"}, + {ID: "Qwen3.8-Flash", Name: "Qwen3.8-Flash"}, {ID: "DeepSeek-V4-Pro", Name: "DeepSeek-V4-Pro"}, - {ID: "DeepSeek-V4-Flash", Name: "DeepSeek-V4-Flash"}, - {ID: "GLM-5.2", Name: "GLM-5.2"}, - {ID: "Kimi-K2.7-Code", Name: "Kimi-K2.7-Code"}, - {ID: "MiniMax-M2.7", Name: "MiniMax-M2.7"}, + {ID: "DeepSeek-Flash", Name: "DeepSeek-Flash"}, + {ID: "GLM-5.3", Name: "GLM-5.3"}, + {ID: "GLM-5.3-Flash", Name: "GLM-5.3-Flash"}, + {ID: "Kimi-K3.1-Pro", Name: "Kimi-K3.1-Pro"}, + {ID: "Kimi-K2.8-Preview", Name: "Kimi-K2.8-Preview"}, + {ID: "Step-5-Preview", Name: "Step-5-Preview"}, + {ID: "MiniMax-M3.1-Flash", Name: "MiniMax-M3.1-Flash"}, + {ID: "Qwen-4.0-Max", Name: "Qwen-4.0-Max"}, }, Efforts: effortOptions(domain.ExecutorEffortLevels["qodercn"]), },