Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(git): support SSH repositories with per-host user keys (#207)
crispinhu27e8d7e146c98f
diff --git a/.env.example b/.env.exampleindex 0b17daf7..a03f66b3 100644--- a/.env.example+++ b/.env.example@@ -16,5 +16,7 @@ AGENTFLOW_PLATFORM_MCP_URL=# Optional model IDs available to your CodeBuddy account (comma-separated):AGENTFLOW_ASSISTANT_MODELS=AGENTFLOW_ASSISTANT_MODEL=+# Optional path to administrator-verified SSH host keys. See docs/deployment.md.+AGENTFLOW_GIT_SSH_KNOWN_HOSTS=# Worker separation, installed runners and preview settings retain AGENTFLOW_ names.# See docs/deployment.md. Production HTTPS: AGENTFLOW_SECURE_COOKIES=true.diff --git a/Dockerfile b/Dockerfileindex 1d331349..ae4002b8 100644--- a/Dockerfile+++ b/Dockerfile@@ -28,7 +28,7 @@ RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cacheCOPY --from=chatbot /src/web/native-chat/ web/native-chat/RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build GOOS=${TARGETOS} GOARCH=${TARGETARCH} bash scripts/build-binaries.sh --platform /outFROM node:22-bookworm-RUN --mount=type=cache,target=/root/.npm apt-get update && apt-get install -y --no-install-recommends ca-certificates git bash curl python3 ripgrep \+RUN --mount=type=cache,target=/root/.npm apt-get update && apt-get install -y --no-install-recommends ca-certificates git openssh-client bash curl python3 ripgrep \&& rm -rf /var/lib/apt/lists/* \&& npm install -g @openai/[email protected] @tencent-ai/[email protected]COPY --from=docker:27-cli /usr/local/bin/docker /usr/local/bin/dockerdiff --git a/README.md b/README.mdindex 7641f4f4..bfb8f353 100644--- a/README.md+++ b/README.md@@ -85,6 +85,8 @@ MIRROR=ghcr.nju.edu.cn ./start.shOpen the address printed by the installer and create your account; the first one becomes the administrator. The service listens on `0.0.0.0:8090` by default. On a cloud host, the installer reads the public IP from the provider's metadata service and prints it; allow the port in your security group, or put an HTTPS reverse proxy in front. Restrict access to your own IP until the administrator account exists. The home page's quick-access guide walks you through adding a model key, connecting a repository and choosing an SOP.+For GitLab, Gitea, Gogs and other Git hosts, [set up Git SSH](docs/deployment.md#git-repositories-over-ssh) to check out and push branches with a personal key. PR/MR and Issue automation requires a hosting API token or a separately configured MCP.+### Try it without an API keyNew accounts join the **LoopForge demo project**, which includes an SOP made only of a script and a human gate:diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 26fca9de..3f55f451 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -85,6 +85,8 @@ MIRROR=ghcr.nju.edu.cn ./start.sh打开安装脚本输出的地址创建账号,第一个账号自动成为管理员。服务默认监听 `0.0.0.0:8090`;在云主机上,安装脚本会从云厂商的元数据服务读取公网 IP 并直接打印出来,放通安全组端口即可访问,或配置 HTTPS 反向代理;管理员账号创建前,建议只允许你的 IP 访问。首页的「快速接入」会带你配置模型凭据、绑定仓库并选好默认 SOP。+GitLab、Gitea、Gogs 等托管可[配置 Git SSH](docs/deployment.md#git-repositories-over-ssh),用个人密钥检出和推送分支。Issue 与 PR/MR 自动化需要托管平台的 API Token 或另行配置的 MCP。[CNB 官方仅支持 HTTPS + 访问令牌](https://docs.cnb.cool/zh/guide/git-access.html)。+### 免 API Key 体验新注册的账号会自动加入 **LoopForge 体验项目**,其中有一条只包含脚本和人工审批的 SOP:diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsxindex 1ad3d378..aa48fb01 100644--- a/chatbot/src/QuickAccessWizard.jsx+++ b/chatbot/src/QuickAccessWizard.jsx@@ -8,6 +8,7 @@ import React, {useState,} from "react";import { createPortal } from "react-dom";+import "../../web/app/git-ssh.js";import HarnessIcon from "./HarnessIcon";import SlidingTabs from "./SlidingTabs";import { api, canChatInProject, canManageProjectRepos, write } from "./api";@@ -548,7 +549,7 @@ function parseGitHubRepo(raw) {.replace(/^['"]+|['"]+$/g, "").replace(/^git\s+clone\s+/i, "").replace(/^github:/i, "https://github.com/")- .replace(/^git@github\.com:/i, "https://github.com/");+ .replace(/^(?:git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/)/i, "https://github.com/");if (/^github\.com\//i.test(value)) value = `https://${value}`;let url;try {@@ -577,8 +578,11 @@ function parseGitHubRepo(raw) {};}-// GitHub first; self-hosted legacy repositories keep the git.example.com form.+// 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 sshInfo = globalThis.LoopForgeGitSSH(raw);+ if (sshInfo) return sshInfo;const github = parseGitHubRepo(raw);if (github) return github;const original = String(raw || "")@@ -777,6 +781,7 @@ export default function QuickAccessWizard({const [step, setStep] = useState(0);const [phase, setPhase] = useState("wizard");const [storedUser, setStoredUser] = useState(user);+ const [sshCredentials, setSSHCredentials] = useState({ userId: null, keys: null, error: false });const [catalogProjects, setCatalogProjects] = useState(projects);const [repositories, setRepositories] = useState([]);const [workflows, setWorkflows] = useState([]);@@ -1037,6 +1042,33 @@ export default function QuickAccessWizard({};}, [open, projectId, projects, user]);+ useEffect(() => {+ if (!open || !user?.id || user.isGuest) return undefined;+ let active = true;+ let generation = 0;+ const refresh = () => {+ const version = ++generation;+ api(`/api/users/${encodeURIComponent(user.id)}/git-ssh-keys`)+ .then((keys) => {+ if (active && version === generation) setSSHCredentials({ userId: user.id, keys: Array.isArray(keys) ? keys : [], error: false });+ })+ .catch(() => {+ if (active && version === generation) setSSHCredentials({ userId: user.id, keys: [], error: true });+ });+ };+ const credentialsChanged = (event) => {+ if (event.origin === location.origin && event.source === window.parent && event.data?.type === "agentflow-credentials-changed") refresh();+ };+ refresh();+ window.addEventListener("focus", refresh);+ window.addEventListener("message", credentialsChanged);+ return () => {+ active = false;+ window.removeEventListener("focus", refresh);+ window.removeEventListener("message", credentialsChanged);+ };+ }, [open, user?.id, user?.isGuest]);+useEffect(() => {if (!open || !selectedWorkflowId) return undefined;// Only platform templates have template roles; a project SOP would 404.@@ -1152,6 +1184,14 @@ export default function QuickAccessWizard({const activeStep = STEPS[activeStepIndex] || STEPS[0];const wizardStepCount = STEPS.length - 1;const gitReady = Boolean(storedUser?.gitTokenConfigured || gitToken.trim());+ const hasSSHKeys = Boolean(storedUser?.gitSshKeyConfigured);+ const selectedSSHRepo = parsedRepo || parseGongfengRepo(defaultRepo?.cloneUrl);+ const sshKeysLoaded = sshCredentials.userId === user?.id && sshCredentials.keys !== null;+ const hasSSHKey = (remote) => sshKeysLoaded && !sshCredentials.error && sshCredentials.keys.some(+ (key) => globalThis.LoopForgeGitSSHHost(key.host) === remote?.host,+ );+ const sshReady = hasSSHKey(selectedSSHRepo);+ const sshRepository = (parsedRepo || defaultRepo)?.provider === "ssh";const codeBuddyReady = Boolean(storedUser?.codeBuddyApiKeyConfigured || codeBuddyApiKey.trim(),);@@ -1238,8 +1278,8 @@ export default function QuickAccessWizard({if (saving) return;setError("");if (activeStep.id === "auth") {- if (!gitReady && !codeBuddyReady && !sponsoredModel) {- setError("请至少填写 GitHub Git Token 与 CodeBuddy API Key 中的一项。");+ if (!gitReady && !hasSSHKeys && !codeBuddyReady && !sponsoredModel) {+ setError("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key。");return;}setSaving(true);@@ -1280,7 +1320,7 @@ export default function QuickAccessWizard({}if (bindRepoNow && repoUrl.trim() && !parsedRepo) {setError(- "仓库地址无法识别,请粘贴 GitHub 仓库链接(https://github.com/owner/repo)或 github:owner/repo。",+ "请输入 GitHub 仓库链接或 Git SSH 克隆地址。CNB 只支持 HTTPS + 访问令牌。",);return;}@@ -1339,17 +1379,20 @@ export default function QuickAccessWizard({const existingRepo = (repositories || []).find((repo) =>repo.projectId === targetProject.id &&- (repo.gongfengProjectId === parsedRepo.project ||- repo.webUrl === parsedRepo.webUrl),+ (parsedRepo.provider === "ssh"+ ? repo.cloneUrl === parsedRepo.cloneUrl+ : repo.gongfengProjectId === parsedRepo.project ||+ repo.webUrl === parsedRepo.webUrl),);if (existingRepo) {boundRepo = await write("/api/repositories",{...existingRepo,+ provider: parsedRepo.provider,name: parsedRepo.name,gongfengProjectId: parsedRepo.project,- webUrl: parsedRepo.webUrl,+ webUrl: parsedRepo.webUrl || existingRepo.webUrl,cloneUrl: parsedRepo.cloneUrl,defaultBranch: repoBranch.trim() || "main",repoUrl: repoUrl.trim(),@@ -1466,7 +1509,7 @@ export default function QuickAccessWizard({repository: boundRepo,workflow: provisionedWorkflow || activeWorkflow,rolesCount: roles.length,- gitReady: Boolean(latestUser?.gitTokenConfigured),+ gitReady: Boolean(boundRepo?.provider === "ssh" ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) : latestUser?.gitTokenConfigured),codeBuddyReady: Boolean(latestUser?.codeBuddyApiKeyConfigured ||storedUser?.codeBuddyApiKeyConfigured,@@ -1641,7 +1684,7 @@ export default function QuickAccessWizard({size={14}/><span>- GitHub 访问:+ {completedSummary?.repository?.provider === "ssh" ? "Git SSH 访问:" : "GitHub 访问:"}{completedSummary?.gitReady? "已就绪": "未配置,克隆/推送私有仓库前可在个人配置补齐"}@@ -1786,6 +1829,7 @@ export default function QuickAccessWizard({{storedUser?.gitTokenConfigured ? "管理 GitHub 授权" : "连接 GitHub"}</button><p className="qa-hint">在个人配置中完成授权,返回后继续;无需手动复制令牌。</p>+ <p className="qa-hint">GitLab 等 SSH 仓库:<button type="button" className="qa-link-btn" onClick={() => openCredentialSettings("gitSshKey")}>{hasSSHKeys ? "管理 Git SSH 密钥" : "配置 Git SSH 密钥"}</button></p><details><summary>使用访问令牌(高级)</summary><div className="qa-input-row">@@ -1972,7 +2016,7 @@ export default function QuickAccessWizard({/^https?:\/\//,"",)- : repo.gongfengProjectId || repo.webUrl}+ : repo.gongfengProjectId || repo.webUrl || repo.cloneUrl}</code><small>{repo.defaultBranch || "main"}@@ -2056,14 +2100,14 @@ export default function QuickAccessWizard({? "旧项目可直接追加新仓库,复用已有流程与角色;留空则沿用现有仓库": "沿用项目现有仓库与流程": bindRepoNow- ? "粘贴 GitHub 仓库链接,自动设为项目默认仓库"+ ? "粘贴 GitHub 链接或 Git SSH 地址,自动设为项目默认仓库": "已跳过,可在派发需求或项目配置中再绑定"}</span></div><HarnessSwitchchecked={bindRepoNow}onChange={setBindRepoNow}- label="添加或绑定 GitHub 仓库"+ label="添加或绑定代码仓库"/></header>@@ -2112,8 +2156,8 @@ export default function QuickAccessWizard({<span className="qa-label">{projectMode === "existing" &&projectRepos.length- ? "新增 GitHub 仓库地址(可选)"- : "GitHub 仓库地址"}+ ? "新增仓库地址(可选)"+ : "GitHub 链接或 Git SSH 地址"}</span><inputclassName="qa-input qa-mono"@@ -2160,12 +2204,14 @@ export default function QuickAccessWizard({</p>) : (<p key="help" className="qa-hint">- 支持粘贴 GitHub 仓库链接、- <code>- [email protected]:owner/repo.git- </code> 或 <code>github:owner/repo</code>。+ 支持 GitHub 链接或 Git SSH 地址,例如 <code>[email protected]:group/repo.git</code>。</p>)}+ {selectedSSHRepo?.provider === "ssh" && sshKeysLoaded && !sshReady ? (+ <p className="qa-hint is-error" role="alert">+ {sshCredentials.error ? "无法读取 SSH 密钥配置,请稍后重试。" : `尚未配置 ${selectedSSHRepo.host} 的 SSH 密钥,可稍后在「个人配置 → Git SSH 密钥」添加。`}+ </p>+ ) : null}</div></div></div>@@ -2290,10 +2336,10 @@ export default function QuickAccessWizard({<dt>凭据</dt><dd><span- className={`qa-dot ${gitReady && (codeBuddyReady || sponsoredModel) ? "is-ok" : ""}`}+ className={`qa-dot ${(sshRepository ? sshReady : gitReady) && (codeBuddyReady || sponsoredModel) ? "is-ok" : ""}`}/><span>- GitHub {gitReady ? "已配置" : "未配置"} ·+ {sshRepository ? "Git SSH" : "GitHub"} {(sshRepository ? sshReady : gitReady) ? "已配置" : "未配置"} ·CodeBuddy{" "}{codeBuddyReady? "已配置"diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.jsindex df86f939..d3dbcb3b 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",+ gitSshKey: "Git SSH 密钥",};// A CodeBuddy key only works on the edition that issued it, and the CLI@@ -85,6 +86,13 @@ export function codeBuddyKeyWarning(key) {// Where and how to get each credential. Keep in sync with// assistantCredentialRules in internal/httpapi/assistant_run_view.go.export const CREDENTIAL_GUIDES = {+ gitSshKey: {+ steps: [+ "把专用公钥添加到代码托管账号,并按需授予仓库写权限",+ "到「个人配置 → Git SSH 密钥」为该主机添加无口令私钥,同一主机的仓库自动共用;请管理员信任该 SSH 主机",+ "回到这里重试",+ ],+ },gitToken: {url: "/#/settings",link: "连接 GitHub",@@ -136,6 +144,10 @@ const RULES = ["codeBuddyApiKey",/CodeBuddy[^。\n]{0,20}(API Key|Key|凭据)|拒绝了你的 API Key/i,],+ [+ "gitSshKey",+ /Git SSH (?:密钥|私钥)/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,@@ -158,11 +170,11 @@ export function credentialHint(text) {return null;}-export function openCredentialSettings(field) {+export function openCredentialSettings(field, sshRemote) {const credential = CREDENTIALS[field] ? field : "";if (window.parent !== window)window.parent.postMessage(- { type: "agentflow-chat-open-view", view: "settings", credential },+ { type: "agentflow-chat-open-view", view: "settings", credential, ...(credential === "gitSshKey" && sshRemote ? { sshRemote } : {}) },location.origin,);else location.href = "/#/settings";diff --git a/chatbot/src/quick-access-wizard.css b/chatbot/src/quick-access-wizard.cssindex c8092066..db914734 100644--- a/chatbot/src/quick-access-wizard.css+++ b/chatbot/src/quick-access-wizard.css@@ -1018,6 +1018,10 @@color: var(--qa-warn-text);}+.qa-hint.is-error {+ color: var(--qa-err-text);+}+.qa-repo-permission {margin-bottom: 12px;padding: 10px 12px;diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsxindex 06bb5bee..e3f68004 100644--- a/chatbot/tests/quick-access-wizard.test.jsx+++ b/chatbot/tests/quick-access-wizard.test.jsx@@ -21,6 +21,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {} : user];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/workflows")return [{@@ -35,7 +36,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {if (path.includes("/verify")) return { valid: true };return [];});- const mockState = { failClone: false, unconfigured: false, users: null };+ const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null };const writeMock = vi.fn(async (path, body) => {if (path.includes("/git-token/verify")) return { valid: true };if (path === "/api/projects") return { ...project, ...body };@@ -78,13 +79,19 @@ describe("QuickAccessWizard", () => {webUrl: "https://github.com/acme/widgets",cloneUrl: "https://github.com/acme/widgets.git",});- expect(parseGongfengRepo("[email protected]:acme/widgets.git")?.project).toBe("github:acme/widgets");+ // GitHub SSH-style addresses stay GitHub repositories (token + automatic PRs).+ for (const address of ["[email protected]:acme/widgets.git", "ssh://[email protected]/acme/widgets.git"]) {+ expect(parseGongfengRepo(address)).toMatchObject({ provider: "github", project: "github:acme/widgets" });+ }+ expect(parseGongfengRepo("ssh://[email protected]:2222/acme/widgets.git")?.provider).toBe("ssh");+ expect(parseGongfengRepo("git clone ssh://[email protected]:2222/team/sub/app.git")).toMatchObject({+ provider: "ssh", name: "app", cloneUrl: "ssh://[email protected]:2222/team/sub/app.git",+ });expect(parseGongfengRepo("github:acme/widgets")?.cloneUrl).toBe("https://github.com/acme/widgets.git");expect(parseGongfengRepo("git clone https://github.com/acme/widgets.git")?.name).toBe("widgets");expect(parseGongfengRepo("https://[email protected]/acme/widgets")).toBeNull();expect(parseGongfengRepo("https://github.com/acme")).toBeNull();- expect(parseGongfengRepo("[email protected]:team/repo.git")?.project).toBe("team/repo");- expect(parseGongfengRepo("[email protected]:team/repo.git")?.provider).toBe("gongfeng");+ expect(parseGongfengRepo("[email protected]:team/repo.git")?.provider).toBe("ssh");expect(parseGongfengRepo("https://git.example.com/team/repo/-/tree/main")?.name).toBe("repo");expect(parseGongfengRepo("https://example.com/team/repo")).toBeNull();expect(parseGongfengRepo("")).toBeNull();@@ -140,6 +147,46 @@ describe("QuickAccessWizard", () => {expect(completed).toHaveBeenCalledWith("p1");});+ test("warns only when the selected SSH host has no personal key and refreshes after settings changes", async () => {+ mockState.sshKeys = [{ id: "gitlab", name: "GitLab", host: "gitlab.example.org:22" }];+ const userAction = userEvent.setup();+ try {+ render(<QuickAccessWizard open user={{ ...user, gitSshKeyConfigured: true }} projects={[project]} projectId="p1" sponsoredModel="m1" onClose={vi.fn()} onCompleted={vi.fn()} onOpenView={vi.fn()} />);+ await screen.findByRole("dialog");+ await waitFor(() => expect(apiMock).toHaveBeenCalledWith("/api/users/1/git-ssh-keys"));+ await userAction.click(screen.getByRole("button", { name: "下一步" }));+ await screen.findByText("项目与仓库", { selector: "h3" });+ const address = screen.getByPlaceholderText(/https:\/\/github.com\/owner\/repo/);+ await userAction.type(address, "[email protected]:team/repo.git");+ expect(screen.queryByText(/尚未配置 .* 的 SSH 密钥/)).toBeNull();+ expect(screen.queryByRole("button", { name: "配置此仓库的 SSH 密钥" })).toBeNull();+ await userAction.clear(address);+ await userAction.type(address, "ssh://[email protected]:2222/team/repo.git");+ expect(screen.getByRole("alert")).toHaveTextContent("尚未配置 gitlab.example.org:2222 的 SSH 密钥");+ expect(screen.getByRole("alert").querySelector("button")).toBeNull();+ mockState.sshKeys = [...mockState.sshKeys, { id: "port", name: "Other SSH port", host: "gitlab.example.org:2222" }];+ window.dispatchEvent(new MessageEvent("message", { origin: location.origin, source: window.parent, data: { type: "agentflow-credentials-changed" } }));+ await waitFor(() => expect(screen.queryByText(/尚未配置 .* 的 SSH 密钥/)).toBeNull());+ expect(address).toHaveValue("ssh://[email protected]:2222/team/repo.git");+ await userAction.clear(address);+ await userAction.type(address, "[email protected]:team/repo.git");+ expect(screen.getByRole("alert")).toHaveTextContent("尚未配置 gitea.example.org:22 的 SSH 密钥");+ await userAction.clear(address);+ await userAction.type(address, "https://github.com/team/repo");+ expect(screen.queryByText(/尚未配置 .* 的 SSH 密钥/)).toBeNull();+ await userAction.clear(address);+ await userAction.type(address, "[email protected]:team/repo.git");+ expect(screen.getByRole("alert")).toHaveTextContent("可稍后");+ await userAction.click(screen.getByRole("button", { name: "下一步" }));+ await screen.findByText("默认角色与 SOP", { selector: "h3" });+ await userAction.click(screen.getByRole("button", { name: "完成接入" }));+ expect(await screen.findByText("快速接入已完成")).toBeInTheDocument();+ expect(writeMock).toHaveBeenCalledWith("/api/repositories", expect.objectContaining({ provider: "ssh", cloneUrl: "[email protected]:team/repo.git" }));+ } finally {+ mockState.sshKeys = null;+ }+ });+test("validates and saves typed credentials", async () => {mockState.unconfigured = true;const userAction = userEvent.setup();@@ -156,7 +203,7 @@ describe("QuickAccessWizard", () => {);await screen.findByRole("dialog");await userAction.click(screen.getByRole("button", { name: "下一步" }));- expect(screen.getByText(/请至少填写 GitHub Git Token 与 CodeBuddy API Key/)).toBeInTheDocument();+ expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key");expect(screen.queryByText(/工蜂/)).toBeNull();await userAction.click(screen.getByText("使用访问令牌(高级)"));await userAction.type(diff --git a/compose.yaml b/compose.yamlindex 07fb8a81..718e6dfb 100644--- a/compose.yaml+++ b/compose.yaml@@ -32,6 +32,7 @@ services:AGENTFLOW_ALLOW_SIGNUP: ${AGENTFLOW_ALLOW_SIGNUP:-true}AGENTFLOW_SECURE_COOKIES: ${AGENTFLOW_SECURE_COOKIES:-false}AGENTFLOW_GITHUB_CLIENT_ID: ${AGENTFLOW_GITHUB_CLIENT_ID:-}+ AGENTFLOW_GIT_SSH_KNOWN_HOSTS: ${AGENTFLOW_GIT_SSH_KNOWN_HOSTS:-}AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistantAGENTFLOW_CLARIFY_SESSION_DIR: /data/clarifyAGENTFLOW_ASSISTANT_MODEL: ${AGENTFLOW_ASSISTANT_MODEL:-}diff --git a/docs/deployment.md b/docs/deployment.mdindex d750e03d..b2ec4f3b 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -83,6 +83,18 @@ Cloning a repository and building a custom sandbox image report progress while tA clone that is stopped this way is not retried, since a retry would wait on the same network. When the execution host reaches GitHub or Debian mirrors slowly, point git at a proxy (`git config --global http.proxy`) and use a nearby package mirror in the Dockerfile rather than raising these limits.+### Git repositories over SSH++Use Git SSH for GitLab.com, self-managed GitLab, Gitea, Gogs, GitHub, and other Git hosts that offer this transport. In **Project settings → Code repositories** or **Quick access**, enter the clone address, such as `[email protected]:group/repo.git` or `ssh://[email protected]:2222/group/repo.git`, and select the existing default branch. GitHub HTTPS continues to use GitHub authorization or a PAT.++1. The deployment administrator creates a dedicated OpenSSH `known_hosts` file. Verify the host keys against the provider's published fingerprints or with the server administrator before adding them. Use exact hostnames or IP addresses, with `[host]:port` for a nondefault port. Wildcards and hashed entries do not grant access. For a trusted team deployment, add internal hosts explicitly to this same file.+2. Set `AGENTFLOW_GIT_SSH_KNOWN_HOSTS` to the file's absolute path on the platform, workers and execution machines. For Compose, put it under the existing `LOOPFORGE_DATA_DIR` bind mount and set the absolute path in `.env`. Install Git and the OpenSSH client on execution machines and in custom sandbox images. Upgrade execution machines to Runner **0.9.3** or later. Docker sandbox commands need the sandbox and execution process to share the Linux kernel for the signing agent socket. With a Docker VM separate from a native runner, use managed checkout and delivery, or use a native sandbox for interactive Git commands.+3. Generate dedicated SSH keys with no passphrase for unattended execution. Add each public key to your hosting account and grant access to the repositories it needs. Grant write access if the run must push. Under **Personal settings → Git SSH keys**, add one private key per SSH host, such as `gitlab.com` or `git.example.org:2222`. An omitted port means 22. Edit that host's entry to replace its key.++Repositories automatically use the current user's key for their SSH host and port; repositories on the same host and port share that key. The repository form only shows a red warning when that host has no personal key. This reminder does not block saving the repository or completing setup; credentials and host trust can be configured before the first Git operation. There is no repository-specific or default fallback key. Checkout and SOP execution use the responsible user's keys. Conversation submission and the workspace terminal use the requesting user's keys. The temporary signing agent closes when the command or terminal ends. A terminal's agent never lives in the shared workspace: with the `bwrap` driver it sits in a private directory bound only into that terminal, and with the `local` driver (no isolation) it stays outside the workspace in a 0700 directory. Docker and seatbelt workspaces share one filesystem view among all their processes, so their terminals get no personal SSH key; push from there with the platform's submit action. `[email protected]:` and `ssh://[email protected]/` addresses are saved as GitHub repositories (HTTPS + token, automatic pull requests) unless `provider` is explicitly `ssh`. To rotate a key, replace it in settings and revoke the old public key at the host.++SSH handles clone, fetch and push. A conversation delivery returns the branch and commit SHA. You can optionally add a repository web URL to open the host and create a PR/MR manually. Issue import and PR/MR automation need a hosting API credential. To automate those actions, add a hosting-specific MCP in **Settings → Assets → MCP**, give it its own scoped token, and attach it to the relevant agent or workflow. [CNB does not support Git SSH](https://docs.cnb.cool/en/guide/git-access.html); it uses HTTPS with a CNB access token, which is outside this integration.+## AccountsThe first account created in the browser becomes the platform administrator. After that, anyone who can reach the login page may sign up as a regular user while `AGENTFLOW_ALLOW_SIGNUP` is `true` (the default). Registered users can create requirements and run SOPs on your workers, so set `AGENTFLOW_ALLOW_SIGNUP=false` for any installation reachable from untrusted networks and create accounts explicitly instead.diff --git a/docs/open-source-scope.md b/docs/open-source-scope.mdindex a92683c3..97cb123b 100644--- a/docs/open-source-scope.md+++ b/docs/open-source-scope.md@@ -17,7 +17,7 @@ This repository contains the self-hosted platform and LoopForge Local. Detailed| Theme | Upstream light/dark styles; preference applied before first paint and persisted || LoopForge Local | Built-in workflows, host integrations, installers and tests under `local/`; guides under `docs/local/`; project policies and history at the repository root |-Legacy organization-specific tracker and authentication protocol code remains as optional compatibility code with example endpoints; it is not automatically configured, and its Web entry points (external tracker sync fields, TAPD import/push) stay hidden so the default UI only offers GitHub and platform-local requirements. Public defaults never install enterprise MCP servers or contact corporate identity/market services. GitHub Enterprise and non-GitHub public hosting require additional provider configuration/adapters; the initial public adapter targets github.com.+Legacy organization-specific tracker and authentication protocol code remains as optional compatibility code with example endpoints. Its Web entry points (external tracker sync fields, TAPD import/push) stay hidden by default. The built-in public hosting API adapter targets github.com. GitHub Enterprise, GitLab, Gitea and other Git hosts can be bound for clone and push through [Git SSH](deployment.md#git-repositories-over-ssh); hosting API actions need their own adapter or MCP. Public defaults never install enterprise MCP servers or contact corporate identity/market services.The source-only master does not carry its deployed database seed content. Public SOP definitions are therefore explicit public catalog data, not a claim to contain private production projects or prompts. Behavior and execution are shared with master; operator assets, credentials and private integrations are deployment data.diff --git a/internal/domain/project.go b/internal/domain/project.goindex b2d98d6a..cab80750 100644--- a/internal/domain/project.go+++ b/internal/domain/project.go@@ -63,6 +63,9 @@ type ProjectMember struct {Role string `json:"role"` // maintainer, member, viewer}+// RepositoryProviderSSH uses Git transport only; it has no hosting API adapter.+const RepositoryProviderSSH = "ssh"+type Repository struct {ID string `json:"id"`ProjectID string `json:"projectId"`diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.goindex bdde8c9e..772e262b 100644--- a/internal/domain/public_repository.go+++ b/internal/domain/public_repository.go@@ -17,8 +17,11 @@ func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) {if strings.HasPrefix(s, "github:") {s = "https://github.com/" + strings.TrimPrefix(s, "github:")}- if strings.HasPrefix(s, "[email protected]:") {- s = "https://github.com/" + strings.TrimPrefix(s, "[email protected]:")+ for _, prefix := range []string{"[email protected]:", "ssh://[email protected]/", "ssh://[email protected]:22/"} {+ if strings.HasPrefix(s, prefix) {+ s = "https://github.com/" + strings.TrimPrefix(s, prefix)+ break+ }}if strings.HasPrefix(s, "github.com/") {s = "https://" + sdiff --git a/internal/domain/runner.go b/internal/domain/runner.goindex 536a2e79..fb7ada1b 100644--- a/internal/domain/runner.go+++ b/internal/domain/runner.go@@ -84,6 +84,12 @@ func (r Runner) SupportsConversationWorkspace() bool {// it directly, without a Gongfeng MR.const RunnerVersionSharedPush = "0.9.0"+const RunnerVersionGitSSH = "0.9.3"++func (r Runner) SupportsGitSSH() bool {+ return versionAtLeast(r.RunnerVersion, RunnerVersionGitSSH)+}+func (r Runner) SupportsSharedPush() bool {return versionAtLeast(r.RunnerVersion, RunnerVersionSharedPush)}@@ -379,6 +385,8 @@ func PublicRunnerTask(task RunnerTask) RunnerTask {copyInvocation.AgentCLIAPIKey = ""copyInvocation.AgentCLIBaseURL = ""copyInvocation.AgentCLIProtocol = ""+ copyInvocation.GitSSHUserID = 0+ copyInvocation.GitSSHKeys = nilif copyInvocation.Repository != nil {copyRepository := *copyInvocation.RepositorycopyRepository.GitToken = ""@@ -451,6 +459,10 @@ type RunnerInvocation struct {// the task workspace, so the sandbox and workspace live on that machine.// Legacy single-repository field; Repositories is authoritative when set.Repository *RunnerRepository `json:"repository,omitempty"`+ // Only the user reference is stored in the queue. GitSSHKeys is filled on+ // authenticated claim or on the outbound workspace control connection.+ GitSSHUserID int64 `json:"gitSshUserId,omitempty"`+ GitSSHKeys map[string]string `json:"gitSshKeys,omitempty"` // clone URL to private key// Repositories lists every repository the run touches (multi-repository// support). Each entry checks out into its Dir under the task workspace.Repositories []RunnerRepository `json:"repositories,omitempty"`@@ -466,6 +478,7 @@ type RunnerRepository struct {Ref string `json:"ref,omitempty"`WorkBranch string `json:"workBranch,omitempty"`GitToken string `json:"gitToken,omitempty"`+ UseSSH bool `json:"useSsh,omitempty"`// RequireExistingWorkBranch keeps explicit continuation on an existing// remote head. Missing/deleted heads are errors, never branch creation.RequireExistingWorkBranch bool `json:"requireExistingWorkBranch,omitempty"`@@ -493,6 +506,21 @@ type RunnerRepository struct {DefaultBranch string `json:"defaultBranch,omitempty"`}+func (inv *RunnerInvocation) GitSSHRemotes() []string {+ var remotes []string+ if inv != nil {+ for _, repository := range inv.Repositories {+ if repository.UseSSH {+ remotes = append(remotes, repository.CloneURL)+ }+ }+ if len(inv.Repositories) == 0 && inv.Repository != nil && inv.Repository.UseSSH {+ remotes = append(remotes, inv.Repository.CloneURL)+ }+ }+ return remotes+}+// RunnerInputFile is one file written into the task workspace before a run.type RunnerInputFile struct {Path string `json:"path"`diff --git a/internal/domain/runner_workspace.go b/internal/domain/runner_workspace.goindex 3fd99608..199844a7 100644--- a/internal/domain/runner_workspace.go+++ b/internal/domain/runner_workspace.go@@ -53,6 +53,7 @@ type RunnerWorkspaceRequest struct {Checkpoint []byte `json:"checkpoint,omitempty"`Terminal *WorkspaceTerminalRequest `json:"terminal,omitempty"`TerminalOwner int64 `json:"terminalOwner,omitempty"`+ TerminalGitSSHKeys map[string]string `json:"terminalGitSshKeys,omitempty"`// WorkspaceRunID selects the shared checkout owner; RunID continues to// identify this run's independent sandbox, terminal scope and locks.Browser *BrowserRequest `json:"browser,omitempty"`diff --git a/internal/domain/user.go b/internal/domain/user.goindex 2ad22a72..55cec9f2 100644--- a/internal/domain/user.go+++ b/internal/domain/user.go@@ -33,6 +33,7 @@ type User struct {GitToken string `json:"gitToken,omitempty"`GitTokenConfigured bool `json:"gitTokenConfigured,omitempty"`GitTokenOAuth bool `json:"gitTokenOAuth,omitempty"`+ GitSSHKeyConfigured bool `json:"gitSshKeyConfigured,omitempty"`GongfengRefreshToken string `json:"-"`GongfengTokenExpiresAt time.Time `json:"-"`CodeBuddyAPIKey string `json:"codeBuddyApiKey,omitempty"`@@ -44,6 +45,13 @@ type User struct {const PlatformRoleAdmin = "admin"+// GitSSHKey is the public description of a personal SSH credential.+type GitSSHKey struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Host string `json:"host"`+}+// NormalizeCodeBuddyInternetEnvironment maps a network environment chosen in// personal settings to the CODEBUDDY_INTERNET_ENVIRONMENT value: "" for the// international edition, "internal" for the China edition and "ioa" for iOA.diff --git a/internal/engine/align.go b/internal/engine/align.goindex 592ad392..4ad0e843 100644--- a/internal/engine/align.go+++ b/internal/engine/align.go@@ -113,6 +113,10 @@ func ShouldAlignIntegrate(r domain.RepositoryContext) bool {// returned as AlignConflictError (with extracted conflict hunks); the remote// integrate branch is left unchanged.func AlignIntegrateBaseline(repository domain.RepositoryContext, gitToken string, locks IntegrationLocker) error {+ return alignIntegrateBaseline(context.Background(), repository, gitToken, locks)+}++func alignIntegrateBaseline(ctx context.Context, repository domain.RepositoryContext, gitToken string, locks IntegrationLocker) error {if !ShouldAlignIntegrate(repository) {return nil}@@ -128,7 +132,7 @@ func AlignIntegrateBaseline(repository domain.RepositoryContext, gitToken stringwork.WorkBranch = ""work.IntegrateBranch = domain.NormalizeIntegrateBranch(repository.IntegrateBranch)work.BaseBranch = work.IntegrateBranch- ctx := withGitToken(context.Background(), gitToken)+ ctx = withRepositoryGit(withGitToken(ctx, gitToken), work)if err := prepareRepository(ctx, dir, work); err != nil {return err}diff --git a/internal/engine/clarify_workspace.go b/internal/engine/clarify_workspace.goindex a4f11438..6e2a94b1 100644--- a/internal/engine/clarify_workspace.go+++ b/internal/engine/clarify_workspace.go@@ -47,9 +47,10 @@ func PrepareClarifyWorkspaceAtBranch(ctx context.Context, cacheDir string, repobaseBranch = "master"}- if strings.TrimSpace(token) == "" {- // A readable local repository needs no remote credentials. HTTP/SSH- // sources still require the responsible user's configured Git token.+ if repo.Provider == domain.RepositoryProviderSSH {+ ctx = gitwork.WithSSHRemote(ctx, cloneURL)+ } else if strings.TrimSpace(token) == "" {+ // A readable local repository needs no remote credentials.if info, err := os.Stat(cloneURL); err != nil || !info.IsDir() {return "", fmt.Errorf("需求责任人未配置 Git Token(未指定责任人时用项目 Owner),请让该账号到「个人配置 → 个人凭证」填写。新建需求分析拉代码用的是责任人凭证,不是当前点击的人")}@@ -74,7 +75,7 @@ func PrepareClarifyWorkspaceAtBranch(ctx context.Context, cacheDir string, repoargs := []string{"clone", "--no-hardlinks", "--single-branch", "--depth", "1","--branch", baseBranch,- "--", gitwork.RewriteRemoteForToken(cloneURL, token), cacheDir,+ "--", cloneRemoteForGit(ctx, cloneURL), cacheDir,}if _, err := runGit(ctx, cacheDir, args...); err != nil {_ = os.RemoveAll(cacheDir)diff --git a/internal/engine/conversation_branch_choice_test.go b/internal/engine/conversation_branch_choice_test.goindex 3b62e1f1..f383e8d8 100644--- a/internal/engine/conversation_branch_choice_test.go+++ b/internal/engine/conversation_branch_choice_test.go@@ -114,14 +114,14 @@ func TestPushConversationWorkspaceRefusesAnotherCheckedOutBranch(t *testing.T) {if err := os.WriteFile(filepath.Join(checkout, "app.txt"), []byte("changed\n"), 0o600); err != nil {t.Fatal(err)}- if _, err := e.PushConversationWorkspace(context.Background(), run.ID, "token", "alice", "[email protected]", "msg", ""); err == nil || !strings.Contains(err.Error(), "feature/manual") || !strings.Contains(err.Error(), "feature/recorded") {+ if _, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "token", "alice", "[email protected]", "msg", ""); err == nil || !strings.Contains(err.Error(), "feature/manual") || !strings.Contains(err.Error(), "feature/recorded") {t.Fatalf("push from another branch must be refused: %v", err)}if out, _ := exec.Command("git", "-C", remote, "branch", "--list", "feature/*").CombinedOutput(); strings.TrimSpace(string(out)) != "" {t.Fatalf("nothing may be pushed from a drifted checkout: %s", out)}testGit(t, checkout, "checkout", "feature/recorded")- heads, err := e.PushConversationWorkspace(context.Background(), run.ID, "token", "alice", "[email protected]", "msg", "")+ heads, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "token", "alice", "[email protected]", "msg", "")if err != nil || len(heads) != 1 || heads[0].WorkBranch != "feature/recorded" {t.Fatalf("back on the recorded branch the push goes through, read-only repositories stay out: %+v %v", heads, err)}diff --git a/internal/engine/conversation_push.go b/internal/engine/conversation_push.goindex 96904287..1315a441 100644--- a/internal/engine/conversation_push.go+++ b/internal/engine/conversation_push.go@@ -21,9 +21,9 @@ const (// pushes the work branch of every bound repository that differs from its base,// so a conversation can open an MR without an SOP delivery node. Unchanged// repositories are left out of the returned heads. Callers-// hold the conversation workspace lease and pass the requesting user's own-// token: the push is attributed to whoever asked for it.-func (e *Engine) PushConversationWorkspace(ctx context.Context, runID, gitToken, gitUserName, gitUserEmail, message, sharedTarget string) ([]domain.RunnerWorkBranchHead, error) {+// hold the conversation workspace lease and supply the requesting user's Git+// identity, so the push is attributed to whoever asked for it.+func (e *Engine) PushConversationWorkspace(ctx context.Context, runID string, requesterID int64, gitToken, gitUserName, gitUserEmail, message, sharedTarget string) ([]domain.RunnerWorkBranchHead, error) {run, ok := e.repo.RunState(runID)if !ok {return nil, fmt.Errorf("运行不存在")@@ -31,18 +31,25 @@ func (e *Engine) PushConversationWorkspace(ctx context.Context, runID, gitToken,if WorkspaceRunID(run) != run.ID {return nil, fmt.Errorf("子 SOP 共享父任务工作区,请从父任务提交")}- if strings.TrimSpace(gitToken) == "" {- return nil, fmt.Errorf("未配置 Git Token,无法推送工作分支。%s", gitTokenFixHint)- }var repositories []domain.RepositoryContextfor _, rc := range run.RepositoryContexts() {- if strings.TrimSpace(rc.CloneURL) != "" && strings.TrimSpace(rc.WorkBranch) != "" {- repositories = append(repositories, rc)+ if rc.ReadOnly || strings.TrimSpace(rc.CloneURL) == "" || strings.TrimSpace(rc.WorkBranch) == "" {+ continue+ }+ if rc.Provider != domain.RepositoryProviderSSH && strings.TrimSpace(gitToken) == "" {+ return nil, fmt.Errorf("%s: 未配置 Git Token,无法推送工作分支。%s", rc.Name, gitTokenFixHint)}+ repositories = append(repositories, rc)}if len(repositories) == 0 {return nil, fmt.Errorf("当前任务没有绑定可推送的代码仓库")}+ sshKeys := e.repo.GitSSHKeysForRemotes(requesterID, sshRepositoryURLs(repositories))+ for _, rc := range repositories {+ if rc.Provider == domain.RepositoryProviderSSH && sshKeys[rc.CloneURL] == "" {+ return nil, fmt.Errorf("%s: %w", rc.Name, gitwork.ErrSSHKeyRequired)+ }+ }message = strings.TrimSpace(message)if message == "" {message = "LoopForge: " + strings.TrimSpace(run.Input)@@ -52,8 +59,9 @@ func (e *Engine) PushConversationWorkspace(ctx context.Context, runID, gitToken,ctx, cancel := context.WithTimeout(ctx, conversationPushTimeout)defer cancel()ctx = withGitIdentity(withGitToken(ctx, gitToken), gitUserName, gitUserEmail)+ ctx = gitwork.WithSSHKeys(ctx, sshKeys)if runnerID := e.defaultExecutionRunner(run); runnerID != "" {- return e.pushConversationOnRunner(ctx, runnerID, run, repositories, gitToken, gitUserName, gitUserEmail, message, sharedTarget)+ return e.pushConversationOnRunner(ctx, runnerID, run, repositories, requesterID, gitToken, gitUserName, gitUserEmail, message, sharedTarget)}root, reason := e.LocalRunWorkspace(run)if reason != "" {@@ -61,6 +69,7 @@ func (e *Engine) PushConversationWorkspace(ctx context.Context, runID, gitToken,}heads := []domain.RunnerWorkBranchHead{}for _, rc := range repositories {+ ctx := withRepositoryGit(ctx, rc)dir := repositoryWorkspacePath(root, rc)if !gitwork.HasWork(ctx, dir, repositoryBaseBranch(rc)) {continue@@ -105,7 +114,7 @@ func (e *Engine) PushConversationWorkspace(ctx context.Context, runID, gitToken,return heads, nil}-func (e *Engine) pushConversationOnRunner(ctx context.Context, runnerID string, run domain.Run, repositories []domain.RepositoryContext, gitToken, gitUserName, gitUserEmail, message, sharedTarget string) ([]domain.RunnerWorkBranchHead, error) {+func (e *Engine) pushConversationOnRunner(ctx context.Context, runnerID string, run domain.Run, repositories []domain.RepositoryContext, requesterID int64, gitToken, gitUserName, gitUserEmail, message, sharedTarget string) ([]domain.RunnerWorkBranchHead, error) {if run.ExecutionContext.RunnerWorkspaceLayout != domain.RunnerWorkspaceLayoutShared {return nil, fmt.Errorf("该任务的执行机器工作区不是共享布局,暂不支持直接提交 MR")}@@ -113,6 +122,9 @@ func (e *Engine) pushConversationOnRunner(ctx context.Context, runnerID string,if !ok {return nil, fmt.Errorf("执行机器 %s 不存在", runnerID)}+ if err := e.requireWorkBranchCapabilities(runnerID, repositories); err != nil {+ return nil, err+ }if sharedTarget != "" && !runner.SupportsSharedPush() {return nil, fmt.Errorf("执行机器 %s 的 runner 版本是 %s,还不支持直推共享分支(需要 %s 及以上);请先升级 runner,或改用 MR 提交", runnerID, strings.TrimSpace(runner.RunnerVersion), domain.RunnerVersionSharedPush)}@@ -132,6 +144,11 @@ func (e *Engine) pushConversationOnRunner(ctx context.Context, runnerID string,}}invocation.Repositories = kept+ if len(invocation.GitSSHRemotes()) > 0 {+ invocation.GitSSHUserID = requesterID+ } else {+ invocation.GitSSHUserID = 0+ }task := domain.RunnerTask{ID: fmt.Sprintf("rt-%d-%s-push", time.Now().UnixNano(), safeRunnerPath(run.ID)),RunnerID: runnerID,diff --git a/internal/engine/conversation_push_test.go b/internal/engine/conversation_push_test.goindex fa462df1..1e96154b 100644--- a/internal/engine/conversation_push_test.go+++ b/internal/engine/conversation_push_test.go@@ -58,10 +58,10 @@ func TestPushConversationWorkspaceCommitsAndPushesWorkBranch(t *testing.T) {t.Fatal(err)}- if _, err := e.PushConversationWorkspace(context.Background(), run.ID, "", "alice", "[email protected]", "msg", ""); err == nil || !strings.Contains(err.Error(), "Git Token") {+ if _, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "", "alice", "[email protected]", "msg", ""); err == nil || !strings.Contains(err.Error(), "Git Token") {t.Fatalf("missing token must explain the fix: %v", err)}- heads, err := e.PushConversationWorkspace(context.Background(), run.ID, "token", "alice", "[email protected]", "fix: 改文案", "")+ heads, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "token", "alice", "[email protected]", "fix: 改文案", "")if err != nil {t.Fatal(err)}@@ -74,7 +74,7 @@ func TestPushConversationWorkspaceCommitsAndPushesWorkBranch(t *testing.T) {if msg := testGit(t, remote, "log", "-1", "--format=%s|%an", "feature/direct"); msg != "fix: 改文案|alice" {t.Fatalf("commit = %q", msg)}- again, err := e.PushConversationWorkspace(context.Background(), run.ID, "token", "alice", "[email protected]", "noop", "")+ again, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "token", "alice", "[email protected]", "noop", "")if err != nil || len(again) != 1 || again[0].Head != heads[0].Head {t.Fatalf("re-push without changes must report the same head: %+v %v", again, err)}@@ -86,7 +86,7 @@ func TestPushConversationWorkspaceCommitsAndPushesWorkBranch(t *testing.T) {if err := os.WriteFile(filepath.Join(checkout, "app.txt"), []byte("shared\n"), 0o600); err != nil {t.Fatal(err)}- direct, err := e.PushConversationWorkspace(context.Background(), run.ID, "token", "alice", "[email protected]", "feat: 直推 preview", "preview")+ direct, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "token", "alice", "[email protected]", "feat: 直推 preview", "preview")if err != nil {t.Fatal(err)}diff --git a/internal/engine/conversation_workspace.go b/internal/engine/conversation_workspace.goindex fbd7a8f8..d77ca47d 100644--- a/internal/engine/conversation_workspace.go+++ b/internal/engine/conversation_workspace.go@@ -10,6 +10,7 @@ import ("time""agentflow/internal/domain"+ "agentflow/internal/gitwork""agentflow/internal/repo")@@ -148,8 +149,10 @@ func (e *Engine) MaterializeConversationWorkspace(ctx context.Context, id stringdefer env.nodeMu.Unlock()// Same checkout as an SOP node: the responsible user's Git Token, the// frozen base branch, and a fresh work branch.- gitToken := env.credentialSnapshot().GitToken+ credentials := env.credentialSnapshot()+ gitToken := credentials.GitTokenctx = withGitToken(e.withPreparationProgress(ctx, run.ID), gitToken)+ ctx = gitwork.WithSSHKeys(ctx, credentials.GitSSHKeys)return env.prepareRepositoriesOnce(func() error {if err := prepareRepositories(ctx, env.Workspace(), run.RepositoryContexts()); err != nil {return explainGitAuthFailure(fmt.Errorf("repository checkout: %w", err), strings.TrimSpace(gitToken) != "")diff --git a/internal/engine/execution_cleanup_cases_test.go b/internal/engine/execution_cleanup_cases_test.goindex 8a533422..2e0fb2a0 100644--- a/internal/engine/execution_cleanup_cases_test.go+++ b/internal/engine/execution_cleanup_cases_test.go@@ -257,7 +257,7 @@ func TestWorkspacePreparationDirectValidationAndRemoteStates(t *testing.T) {if _, err := e.TrustedWorkspaceRequest("missing", domain.RunnerWorkspaceRequest{}); err == nil {t.Fatal("missing trusted request succeeded")}- if _, err := e.HandlePreparedWorkspaceTerminal(context.Background(), "missing", &runtime.TerminalPool{}, "scope", domain.WorkspaceTerminalRequest{Operation: "open"}); err == nil {+ if _, err := e.HandlePreparedWorkspaceTerminal(context.Background(), "missing", &runtime.TerminalPool{}, "scope", domain.WorkspaceTerminalRequest{Operation: "open"}, 0); err == nil {t.Fatal("unprepared terminal opened")}if state, err := e.PrepareNodeWorkspace(context.Background(), domain.Run{}, &runEnvironment{}); err != nil || state.Status != "ready" {diff --git a/internal/engine/git_auth.go b/internal/engine/git_auth.goindex ca8c9436..b8d3be8a 100644--- a/internal/engine/git_auth.go+++ b/internal/engine/git_auth.go@@ -8,6 +8,7 @@ import ("regexp""strings"+ "agentflow/internal/domain""agentflow/internal/gitwork""agentflow/internal/repo")@@ -27,6 +28,30 @@ func withGitToken(ctx context.Context, token string) context.Context {func gitTokenFrom(ctx context.Context) string { return gitwork.TokenFrom(ctx) }+func withRepositoryGit(ctx context.Context, repository domain.RepositoryContext) context.Context {+ if repository.Provider == domain.RepositoryProviderSSH {+ return gitwork.WithSSHRemote(ctx, repository.CloneURL)+ }+ return ctx+}++func sshRepositoryURLs(repositories []domain.RepositoryContext) []string {+ var urls []string+ for _, repository := range repositories {+ if repository.Provider == domain.RepositoryProviderSSH {+ urls = append(urls, repository.CloneURL)+ }+ }+ return urls+}++func cloneRemoteForGit(ctx context.Context, remote string) string {+ if gitwork.UsesSSH(ctx) {+ return remote+ }+ return gitwork.RewriteRemoteForToken(remote, gitTokenFrom(ctx))+}+func withGitIdentity(ctx context.Context, name, email string) context.Context {identity := gitIdentity{name: strings.TrimSpace(name), email: strings.TrimSpace(email)}if identity.name == "" || identity.email == "" {diff --git a/internal/engine/integrate.go b/internal/engine/integrate.goindex 363b2bee..e7064b27 100644--- a/internal/engine/integrate.go+++ b/internal/engine/integrate.go@@ -65,7 +65,9 @@ func (e *Engine) integrateScheduledRun(id string) (bool, error) {if env == nil {return false, fmt.Errorf("run sandbox missing")}- ctx := withGitIdentity(withGitToken(context.Background(), env.credentialSnapshot().GitToken), env.credentialSnapshot().GitUserName, env.credentialSnapshot().GitUserEmail)+ credentials := env.credentialSnapshot()+ ctx := withGitIdentity(withGitToken(context.Background(), credentials.GitToken), credentials.GitUserName, credentials.GitUserEmail)+ ctx = gitwork.WithSSHKeys(ctx, credentials.GitSSHKeys)runner, onRunner, err := e.integrationRunner(r)if err != nil {return false, err@@ -78,6 +80,7 @@ func (e *Engine) integrateScheduledRun(id string) (bool, error) {}}for _, rc := range repositories {+ ctx := withRepositoryGit(ctx, rc)b, w := strings.TrimSpace(rc.IntegrateBranch), strings.TrimSpace(rc.WorkBranch)if b == "" || w == "" {continue@@ -155,7 +158,7 @@ func integrateLocally(ctx context.Context, r domain.Run, workspace string, rc do// integration branch through a Gongfeng MR, or with pushDirect when Gongfeng// is not configured.func (e *Engine) mergeWorkBranchIntoIntegrate(id string, r domain.Run, rc domain.RepositoryContext, work, integrate string, pushDirect func() error) error {- if e.MergeIntoBranch != nil && strings.TrimSpace(rc.GongfengProjectID) != "" {+ if rc.Provider != domain.RepositoryProviderSSH && e.MergeIntoBranch != nil && strings.TrimSpace(rc.GongfengProjectID) != "" {title := integrateMRTitle(r, rc, work, integrate)ref, err := e.MergeIntoBranch(rc.GongfengProjectID, work, integrate, title, integrateMRDescription(r, work, integrate))if err != nil {diff --git a/internal/engine/integration_cases_test.go b/internal/engine/integration_cases_test.goindex 9fb9ecb3..8f784d40 100644--- a/internal/engine/integration_cases_test.go+++ b/internal/engine/integration_cases_test.go@@ -31,21 +31,21 @@ func TestRunnerIntegrateAndConversationPushCanceled(t *testing.T) {if _, err := e.integrateOnRunner(ctx, runner, run, run.Repositories[0], false); !errors.Is(err, context.Canceled) {t.Fatalf("integrate cancel = %v", err)}- if _, err := e.pushConversationOnRunner(ctx, runner.ID, run, run.Repositories, "token", "name", "mail", "message", ""); !errors.Is(err, context.Canceled) {+ if _, err := e.pushConversationOnRunner(ctx, runner.ID, run, run.Repositories, 0, "token", "name", "mail", "message", ""); !errors.Is(err, context.Canceled) {t.Fatalf("push cancel = %v", err)}legacy := runlegacy.ExecutionContext.RunnerWorkspaceLayout = ""- if _, err := e.pushConversationOnRunner(context.Background(), runner.ID, legacy, legacy.Repositories, "token", "", "", "message", ""); err == nil {+ if _, err := e.pushConversationOnRunner(context.Background(), runner.ID, legacy, legacy.Repositories, 0, "token", "", "", "message", ""); err == nil {t.Fatal("legacy runner layout pushed")}- if _, err := e.pushConversationOnRunner(context.Background(), "missing", run, run.Repositories, "token", "", "", "message", ""); err == nil {+ if _, err := e.pushConversationOnRunner(context.Background(), "missing", run, run.Repositories, 0, "token", "", "", "message", ""); err == nil {t.Fatal("missing runner pushed")}- if _, err := e.PushConversationWorkspace(context.Background(), "missing", "token", "", "", "", ""); err == nil {+ if _, err := e.PushConversationWorkspace(context.Background(), "missing", 0, "token", "", "", "", ""); err == nil {t.Fatal("missing run pushed")}- if _, err := e.PushConversationWorkspace(context.Background(), run.ID, "", "", "", "", ""); err == nil {+ if _, err := e.PushConversationWorkspace(context.Background(), run.ID, 0, "", "", "", "", ""); err == nil {t.Fatal("missing token pushed")}noRepos := run@@ -55,7 +55,7 @@ func TestRunnerIntegrateAndConversationPushCanceled(t *testing.T) {if err := st.PutRun(noRepos); err != nil {t.Fatal(err)}- if _, err := e.PushConversationWorkspace(context.Background(), noRepos.ID, "token", "", "", "", ""); err == nil {+ if _, err := e.PushConversationWorkspace(context.Background(), noRepos.ID, 0, "token", "", "", "", ""); err == nil {t.Fatal("repository-less run pushed")}if got := truncateCommitMessage(strings.Repeat("界", 2100)); len([]rune(got)) != 2000 {diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.goindex f70dd451..b46d984f 100644--- a/internal/engine/node_execute.go+++ b/internal/engine/node_execute.go@@ -2,6 +2,7 @@ package engineimport ("agentflow/internal/domain"+ "agentflow/internal/gitwork""agentflow/internal/repo""agentflow/internal/runtime""context"@@ -463,8 +464,10 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workflreturn sb.Exec(ctx, runtime.CommandSpec{Argv: []string{"sh", "-lc", bindExecutionTarget(command, target)}, Provider: "verification", CredentialBindings: []runtime.CredentialBinding{runtime.BindGit, runtime.BindMCP}}, gateSink)}current, _ = e.repo.RunState(runID)- gitTok := sb.credentialSnapshot().GitToken+ gitCredentials := sb.credentialSnapshot()+ gitTok := gitCredentials.GitTokenctx = withGitToken(ctx, gitTok)+ ctx = gitwork.WithSSHKeys(ctx, gitCredentials.GitSSHKeys)ctx = withGitIdentity(ctx, sb.credentialSnapshot().GitUserName, sb.credentialSnapshot().GitUserEmail)// Repository checkout and Agent-configuration index isolation belong to the// run environment, not to each node. The same checkout and .git/index are@@ -755,7 +758,11 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl}return result, dispatchErr}- boundAssets, skipped, bindErr := runtime.PrepareMCPServers(assets, runtime.MCPTarget{GitToken: sb.credentialSnapshot().GitToken, RequireCredentials: true})+ repositories := current.RepositoryContexts()+ boundAssets, skipped, bindErr := runtime.PrepareMCPServers(assets, runtime.MCPTarget{+ GitToken: gitTok, RequireCredentials: true,+ SSHRepositoriesOnly: len(repositories) > 0 && len(sshRepositoryURLs(repositories)) == len(repositories),+ })for _, warning := range skipped {warnMCPSkipped(warning)}diff --git a/internal/engine/prompt.go b/internal/engine/prompt.goindex bd23b0e6..191974c0 100644--- a/internal/engine/prompt.go+++ b/internal/engine/prompt.go@@ -34,7 +34,11 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, nodeprompt = strings.ReplaceAll(prompt, "{{input}}", run.Input)repository := "未绑定代码仓库"if run.Repository.RepositoryID != "" {- repository = fmt.Sprintf("%s (%s), 最新远端基线 %s, 本次工作分支 %s", run.Repository.Name, run.Repository.GongfengProjectID, run.Repository.BaseBranch, run.Repository.WorkBranch)+ identity := run.Repository.GongfengProjectID+ if run.Repository.Provider == domain.RepositoryProviderSSH {+ identity = "Git SSH"+ }+ repository = fmt.Sprintf("%s (%s), 最新远端基线 %s, 本次工作分支 %s", run.Repository.Name, identity, run.Repository.BaseBranch, run.Repository.WorkBranch)}prompt = strings.ReplaceAll(prompt, "{{repository}}", repository)pipelineURL := "未配置 Pipeline"@@ -42,6 +46,11 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, nodepipelineURL = strings.ReplaceAll(run.Repository.PipelineURLPattern, "{build_id}", "current")}prompt = strings.ReplaceAll(prompt, "{{pipelineUrl}}", pipelineURL)+ if !strings.Contains(prompt, "{{existingMR}}") {+ if hint := sshDeliveryHint(run); hint != "" {+ prompt += "\n\n## Git SSH 仓库交付\n\n" + hint+ }+ }prompt = strings.ReplaceAll(prompt, "{{existingMR}}", existingMRBlurb(st, run))rejectTo := node.RejectToif rejectTo == "" {@@ -99,10 +108,36 @@ func applyPromptPlaceholders(st *repo.Store, wf domain.WorkflowDefinition, nodereturn prompt}+func sshDeliveryHint(run domain.Run) string {+ var sshRepos []string+ for _, repository := range run.RepositoryContexts() {+ if repository.Provider == domain.RepositoryProviderSSH {+ sshRepos = append(sshRepos, repository.Name)+ }+ }+ if len(sshRepos) == 0 {+ return ""+ }+ return "Git SSH 仓库(" + strings.Join(sshRepos, "、") + "):负责交付的节点在用户要求推送时只推本轮工作分支,并报告分支名和提交 SHA。需要 PR/MR 时,可使用另行配置的托管平台 MCP,或请用户到托管平台手动创建。"+}+func existingMRBlurb(st *repo.Store, run domain.Run) string {+ hint := sshDeliveryHint(run)+ if hint == "" {+ return hostedMRBlurb(st, run)+ }+ for _, repository := range run.RepositoryContexts() {+ if repository.Provider != domain.RepositoryProviderSSH {+ return hint + "\n其它仓库:" + hostedMRBlurb(st, run)+ }+ }+ return hint+}++func hostedMRBlurb(st *repo.Store, run domain.Run) string {var continued []stringfor _, repository := range run.RepositoryContexts() {- if repository.RequireExistingWorkBranch {+ if repository.Provider != domain.RepositoryProviderSSH && repository.RequireExistingWorkBranch {continued = append(continued, fmt.Sprintf("%s:继续已有分支 %s,MR 目标主分支 %s", repository.Name, repository.WorkBranch, repositoryBaseBranch(repository)))}}diff --git a/internal/engine/repository_workspace.go b/internal/engine/repository_workspace.goindex 4f0147c4..913d4691 100644--- a/internal/engine/repository_workspace.go+++ b/internal/engine/repository_workspace.go@@ -95,6 +95,7 @@ func prepareRepository(ctx context.Context, workspace string, repository domain.if repository.RepositoryID == "" {return nil}+ ctx = withRepositoryGit(ctx, repository)if repository.RequireExistingWorkBranch && !existingDevelopmentBranch(repository) {return fmt.Errorf("continuing an existing branch requires a development branch distinct from the main and integration branches")}@@ -181,7 +182,7 @@ func prepareRepository(ctx context.Context, workspace string, repository domain.}// Clone into the existing directory (`.`) so git cannot unlink and// recreate `workspace`. That inode is the Docker bind-mount source.- args = append(args, "--", gitwork.RewriteRemoteForToken(remote, gitTokenFrom(ctx)), ".")+ args = append(args, "--", cloneRemoteForGit(ctx, remote), ".")if _, err := gitwork.Watch(ctx, workspace, watch, args...); err != nil {return fmt.Errorf("git clone: %w", err)}@@ -203,11 +204,17 @@ func prepareRepository(ctx context.Context, workspace string, repository domain.if procwatch.Stopped(err) || ctx.Err() != nil {return err}+ if gitwork.UsesSSH(ctx) && !localIsGit {+ return err+ }if clearErr := reset(workspace); clearErr != nil {return clearErr}if retryErr := clone(baseBranch, false); retryErr != nil {- if seeded, seedErr := seedEmptyRepository(ctx, workspace, gitwork.RewriteRemoteForToken(remote, gitTokenFrom(ctx)), repository.DefaultBranch, baseBranch, reset); seeded {+ if gitwork.UsesSSH(ctx) {+ return retryErr // An SSH checkout never initializes a remote branch.+ }+ if seeded, seedErr := seedEmptyRepository(ctx, workspace, cloneRemoteForGit(ctx, remote), repository.DefaultBranch, baseBranch, reset); seeded {if seedErr != nil {return seedErr}@@ -386,7 +393,9 @@ func resumeRepository(ctx context.Context, workspace string, repository domain.R}if _, err := gitC(ctx, workspace, "remote", "get-url", "origin"); err == nil {if _, err := gitC(ctx, workspace, "fetch", "--prune", "origin", baseBranch); err != nil {- _, _ = gitC(ctx, workspace, "fetch", "--prune", "origin")+ if _, fallbackErr := gitC(ctx, workspace, "fetch", "--prune", "origin"); fallbackErr != nil && gitwork.UsesSSH(ctx) {+ return fmt.Errorf("git fetch: %w", fallbackErr)+ }}if repository.WorkBranch != "" {if err := fetchRepositoryWorkBranch(ctx, workspace, repository); err != nil {diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.goindex de10891d..d2faf2a5 100644--- a/internal/engine/run_environment.go+++ b/internal/engine/run_environment.go@@ -224,6 +224,7 @@ func (e *Engine) resolveRunCredentials(run domain.Run) runtime.RunCredentials {CodeBuddy: resolveCodeBuddyCredential(e.repo, userID),GitToken: resolveGitToken(e.repo, userID),}+ credentials.GitSSHKeys = e.repo.GitSSHKeysForRemotes(userID, sshRepositoryURLs(run.RepositoryContexts()))identity := resolveGitIdentity(e.repo, userID)credentials.GitUserName = identity.namecredentials.GitUserEmail = identity.emaildiff --git a/internal/engine/runner_align.go b/internal/engine/runner_align.goindex 9593feab..8b203b7a 100644--- a/internal/engine/runner_align.go+++ b/internal/engine/runner_align.go@@ -9,6 +9,7 @@ import ("time""agentflow/internal/domain"+ "agentflow/internal/gitwork")const alignTaskTimeout = 15 * time.Minute@@ -17,12 +18,31 @@ const alignTaskTimeout = 15 * time.Minute// branch. With a cloud runner pool it runs on a pool runner; otherwise, and// for repositories only reachable through a local path, on this host.func (e *Engine) AlignBaseline(repository domain.RepositoryContext, gitToken string) error {+ return e.alignBaseline(repository, gitToken, 0)+}++func (e *Engine) AlignBaselineForUser(repository domain.RepositoryContext, userID int64) error {+ return e.alignBaseline(repository, resolveGitToken(e.repo, userID), userID)+}++func (e *Engine) alignBaseline(repository domain.RepositoryContext, gitToken string, userID int64) error {if !ShouldAlignIntegrate(repository) {return nil}runner, ok := e.alignRunner(repository)+ ssh := repository.Provider == domain.RepositoryProviderSSH+ if ssh {+ gitToken = ""+ }if !ok {- return AlignIntegrateBaseline(repository, gitToken, e.repo)+ ctx := context.Background()+ if ssh {+ ctx = gitwork.WithSSHKeys(ctx, e.repo.GitSSHKeysForRemotes(userID, []string{repository.CloneURL}))+ }+ return alignIntegrateBaseline(ctx, repository, gitToken, e.repo)+ }+ if err := e.requireWorkBranchCapabilities(runner.ID, []domain.RepositoryContext{repository}); err != nil {+ return err}unlock, err := lockIntegration(e.repo, repository.RepositoryID)if err != nil {@@ -44,10 +64,14 @@ func (e *Engine) AlignBaseline(repository domain.RepositoryContext, gitToken strName: repository.Name,CloneURL: repository.CloneURL,GitToken: gitToken,+ UseSSH: ssh,IntegrateBranch: integrate,DefaultBranch: strings.TrimSpace(repository.DefaultBranch),}}},}+ if ssh {+ task.Invocation.GitSSHUserID = userID+ }if err := e.repo.PutRunnerTask(task); err != nil {return err}diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.goindex af1a864c..a1e6b4f6 100644--- a/internal/engine/runner_dispatch.go+++ b/internal/engine/runner_dispatch.go@@ -122,6 +122,12 @@ func (e *Engine) requireWorkBranchCapabilities(runnerID string, repositories []dreturn nil}for _, repository := range repositories {+ if repository.Provider == domain.RepositoryProviderSSH {+ runner, ok := e.repo.Runner(runnerID)+ if !ok || !runner.SupportsGitSSH() {+ return fmt.Errorf("Git SSH 仓库需要执行机器升级至 %s 或更新版本,请先更新 Runner", domain.RunnerVersionGitSSH)+ }+ }if repository.CreateNewWorkBranch {runner, ok := e.repo.Runner(runnerID)if !ok || !runner.SupportsCreateNewWorkBranch() {@@ -340,6 +346,7 @@ func bindRunnerRepositories(invocation *domain.RunnerInvocation, run domain.Run,RequireExistingWorkBranch: run.Repository.RequireExistingWorkBranch,CreateNewWorkBranch: run.Repository.CreateNewWorkBranch,GitToken: gitToken,+ UseSSH: run.Repository.Provider == domain.RepositoryProviderSSH,}}for _, rc := range run.RepositoryContexts() {@@ -355,9 +362,21 @@ func bindRunnerRepositories(invocation *domain.RunnerInvocation, run domain.Run,RequireExistingWorkBranch: rc.RequireExistingWorkBranch,CreateNewWorkBranch: rc.CreateNewWorkBranch,GitToken: gitToken,+ UseSSH: rc.Provider == domain.RepositoryProviderSSH,Dir: rc.WorkspaceDir,})}+ if len(invocation.GitSSHRemotes()) > 0 {+ invocation.GitSSHUserID = run.ExecutionContext.ResponsibleUserID+ if invocation.Repository != nil && invocation.Repository.UseSSH {+ invocation.Repository.GitToken = ""+ }+ for i := range invocation.Repositories {+ if invocation.Repositories[i].UseSSH {+ invocation.Repositories[i].GitToken = ""+ }+ }+ }}func shellSingleQuote(value string) string {diff --git a/internal/engine/runner_terminal_cases_test.go b/internal/engine/runner_terminal_cases_test.goindex fa3ff8e5..5a5323fd 100644--- a/internal/engine/runner_terminal_cases_test.go+++ b/internal/engine/runner_terminal_cases_test.go@@ -133,16 +133,16 @@ func TestRunnerIntegrateAndConversationTerminalResults(t *testing.T) {headsJSON := `[{"repositoryId":"repo","name":"Repo","workBranch":"work","head":"def"}]`e, _ = cvETerminalEngine(t, domain.RunnerTaskSuccess, headsJSON, "", nil)- heads, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, "token", "User", "[email protected]", "message", "")+ heads, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, 0, "token", "User", "[email protected]", "message", "")if err != nil || len(heads) != 1 {t.Fatalf("heads=%v err=%v", heads, err)}e, _ = cvETerminalEngine(t, domain.RunnerTaskSuccess, "{", "", nil)- if _, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, "", "", "", "message", ""); err == nil || !strings.Contains(err.Error(), "decode") {+ if _, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, 0, "", "", "", "message", ""); err == nil || !strings.Contains(err.Error(), "decode") {t.Fatalf("invalid push result err=%v", err)}e, _ = cvETerminalEngine(t, domain.RunnerTaskFailed, "", "", nil)- if _, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, "", "", "", "message", ""); err == nil {+ if _, err := e.pushConversationOnRunner(context.Background(), "runner-terminal", run, []domain.RepositoryContext{rc}, 0, "", "", "", "message", ""); err == nil {t.Fatal("failed push succeeded")}}diff --git a/internal/engine/workspace_checkpoint_transport.go b/internal/engine/workspace_checkpoint_transport.goindex 0606beb5..92f6287b 100644--- a/internal/engine/workspace_checkpoint_transport.go+++ b/internal/engine/workspace_checkpoint_transport.go@@ -218,7 +218,7 @@ func (e *Engine) HandleWorkspaceCheckpoint(w http.ResponseWriter, r *http.Requesresult.Payload = json.RawMessage(`{"ok":true}`)break}- value, err := e.HandlePreparedWorkspaceTerminal(r.Context(), run.ID, &e.workspaceTerminals, scope, *request.Terminal)+ value, err := e.HandlePreparedWorkspaceTerminal(r.Context(), run.ID, &e.workspaceTerminals, scope, *request.Terminal, request.TerminalOwner)result.Payload, _ = json.Marshal(value)if err != nil {result.Error = err.Error()diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.goindex 9e12310b..d23bfd44 100644--- a/internal/engine/workspace_preparation.go+++ b/internal/engine/workspace_preparation.go@@ -94,7 +94,8 @@ func (e *Engine) prepareLocalEnvironment(ctx context.Context, run domain.Run, en}func (e *Engine) preparedWorkspaceRequest(run domain.Run, request domain.RunnerWorkspaceRequest) (domain.RunnerWorkspaceRequest, error) {- if runnerID := e.defaultExecutionRunner(run); runnerID != "" {+ runnerID := e.defaultExecutionRunner(run)+ if runnerID != "" {if run.ExecutionContext.RunnerWorkspaceLayout != domain.RunnerWorkspaceLayoutShared && len(runtime.PreparationNodes(runtime.WorkspacePreparationWorkflow(run.WorkflowSnapshot))) > 0 {return request, fmt.Errorf("此历史运行使用逐节点工作区,不能自动重建共享环境;请重新发起一次运行")}@@ -138,10 +139,24 @@ func (e *Engine) preparedWorkspaceRequest(run domain.Run, request domain.RunnerWcredentials := e.resolveRunCredentials(run)invocation := &domain.RunnerInvocation{}bindRunnerRepositories(invocation, run, credentials.GitToken, credentials.GitUserName, credentials.GitUserEmail)+ invocation.GitSSHUserID = 0assets := e.resolveScriptMCPAssets(run.ExecutionContext.ProjectID, run.ExecutionContext.ResponsibleUserID)invocation.Assets = assetsinvocation.MCPCallServers = assets.MCPServersrequest.PreparationInvocation = invocation+ // Status and terminal I/O don't need keys. A separate platform instance+ // can also resolve its own credentials from the shared store.+ request.TerminalGitSSHKeys = nil+ terminalOpen := request.Operation == domain.RunnerWorkspaceOperationTerminal && request.Terminal != nil && request.Terminal.Operation == "open"+ sshRemotes := invocation.GitSSHRemotes()+ if runnerID != "" && len(sshRemotes) > 0 {+ if request.Operation == domain.RunnerWorkspaceOperationPrepare || terminalOpen {+ invocation.GitSSHKeys = credentials.GitSSHKeys+ }+ if terminalOpen {+ request.TerminalGitSSHKeys = e.repo.GitSSHKeysForRemotes(request.TerminalOwner, sshRemotes)+ }+ }request.RunStatus = run.Statusrequest.WorkspaceLayout = run.ExecutionContext.RunnerWorkspaceLayoutreturn request, nil@@ -312,16 +327,16 @@ func (e *Engine) PrepareNodeWorkspace(ctx context.Context, run domain.Run, env *// HandleWorkspaceTerminal uses exactly the same environment and preparation// contract as SOP execution. The pool owns the PTY, the Engine owns the sandbox.-func (e *Engine) HandleWorkspaceTerminal(ctx context.Context, id string, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest) (runtime.TerminalResult, error) {+func (e *Engine) HandleWorkspaceTerminal(ctx context.Context, id string, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest, actorID int64) (runtime.TerminalResult, error) {if req.Operation == "open" {if _, err := e.EnsureWorkspaceReady(ctx, id); err != nil {return runtime.TerminalResult{}, err}}- return e.HandlePreparedWorkspaceTerminal(ctx, id, pool, scope, req)+ return e.HandlePreparedWorkspaceTerminal(ctx, id, pool, scope, req, actorID)}-func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, id string, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest) (runtime.TerminalResult, error) {+func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, id string, pool *runtime.TerminalPool, scope string, req domain.WorkspaceTerminalRequest, actorID int64) (runtime.TerminalResult, error) {if req.Operation != "open" {return pool.HandleSandbox(ctx, nil, scope, req, nil)}@@ -337,6 +352,14 @@ func (e *Engine) HandlePreparedWorkspaceTerminal(ctx context.Context, id string,if err != nil || state.Status != "ready" || state.Environment != epoch {return runtime.TerminalResult{}, fmt.Errorf("工作区执行环境已变化,请重新准备后打开终端")}+ sshKeys := env.credentialSnapshot().GitSSHKeys+ if len(sshKeys) > 0 {+ remotes := make([]string, 0, len(sshKeys))+ for remote := range sshKeys {+ remotes = append(remotes, remote)+ }+ return pool.HandleSandboxWithGitSSH(ctx, env.sandbox, scope, req, nil, e.repo.GitSSHKeysForRemotes(actorID, remotes))+ }return pool.HandleSandbox(ctx, env.sandbox, scope, req, nil)}diff --git a/internal/gitwork/git.go b/internal/gitwork/git.goindex 3b7985ad..f47bd921 100644--- a/internal/gitwork/git.go+++ b/internal/gitwork/git.go@@ -3,6 +3,7 @@ package gitworkimport ("context""fmt"+ "os""os/exec""path/filepath""strings"@@ -14,7 +15,12 @@ import (// Env. Output is trimmed and redacted; on failure it is part of the error.func Run(ctx context.Context, workspace string, args ...string) (string, error) {token := TokenFrom(ctx)- out, err := command(ctx, workspace, token, args).CombinedOutput()+ sshEnv, cleanup, err := sshCommandEnvironment(ctx, args)+ if err != nil {+ return "", err+ }+ defer cleanup()+ out, err := command(ctx, workspace, token, sshEnv, args).CombinedOutput()text := Redact(strings.TrimSpace(string(out)), token)if err != nil {if text != "" {@@ -37,19 +43,38 @@ const (// is killed, and the error carries only the last lines of output.func Watch(ctx context.Context, workspace string, opts procwatch.Options, args ...string) (string, error) {token := TokenFrom(ctx)+ sshEnv, cleanup, err := sshCommandEnvironment(ctx, args)+ if err != nil {+ return "", err+ }+ defer cleanup()opts.Redact = func(line string) string { return Redact(line, token) }- text, err := procwatch.Run(ctx, func(ctx context.Context) *exec.Cmd { return command(ctx, workspace, token, args) }, opts)+ text, err := procwatch.Run(ctx, func(ctx context.Context) *exec.Cmd { return command(ctx, workspace, token, sshEnv, args) }, opts)if err != nil && text != "" {return text, fmt.Errorf("%w: %s", err, text)}return text, err}-func command(ctx context.Context, workspace, token string, args []string) *exec.Cmd {+func command(ctx context.Context, workspace, token string, sshEnv map[string]string, args []string) *exec.Cmd {dir := CommandDir(workspace)+ if len(sshEnv) > 0 {+ token = ""+ }cmd := exec.CommandContext(ctx, "git", append(AuthConfigArgs(token), args...)...)cmd.Dir = dircmd.Env = WithEnvValue(Env(token), "PWD", dir)+ if len(sshEnv) > 0 {+ // Do not let URL rewrites switch a managed SSH operation to another+ // transport. SSH itself only connects to the requested pinned host.+ cmd.Env = WithEnvValue(cmd.Env, "GIT_ALLOW_PROTOCOL", "ssh")+ cmd.Env = WithEnvValue(cmd.Env, "GIT_CONFIG_GLOBAL", os.DevNull)+ cmd.Env = WithEnvValue(cmd.Env, "GIT_CONFIG_NOSYSTEM", "1")+ cmd.Env = WithEnvValue(cmd.Env, "GIT_CONFIG_PARAMETERS", "")+ for k, v := range sshEnv {+ cmd.Env = WithEnvValue(cmd.Env, k, v)+ }+ }// A run without a checkout must not discover the platform's own .git// when the operator keeps workspaces below a source checkout.if absolute, err := filepath.Abs(dir); err == nil {diff --git a/internal/gitwork/ssh.go b/internal/gitwork/ssh.gonew file mode 100644index 00000000..97c28a36--- /dev/null+++ b/internal/gitwork/ssh.go@@ -0,0 +1,314 @@+package gitwork++import (+ "bytes"+ "context"+ "crypto/sha256"+ "errors"+ "fmt"+ "net"+ "os"+ "path/filepath"+ "sort"+ "strconv"+ "strings"+ "sync"++ "golang.org/x/crypto/ssh"+ "golang.org/x/crypto/ssh/agent"+ "golang.org/x/crypto/ssh/knownhosts"+)++const SSHKnownHostsEnv = "AGENTFLOW_GIT_SSH_KNOWN_HOSTS"++const SSHKeyHint = "请到「个人配置 → Git SSH 密钥」为该 SSH 主机添加私钥,并在代码托管平台为对应公钥授予仓库权限"++var ErrSSHKeyRequired = errors.New("未配置 Git SSH 密钥。" + SSHKeyHint)++func NormalizeSSHPrivateKey(value string) (string, error) {+ value = strings.ReplaceAll(strings.TrimSpace(value), "\r\n", "\n") + "\n"+ if len(value) > 16<<10 {+ return "", errors.New("Git SSH 私钥不能超过 16 KiB")+ }+ if _, _, err := parseSSHIdentity(value); err != nil {+ return "", err+ }+ return value, nil+}++func parseSSHIdentity(value string) (any, ssh.Signer, error) {+ if strings.TrimSpace(value) == "" {+ return nil, nil, ErrSSHKeyRequired+ }+ key, err := ssh.ParseRawPrivateKey([]byte(value))+ var passphrase *ssh.PassphraseMissingError+ if errors.As(err, &passphrase) {+ return nil, nil, errors.New("Git SSH 密钥需要口令,无法用于无人值守;请使用单独生成的无口令部署密钥")+ }+ if err == nil {+ if signer, err := ssh.NewSignerFromKey(key); err == nil {+ return key, signer, nil+ }+ }+ return nil, nil, errors.New("Git SSH 私钥格式无效,请粘贴完整的 OpenSSH 或 PEM 私钥")+}++func sshHostKeys(remotes []SSHRemote) ([]byte, error) {+ path := strings.TrimSpace(os.Getenv(SSHKnownHostsEnv))+ if path == "" {+ return nil, fmt.Errorf("Git SSH 尚未启用,请管理员配置 %s", SSHKnownHostsEnv)+ }+ content, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("无法读取 %s 指定的主机密钥文件", SSHKnownHostsEnv)+ }+ allowed := make(map[string]bool, len(remotes))+ for _, remote := range remotes {+ allowed[knownhosts.Normalize(net.JoinHostPort(remote.Host, remote.Port))] = false+ }+ var pinned bytes.Buffer+ for _, line := range bytes.Split(content, []byte("\n")) {+ marker, hosts, key, _, _, err := ssh.ParseKnownHosts(line)+ if err != nil || (marker != "" && marker != "revoked" && marker != "cert-authority") {+ continue+ }+ for _, host := range hosts {+ host = strings.ToLower(host)+ if _, ok := allowed[host]; !ok {+ continue+ }+ if marker != "" {+ fmt.Fprintf(&pinned, "@%s ", marker)+ }+ fmt.Fprintf(&pinned, "%s %s", host, ssh.MarshalAuthorizedKey(key))+ if marker != "revoked" {+ allowed[host] = true+ }+ }+ }+ for _, remote := range remotes {+ if endpoint := knownhosts.Normalize(net.JoinHostPort(remote.Host, remote.Port)); !allowed[endpoint] {+ return nil, fmt.Errorf("SSH 主机 %s 未获信任,请管理员在 %s 中添加并核对该主机和端口的公钥", endpoint, SSHKnownHostsEnv)+ }+ }+ return pinned.Bytes(), nil+}++// StartSSH adds one Git URL rewrite and one OpenSSH identity per repository.+// Aliases bind each repository to its selected host key.+// The filesystem contains a socket and public data only. clientRoot is the+// mount path corresponding to root for a client in a container.+func StartSSH(environment map[string]string, keys map[string]string, root, clientRoot string) (func(), error) {+ if len(keys) == 0 {+ return func() {}, nil+ }+ type binding struct {+ remote SSHRemote+ alias string+ key string+ }+ urls := make([]string, 0, len(keys))+ for raw := range keys {+ urls = append(urls, raw)+ }+ sort.Strings(urls)+ var bindings []binding+ var remotes []SSHRemote+ configCount, _ := strconv.Atoi(environment["GIT_CONFIG_COUNT"])+ for _, raw := range urls {+ remote, err := ParseSSHRemote(raw)+ if err != nil {+ return nil, err+ }+ destination := raw+ if key := keys[raw]; key != "" {+ sum := sha256.Sum256([]byte(remote.URL))+ alias := fmt.Sprintf("lf-%x", sum[:16])+ destination = remote.aliasURL(alias)+ bindings = append(bindings, binding{remote: remote, alias: alias, key: key})+ remotes = append(remotes, remote)+ }+ // The exact URL takes priority over the legacy host-wide HTTPS+ // rewrite, including when this repository has no assigned key.+ suffix := strconv.Itoa(configCount)+ environment["GIT_CONFIG_KEY_"+suffix] = "url." + destination + ".insteadOf"+ environment["GIT_CONFIG_VALUE_"+suffix] = raw+ configCount+++ }+ environment["GIT_CONFIG_COUNT"] = strconv.Itoa(configCount)+ environment["GIT_SSH_VARIANT"] = "ssh"+ if len(bindings) == 0 {+ // Keep terminals usable for editing without using a host identity.+ environment["GIT_SSH_COMMAND"] = `sh -c 'echo "未配置 Git SSH 密钥,请在个人配置中添加" >&2; exit 1' --`+ return func() {}, nil+ }+ pinned, err := sshHostKeys(remotes)+ if err != nil {+ return nil, err+ }+ keyring := agent.NewKeyring()+ publicKeys := make(map[string][]byte)+ var config strings.Builder+ for _, item := range bindings {+ r := item.remote+ keyFile, loaded := publicKeys[item.key]+ if !loaded {+ key, signer, err := parseSSHIdentity(item.key)+ if err != nil {+ return nil, err+ }+ if err := keyring.Add(agent.AddedKey{PrivateKey: key}); err != nil {+ return nil, errors.New("无法将 Git SSH 密钥加载到临时代理")+ }+ keyFile = ssh.MarshalAuthorizedKey(signer.PublicKey())+ publicKeys[item.key] = keyFile+ }+ // Only the numeric port is expanded by Match exec. The host key is+ // checked against the real endpoint, including a custom port.+ fmt.Fprintf(&config, "Match originalhost %s exec \"test %%p = %s\"\n HostName %s\n HostKeyAlias %s\n ProxyCommand none\n IdentityAgent ./agent\n IdentityFile ./%s.pub\n UserKnownHostsFile ./known_hosts\n",+ item.alias, r.Port, r.Host, knownhosts.Normalize(r.Endpoint()), item.alias)+ }+ config.WriteString(`Host *+ ProxyCommand /bin/false+ IdentityAgent none+ UserKnownHostsFile /dev/null+ GlobalKnownHostsFile /dev/null+ StrictHostKeyChecking yes+ CheckHostIP no+ UpdateHostKeys no+ BatchMode yes+ PreferredAuthentications publickey+ IdentitiesOnly yes+ ForwardAgent no+ ClearAllForwardings yes+ ControlMaster no+ ConnectTimeout 15+`)+ dir, err := os.MkdirTemp(root, "lf-ssh-")+ if err != nil {+ return nil, fmt.Errorf("create Git SSH session: %w", err)+ }+ files := map[string][]byte{"config": []byte(config.String()), "known_hosts": pinned}+ for _, item := range bindings {+ files[item.alias+".pub"] = publicKeys[item.key]+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(dir, name), content, 0o600); err != nil {+ _ = os.RemoveAll(dir)+ return nil, fmt.Errorf("write Git SSH session configuration: %w", err)+ }+ }+ listener, err := listenSSHAgent(dir)+ if err != nil {+ _ = os.RemoveAll(dir)+ return nil, fmt.Errorf("start Git SSH agent: %w", err)+ }+ stop := serveSSHAgent(listener, keyring)+ clientDir := dir+ if clientRoot != "" {+ clientDir = filepath.Join(clientRoot, filepath.Base(dir))+ }+ environment["GIT_SSH_COMMAND"] = "cd " + shellQuote(clientDir) + " && exec ssh -F ./config"+ return sync.OnceFunc(func() {+ stop()+ _ = os.RemoveAll(dir)+ }), nil+}++func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'" }++func listenSSHAgent(dir string) (net.Listener, error) {+ path := filepath.Join(dir, "agent")+ if len(path) < 100 {+ return net.Listen("unix", path)+ }+ // Unix socket addresses have a small fixed length. Bind through a short+ // alias; the socket itself remains in the workspace's private directory.+ alias, err := os.MkdirTemp("/tmp", "lf-ssh-")+ if err != nil {+ return nil, err+ }+ defer os.RemoveAll(alias)+ if err := os.Symlink(dir, filepath.Join(alias, "d")); err != nil {+ return nil, err+ }+ return net.Listen("unix", filepath.Join(alias, "d", "agent"))+}++func serveSSHAgent(listener net.Listener, keyring agent.Agent) func() {+ var mu sync.Mutex+ clients := map[net.Conn]bool{}+ closed := false+ go func() {+ for {+ conn, err := listener.Accept()+ if err != nil {+ return+ }+ mu.Lock()+ if closed {+ mu.Unlock()+ _ = conn.Close()+ return+ }+ clients[conn] = true+ mu.Unlock()+ go func() {+ _ = agent.ServeAgent(keyring, conn)+ _ = conn.Close()+ mu.Lock()+ delete(clients, conn)+ mu.Unlock()+ }()+ }+ }()+ return func() {+ _ = listener.Close()+ mu.Lock()+ defer mu.Unlock()+ closed = true+ for conn := range clients {+ _ = conn.Close()+ }+ _ = keyring.RemoveAll()+ }+}++type sshKeysContext struct{}+type sshRemoteContext struct{}++func WithSSHKeys(ctx context.Context, keys map[string]string) context.Context {+ return context.WithValue(ctx, sshKeysContext{}, keys)+}++func WithSSHRemote(ctx context.Context, remote string) context.Context {+ return context.WithValue(ctx, sshRemoteContext{}, remote)+}++func UsesSSH(ctx context.Context) bool {+ remote, _ := ctx.Value(sshRemoteContext{}).(string)+ return remote != ""+}++func sshCommandEnvironment(ctx context.Context, args []string) (map[string]string, func(), error) {+ remote, _ := ctx.Value(sshRemoteContext{}).(string)+ if remote == "" {+ return nil, func() {}, nil+ }+ if len(args) >= 2 && args[0] == "-C" {+ args = args[2:]+ }+ if len(args) > 0 {+ switch args[0] {+ case "clone", "fetch", "pull", "push", "ls-remote":+ keys, _ := ctx.Value(sshKeysContext{}).(map[string]string)+ if keys[remote] == "" {+ return nil, nil, fmt.Errorf("%s: %w", remote, ErrSSHKeyRequired)+ }+ env := make(map[string]string)+ cleanup, err := StartSSH(env, map[string]string{remote: keys[remote]}, "", "")+ return env, cleanup, err+ }+ }+ return nil, func() {}, nil+}diff --git a/internal/gitwork/ssh_remote.go b/internal/gitwork/ssh_remote.gonew file mode 100644index 00000000..e51736ed--- /dev/null+++ b/internal/gitwork/ssh_remote.go@@ -0,0 +1,131 @@+package gitwork++import (+ "fmt"+ "net"+ "net/netip"+ "net/url"+ "regexp"+ "strconv"+ "strings"+)++type SSHRemote struct {+ URL, User, Host, Path string+ Port string+}++func (r SSHRemote) Endpoint() string { return net.JoinHostPort(r.Host, r.Port) }++func (r SSHRemote) aliasURL(alias string) string {+ if strings.HasPrefix(r.URL, "ssh://") {+ return "ssh://" + r.User + "@" + net.JoinHostPort(alias, r.Port) + r.Path+ }+ return r.User + "@" + alias + ":" + r.Path+}++// SSHHostScope normalizes a hostname with an optional port, or an SSH URL.+func SSHHostScope(raw string) (string, error) {+ if remote, err := ParseSSHRemote(raw); err == nil {+ return remote.Endpoint(), nil+ }+ address := strings.TrimSpace(raw)+ if ip, err := netip.ParseAddr(address); err == nil && ip.Zone() == "" {+ return net.JoinHostPort(ip.String(), "22"), nil+ }+ if !strings.ContainsAny(address, "/@") {+ if remote, err := ParseSSHRemote("ssh://git@" + address + "/repo"); err == nil {+ return remote.Endpoint(), nil+ }+ }+ return "", fmt.Errorf("请输入 SSH 主机名,可附带端口,例如 gitlab.com 或 git.example.org:2222")+}++var (+ sshUser = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9_.-]*$`)+ sshHost = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9.-]*$`)+ sshPath = regexp.MustCompile(`^[A-Za-z0-9_.~/-]+$`)+ sshSCP = regexp.MustCompile(`^([^@]+)@(\[[^\]]+\]|[^:/]+):(.+)$`)+)++// IsSSHReference distinguishes an explicit SSH clone address from a web or+// legacy project link, including malformed addresses that must be rejected.+func IsSSHReference(raw string) bool {+ s := trimCloneReference(raw)+ lower := strings.ToLower(s)+ if scheme, _, ok := strings.Cut(lower, "://"); ok {+ return scheme == "ssh" || scheme == "git+ssh" || scheme == "ssh+git"+ }+ if i := strings.Index(s, "::"); i >= 0 && isTransportName(s[:i]) {+ return false+ }+ _, scp := scpHost(s)+ return scp+}++func trimCloneReference(raw string) string {+ s := strings.Trim(strings.TrimSpace(raw), `"'`)+ return strings.Trim(strings.TrimSpace(strings.TrimPrefix(s, "git clone ")), `"'`)+}++// ParseSSHRemote accepts a Git SSH URL or an scp-style clone address, without+// credentials, shell metacharacters or implicit use of the host account.+func ParseSSHRemote(raw string) (SSHRemote, error) {+ s := trimCloneReference(raw)+ invalid := fmt.Errorf("请使用 Git SSH 地址,例如 [email protected]:group/repo.git 或 ssh://[email protected]:2222/group/repo.git")+ if len(s) > 2048 || strings.ContainsAny(s, " \t\r\n%?#\\") {+ return SSHRemote{}, invalid+ }+ var user, host, path string+ port := "22"+ if strings.HasPrefix(s, "ssh://") {+ u, err := url.Parse(s)+ if err != nil || u.User == nil || strings.HasSuffix(u.Host, ":") {+ return SSHRemote{}, invalid+ }+ if _, hasPassword := u.User.Password(); hasPassword {+ return SSHRemote{}, invalid+ }+ user, host, path = u.User.Username(), u.Hostname(), u.Path+ if u.Port() != "" {+ p, err := strconv.Atoi(u.Port())+ if err != nil || p < 1 || p > 65535 {+ return SSHRemote{}, invalid+ }+ port = strconv.Itoa(p)+ }+ } else if m := sshSCP.FindStringSubmatch(s); m != nil {+ user, host, path = m[1], strings.Trim(m[2], "[]"), m[3]+ } else {+ return SSHRemote{}, invalid+ }+ host = strings.ToLower(host)+ if ip, err := netip.ParseAddr(host); err == nil {+ host = ip.String()+ } else if !sshHost.MatchString(host) || strings.Contains(host, "..") {+ return SSHRemote{}, invalid+ }+ if !sshUser.MatchString(user) || !sshPath.MatchString(path) {+ return SSHRemote{}, invalid+ }+ for _, part := range strings.Split(strings.TrimPrefix(path, "/"), "/") {+ if part == "" || part == "." || part == ".." {+ return SSHRemote{}, invalid+ }+ }+ if strings.TrimSuffix(path[strings.LastIndex(path, "/")+1:], ".git") == "" {+ return SSHRemote{}, invalid+ }+ // Preserve the distinction between an absolute SSH URL and a path+ // relative to the account's home directory (scp form).+ if strings.HasPrefix(s, "ssh://") {+ s = "ssh://" + user + "@" + net.JoinHostPort(host, port) + path+ } else {+ hostPart := host+ if strings.Contains(host, ":") {+ hostPart = "[" + host + "]"+ }+ s = user + "@" + hostPart + ":" + path+ }+ return SSHRemote{URL: s, User: user, Host: host, Path: path, Port: port}, nil+}diff --git a/internal/httpapi/assistant_run_view.go b/internal/httpapi/assistant_run_view.goindex 1a411569..c36e650b 100644--- a/internal/httpapi/assistant_run_view.go+++ b/internal/httpapi/assistant_run_view.go@@ -117,6 +117,11 @@ var assistantCredentialRules = []struct {"到 LoopForge「个人配置 → CodeBuddy API Key」选择同一网络环境,粘贴 Key 并保存;DeepSeek、OpenAI 等第三方模型的 Key 不能用作 CodeBuddy Key","回到运行重试失败节点",}},+ {"gitSshKey", "Git SSH 密钥", regexp.MustCompile(`Git SSH (密钥|私钥)`), "", []string{+ "把公钥添加到代码托管账号,并按需授予仓库写权限",+ "到 LoopForge「个人配置 → Git SSH 密钥」为该主机添加无口令私钥,同一主机的仓库自动共用",+ "请管理员信任仓库的 SSH 主机,然后重试",+ }},{"gitToken", "GitHub Git Token", regexp.MustCompile(`(?i)Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]`), "https://github.com/settings/tokens", []string{"打开 GitHub「Settings → Developer settings → Personal access tokens」新建令牌","为目标仓库授予 Contents 和 Pull requests 的读写权限,创建后立即复制 token",diff --git a/internal/httpapi/assistant_workspace_mr.go b/internal/httpapi/assistant_workspace_mr.goindex b390e639..82e7e4ff 100644--- a/internal/httpapi/assistant_workspace_mr.go+++ b/internal/httpapi/assistant_workspace_mr.go@@ -11,6 +11,7 @@ import ("net/http""net/url""regexp"+ "slices""strings""time"@@ -21,8 +22,8 @@ import (// workbench_workspace_submit_mr delivers a conversation workspace without// an SOP delivery node: it commits and pushes the work branch, then opens a// GitHub pull request (or a merge request on the optional legacy Gongfeng-// host). Both use the requesting user's own Git Token, so the push and the-// request are attributed to them and limited by their repository permissions.+// host). SSH repositories use the requesting user's Git SSH key and return+// the branch and commit without calling a hosting API.// SOP runs keep delivering through nodes.const gongfengWebBase = "https://git.example.com"@@ -39,27 +40,29 @@ var ()type workspaceMRResult struct {- Repository string `json:"repository"`- SourceBranch string `json:"sourceBranch"`- TargetBranch string `json:"targetBranch"`- BaseBranch string `json:"baseBranch,omitempty"`- Warning string `json:"warning,omitempty"`- Commit string `json:"commit,omitempty"`- Pushed bool `json:"pushed"`- Direct bool `json:"direct,omitempty"`- MRURL string `json:"mrUrl,omitempty"`- MRIID int64 `json:"mrIid,omitempty"`- Existing bool `json:"existing,omitempty"`- Updated bool `json:"updated,omitempty"`- UpdateError string `json:"updateError,omitempty"`- CreateURL string `json:"createUrl,omitempty"`- Error string `json:"error,omitempty"`+ Repository string `json:"repository"`+ SourceBranch string `json:"sourceBranch"`+ TargetBranch string `json:"targetBranch"`+ BaseBranch string `json:"baseBranch,omitempty"`+ Warning string `json:"warning,omitempty"`+ Commit string `json:"commit,omitempty"`+ Pushed bool `json:"pushed"`+ Direct bool `json:"direct,omitempty"`+ PushOnly bool `json:"pushOnly,omitempty"`+ RepositoryURL string `json:"repositoryUrl,omitempty"`+ MRURL string `json:"mrUrl,omitempty"`+ MRIID int64 `json:"mrIid,omitempty"`+ Existing bool `json:"existing,omitempty"`+ Updated bool `json:"updated,omitempty"`+ UpdateError string `json:"updateError,omitempty"`+ CreateURL string `json:"createUrl,omitempty"`+ Error string `json:"error,omitempty"`}func workspaceSubmitMRDescriptor() agentToolDescriptor {return agentToolDescriptor{Name: "workbench_workspace_submit_mr",- Description: "把当前工作区(任务,或本对话打开的临时工作区)的改动提交到工作分支、用请求人自己的 Git Token 推送,并发起 Pull Request(GitHub 仓库)或 MR(工蜂仓库),返回链接 mrUrl。调用前先用 workbench_workspace_command 跑通相关测试。title 写清改了什么;description 用 Markdown 写改动摘要和验证结果。工作分支已有打开的 PR/MR 时会推送新提交,并用本次 title、description 更新它,所以 description 要概括整个 PR/MR 的改动,不只是这次的增量。targetBranch 默认是工作区打开时的 baseBranch(工作分支的起点);打向别的分支时 PR/MR 会带上两个分支之间的差异提交,结果里会给出 warning,要打 release 这类分支应在 workbench_workspace_open 时就传 baseBranch。只提交工作区记录的工作分支:手工 git checkout 到别的分支时会拒绝提交并说明原因;只读检出(branchMode=readonly)的仓库不会提交。默认 mode=mr;用户要把改动合并进 preview/test 这类共享分支并直接推送、不要 PR/MR(例如「先合到 preview 再推」「本地合并然后推送」)时传 mode=direct,它把工作分支 merge --no-ff 进 targetBranch 并直推(目标必须已在远端存在、且不是可写仓库的基线分支);直推不产生 PR/MR。",+ Description: "提交并推送当前工作区的工作分支。GitHub / 工蜂使用请求人的 Git Token 发起或更新 PR/MR,返回 mrUrl;Git SSH 仓库使用请求人的 SSH 密钥推送,返回 sourceBranch 和 commit。调用前先用 workbench_workspace_command 验证。title 写改动标题;description 用 Markdown 概括整个交付的改动和验证结果。targetBranch 默认是工作分支的起点 baseBranch;不同则会给出 warning。只读仓库不会提交,手工切换到其它分支时会拒绝提交。默认 mode=mr;用户明确要合并到 preview/test 等已有共享分支时传 mode=direct 和 targetBranch,直接推送合并结果(目标不能是基线分支)。",InputSchema: json.RawMessage(`{"type":"object","properties":{"title":{"type":"string","minLength":1,"maxLength":200},"description":{"type":"string","maxLength":20000},"targetBranch":{"type":"string","maxLength":200,"description":"PR/MR 的目标分支,默认是工作区打开时的 baseBranch;与起点不同时结果带 warning。mode=direct 时必填,写要直推的共享分支"},"mode":{"type":"string","enum":["mr","direct"],"description":"mr(默认)推工作分支并发起或更新 PR/MR;direct 把工作分支 merge --no-ff 进 targetBranch 后直推,不发 MR"}},"required":["title"],"additionalProperties":false}`),Kind: "workspace",}@@ -124,7 +127,7 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSe}gitToken := strings.TrimSpace(h.repo.GitCredential(ctx, s.User.ID))_, apiToken := gitwork.SplitToken(gitToken)- if apiToken == "" {+ if apiToken == "" && !slices.ContainsFunc(run.RepositoryContexts(), func(rc domain.RepositoryContext) bool { return rc.Provider == domain.RepositoryProviderSSH }) {return "", fmt.Errorf("你还没有配置 Git Token,无法推送和发起 PR。请到「个人配置 → 个人凭证」配置:打开 https://github.com/settings/tokens 新建令牌,为目标仓库授予 Contents 和 Pull requests 的读写权限,复制后粘贴并点校验")}if h.engine == nil {@@ -154,7 +157,7 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSeif len(run.RepositoryContexts()) == 0 {return "", fmt.Errorf("这个工作区没有检出代码仓库,没有可提交的内容")}- heads, err := h.engine.PushConversationWorkspace(ctx, run.ID, gitToken, login, email, title, directTarget)+ heads, err := h.engine.PushConversationWorkspace(ctx, run.ID, s.User.ID, gitToken, login, email, title, directTarget)if err != nil {return "", errors.New(redactAgentToolResult(err.Error(), requester))}@@ -178,7 +181,7 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSeif result.TargetBranch == "" {result.TargetBranch = base}- if !direct && base != "" && result.TargetBranch != base {+ if !direct && rc.Provider != domain.RepositoryProviderSSH && base != "" && result.TargetBranch != base {result.Warning = fmt.Sprintf("工作分支从 %s 拉出,MR 却打向 %s:%s 有而 %s 没有的提交会一起出现在这个 MR 里。要只带本次改动,用 workbench_workspace_open new + baseBranch=%s 新开工作区,把改动搬过去再提交", base, result.TargetBranch, base, result.TargetBranch, result.TargetBranch)}if direct {@@ -190,6 +193,11 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSeresults = append(results, result)continue}+ if rc.Provider == domain.RepositoryProviderSSH {+ result.PushOnly, result.RepositoryURL = true, rc.WebURL+ results = append(results, result)+ continue+ }if path := githubRepoPath(rc); path != "" {result.CreateURL = githubWebBase + "/" + path + "/compare/" + url.PathEscape(result.TargetBranch) + "..." + url.PathEscape(result.SourceBranch) + "?expand=1"pr, err := createGitHubPR(ctx, apiToken, path, result.SourceBranch, result.TargetBranch, title, body)@@ -227,7 +235,7 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSeif len(results) == 0 {return "", fmt.Errorf("工作区里的仓库都没有相对基线分支的改动,没有可提交的内容")}- note := "PR/MR 已发起,把 mrUrl 发给用户。没有改动的仓库不会发起。"+ note := "把每个仓库的交付结果发给用户。PR/MR 使用 mrUrl。"if direct {note = "已把工作分支直接合并推送到共享分支(没有开 PR/MR):把每个仓库的 targetBranch 和 commit 发给用户,说明共享分支已更新到该提交;直推没有 PR/MR,需求不会自动完成,需要人工确认收尾。"}@@ -237,10 +245,16 @@ func (h *agentToolGateway) workspaceSubmitMR(ctx context.Context, s *AgentToolSe}}for _, r := range results {- if r.MRURL == "" && !r.Direct {+ if r.MRURL == "" && !r.Direct && !r.PushOnly {note = "部分仓库没能自动发起 PR/MR:如实告诉用户 error,并给出 createUrl 让用户手动发起(源分支 sourceBranch、目标分支 targetBranch)。"}}+ for _, r := range results {+ if r.PushOnly {+ note += "Git SSH 仓库已推送工作分支:请告知 sourceBranch 和 commit。有 repositoryUrl 时可到托管平台手动创建 PR/MR,也可使用另行配置的托管平台 MCP。"+ break+ }+ }for _, r := range results {if r.Warning != "" {note += "有仓库的 MR 目标和工作分支起点不同,把 warning 如实告诉用户。"@@ -288,6 +302,9 @@ var githubRepoPathPattern = regexp.MustCompile(`^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+// githubRepoPath returns "owner/name" for github.com repositories and "" for// anything else, so the token is only ever sent to GitHub.func githubRepoPath(rc domain.RepositoryContext) string {+ if rc.Provider == domain.RepositoryProviderSSH {+ return ""+ }path, ok := strings.CutPrefix(strings.TrimSpace(rc.GongfengProjectID), "github:")if !ok {path = hostedRepoPath(rc, "github.com", githubRepoPathPattern)@@ -299,6 +316,9 @@ func githubRepoPath(rc domain.RepositoryContext) string {}func hostedRepoPath(rc domain.RepositoryContext, host string, valid *regexp.Regexp) string {+ if rc.Provider == domain.RepositoryProviderSSH {+ return ""+ }for _, raw := range []string{rc.CloneURL, rc.WebURL} {raw = strings.TrimSpace(raw)path := ""diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.goindex bcca7a9c..99b7ac21 100644--- a/internal/httpapi/catalog.go+++ b/internal/httpapi/catalog.go@@ -107,6 +107,52 @@ func (h *catalogHandlers) repositories(c *gin.Context) {v.LocalPath = existing.LocalPath}}+ primary := strings.TrimSpace(body.RepoURL)+ if primary == "" {+ primary = strings.TrimSpace(body.URL)+ }+ sshReference := primary+ if sshReference == "" {+ sshReference = v.CloneURL+ }+ // GitHub and the optional legacy host keep their existing token flow (and+ // GitHub's automatic pull requests) for SSH-style addresses unless the+ // caller explicitly selects SSH authentication.+ legacySSH := false+ if v.Provider != domain.RepositoryProviderSSH {+ if remote, err := gitwork.ParseSSHRemote(sshReference); err == nil {+ legacySSH = remote.Port == "22" && (remote.Host == domain.GongfengRepoHost || remote.Host == "github.com")+ }+ }+ githubShorthand := primary != "" && strings.HasPrefix(strings.TrimPrefix(primary, "git clone "), "github:")+ if v.Provider == domain.RepositoryProviderSSH || (gitwork.IsSSHReference(sshReference) && !legacySSH && !githubShorthand) {+ remote, err := gitwork.ParseSSHRemote(sshReference)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ // Repository definitions can be saved before SSH is configured. Actual+ // Git operations validate the user's key and the pinned host keys.+ if body.RepoURL != "" && body.URL != "" {+ if other, err := gitwork.ParseSSHRemote(body.URL); err != nil || other.URL != remote.URL {+ c.JSON(http.StatusBadRequest, gin.H{"error": "repoUrl 与 url 指向不同仓库"})+ return+ }+ }+ if !validCLIBaseURL(v.WebURL) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "仓库网页地址必须是无凭据的 HTTP(S) 地址"})+ return+ }+ v.Provider, v.CloneURL, v.GongfengProjectID = domain.RepositoryProviderSSH, remote.URL, ""+ if v.Name == "" {+ v.Name = strings.TrimSuffix(remote.Path[strings.LastIndex(remote.Path, "/")+1:], ".git")+ }+ if v.DefaultBranch == "" {+ v.DefaultBranch = "main"+ }+ h.saveRepository(c, v)+ return+ }// One pasted repository reference (web / SSH / clone / git clone / group/repo)// is enough. Prefer repoUrl so an SSH paste keeps an SSH clone URL.var parsed domain.GongfengRepoInfo@@ -119,14 +165,10 @@ func (h *catalogHandlers) repositories(c *gin.Context) {}// An explicit pasted URL is authoritative. Generated identity/web/clone// fields must not silently redirect a correct URL to another repository.- primary := strings.TrimSpace(body.RepoURL)- if primary == "" {- primary = strings.TrimSpace(body.URL)- }if primary != "" {info, ok := domain.ParseRepositoryURL(primary)if !ok {- c.JSON(400, gin.H{"error": "仓库 URL 无法识别,请提供有效的 GitHub 仓库地址"})+ c.JSON(400, gin.H{"error": "仓库 URL 无法识别,请提供 GitHub 链接或 Git SSH 克隆地址"})return}if body.RepoURL != "" && body.URL != "" {@@ -181,10 +223,6 @@ func (h *catalogHandlers) repositories(c *gin.Context) {c.JSON(400, map[string]string{"error": "请提供 projectId 和 GitHub 仓库地址 repoUrl,名称和仓库标识会自动识别"})return}- if _, ok := h.repo.Project(v.ProjectID); !ok {- c.JSON(400, map[string]string{"error": "project not found"})- return- }if strings.HasPrefix(v.GongfengProjectID, "github:") {v.Provider = "github"if v.DefaultBranch == "" {@@ -207,6 +245,14 @@ func (h *catalogHandlers) repositories(c *gin.Context) {return}}+ h.saveRepository(c, v)+}++func (h *catalogHandlers) saveRepository(c *gin.Context, v domain.Repository) {+ if _, ok := h.repo.Project(v.ProjectID); !ok {+ c.JSON(http.StatusBadRequest, gin.H{"error": "project not found"})+ return+ }if err := h.repo.PutRepository(v); err != nil {respond(c, err)returndiff --git a/internal/httpapi/git_ssh_keys.go b/internal/httpapi/git_ssh_keys.gonew file mode 100644index 00000000..f51269fb--- /dev/null+++ b/internal/httpapi/git_ssh_keys.go@@ -0,0 +1,86 @@+package httpapi++import (+ "errors"+ "net/http"+ "strconv"+ "strings"+ "unicode/utf8"++ "agentflow/internal/gitwork"+ "agentflow/internal/repo"++ "github.com/gin-gonic/gin"+ "gorm.io/gorm"+)++func (h *usersHandlers) gitSSHKeys(c *gin.Context) {+ id, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil || id <= 0 {+ c.JSON(http.StatusBadRequest, gin.H{"error": "valid user id is required"})+ return+ }+ if user, ok := h.requestUser(c.Request, false); !ok || user.ID != id {+ c.JSON(http.StatusForbidden, gin.H{"error": "只能管理当前登录用户的 Git SSH 密钥"})+ return+ }+ switch c.Request.Method {+ case http.MethodPut:+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 32<<10)+ var input struct {+ ID string `json:"id"`+ Host string `json:"host"`+ Name string `json:"name"`+ PrivateKey string `json:"privateKey"`+ }+ if !decode(c, &input) {+ return+ }+ host, err := gitwork.SSHHostScope(input.Host)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ name := strings.TrimSpace(input.Name)+ if name == "" || utf8.RuneCountInString(name) > 80 {+ c.JSON(http.StatusBadRequest, gin.H{"error": "请输入 1 到 80 个字符的密钥名称"})+ return+ }+ privateKey := strings.TrimSpace(input.PrivateKey)+ if privateKey != "" {+ privateKey, err = gitwork.NormalizeSSHPrivateKey(privateKey)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ }+ if err := h.repo.SaveGitSSHKey(id, input.ID, host, name, privateKey); err != nil {+ if errors.Is(err, gitwork.ErrSSHKeyRequired) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "添加密钥时请粘贴私钥"})+ return+ }+ if errors.Is(err, repo.ErrGitSSHKeyExists) {+ c.JSON(http.StatusConflict, gin.H{"error": err.Error()})+ return+ }+ if errors.Is(err, gorm.ErrRecordNotFound) {+ c.JSON(http.StatusNotFound, gin.H{"error": "此主机的密钥已不存在"})+ return+ }+ respond(c, err)+ return+ }+ case http.MethodDelete:+ if err := h.repo.DeleteGitSSHKey(id, c.Param("keyID")); err != nil {+ respond(c, err)+ return+ }+ }+ keys, err := h.repo.GitSSHKeyDescriptions(id)+ if err != nil {+ respond(c, err)+ return+ }+ c.Header("Cache-Control", "no-store")+ c.JSON(http.StatusOK, keys)+}diff --git a/internal/httpapi/repository_ssh_test.go b/internal/httpapi/repository_ssh_test.gonew file mode 100644index 00000000..b60ce211--- /dev/null+++ b/internal/httpapi/repository_ssh_test.go@@ -0,0 +1,416 @@+package httpapi++import (+ "context"+ "crypto/ed25519"+ "crypto/rand"+ "encoding/json"+ "encoding/pem"+ "fmt"+ "net"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/gitwork"+ "agentflow/internal/runtime"++ "golang.org/x/crypto/ssh"+ "golang.org/x/crypto/ssh/knownhosts"+)++func TestSSHRepositoryCheckoutAndDelivery(t *testing.T) {+ if _, err := exec.LookPath("ssh"); err != nil {+ t.Skip("OpenSSH client is not installed")+ }+ remote, privateKey, bare, knownHosts := localSSHGit(t, nil)+ f := cvBNewHTTPFixture(t)+ credentialURL := fmt.Sprintf("/api/users/%d/credentials", f.user.ID)+ keyURL := fmt.Sprintf("/api/users/%d/git-ssh-keys", f.user.ID)+ if resp := cvBRequest(t, f, http.MethodPut, keyURL, map[string]string{"host": remote, "name": "SSH host", "privateKey": "invalid"}, true); resp.Code != http.StatusBadRequest {+ t.Fatalf("invalid SSH key: HTTP %d", resp.Code)+ }+ response := cvBRequest(t, f, http.MethodPut, keyURL, map[string]string{"host": remote, "name": "SSH host", "privateKey": privateKey}, true)+ var keys []domain.GitSSHKey+ if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &keys) != nil || len(keys) != 1 || strings.Contains(response.Body.String(), "PRIVATE KEY") {+ t.Fatalf("credential response must show metadata only (HTTP %d)", response.Code)+ }+ if user, _ := f.s.User(f.user.ID); !user.GitSSHKeyConfigured {+ t.Fatal("saved host key is missing its configured flag")+ }+ // An unrelated credential write must not overwrite the SSH key.+ if resp := cvBRequest(t, f, http.MethodPut, credentialURL, map[string]string{"codexBaseUrl": "https://example.org"}, true); resp.Code != http.StatusOK || f.s.GitSSHKeysForRemotes(f.user.ID, []string{remote})[remote] != privateKey {+ t.Fatalf("other credential update changed the SSH key (HTTP %d)", resp.Code)+ }++ input := map[string]string{"projectId": "platform", "repoUrl": remote, "webUrl": "https://forge.example.org/team/app"}+ t.Setenv(gitwork.SSHKnownHostsEnv, "")+ if resp := cvBRequest(t, f, http.MethodDelete, keyURL+"/"+keys[0].ID, nil, true); resp.Code != http.StatusOK {+ t.Fatalf("remove personal key before saving repository: HTTP %d", resp.Code)+ }+ resp := cvBRequest(t, f, http.MethodPost, "/api/repositories", input, true)+ var repository domain.Repository+ if err := json.Unmarshal(resp.Body.Bytes(), &repository); err != nil || resp.Code != http.StatusOK || repository.Provider != domain.RepositoryProviderSSH || repository.CloneURL != remote || repository.GongfengProjectID != "" {+ t.Fatalf("save repository: HTTP %d, %s", resp.Code, resp.Body.String())+ }+ // The missing-key warning is advisory; saving repository configuration does+ // not require a personal key. Add it later before attempting Git operations.+ if resp := cvBRequest(t, f, http.MethodPut, keyURL, map[string]string{"host": remote, "name": "SSH host", "privateKey": privateKey}, true); resp.Code != http.StatusOK {+ t.Fatalf("add personal key after saving repository: HTTP %d", resp.Code)+ }+ gitCtx := gitwork.WithSSHRemote(gitwork.WithSSHKeys(context.Background(), map[string]string{remote: privateKey}), remote)+ if _, err := gitwork.Run(gitCtx, t.TempDir(), "ls-remote", "--", remote); err == nil || !strings.Contains(err.Error(), gitwork.SSHKnownHostsEnv) {+ t.Fatalf("Git execution must still require host pinning: %v", err)+ }+ t.Setenv(gitwork.SSHKnownHostsEnv, knownHosts)+ rc := domain.RepositoryContext{RepositoryID: repository.ID, Name: repository.Name, Provider: repository.Provider, CloneURL: remote, WebURL: repository.WebURL, BaseBranch: "main", DefaultBranch: "main", WorkBranch: "feature/ssh-test", CreateNewWorkBranch: true, WorkspaceDir: "app"}+ run := domain.Run{+ ID: "run-git-ssh", Kind: domain.RunKindWorkspace, Status: "waiting",+ WorkflowSnapshot: domain.WorkflowDefinition{ID: domain.ConversationWorkspaceWorkflowID, SandboxProfileID: "local"},+ ExecutionContext: domain.TelemetryContext{ProjectID: "platform", ResponsibleUserID: f.user.ID},+ Repositories: []domain.RepositoryContext{rc}, Nodes: map[string]*domain.NodeRun{},+ }+ if err := f.s.PutRun(run); err != nil {+ t.Fatal(err)+ }+ // This integration spans multiple Git processes; allow slower CI hosts.+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)+ defer cancel()+ correctPins, err := os.ReadFile(knownHosts)+ if err != nil {+ t.Fatal(err)+ }+ identity, err := ssh.ParsePrivateKey([]byte(privateKey))+ if err != nil {+ t.Fatal(err)+ }+ endpoint, err := gitwork.ParseSSHRemote(remote)+ if err != nil {+ t.Fatal(err)+ }+ wrongPin := knownhosts.Line([]string{net.JoinHostPort(endpoint.Host, endpoint.Port)}, identity.PublicKey()) + "\n"+ if err := os.WriteFile(knownHosts, []byte(wrongPin), 0o600); err != nil {+ t.Fatal(err)+ }+ gitCtx = gitwork.WithSSHRemote(gitwork.WithSSHKeys(ctx, map[string]string{remote: privateKey}), remote)+ if _, err := gitwork.Run(gitCtx, t.TempDir(), "ls-remote", "--", remote); err == nil || !strings.Contains(err.Error(), "Host key verification failed") {+ t.Fatalf("an unexpected host key was not rejected: %v", err)+ }+ if err := os.WriteFile(knownHosts, correctPins, 0o600); err != nil {+ t.Fatal(err)+ }+ if err := f.e.MaterializeConversationWorkspace(ctx, run.ID); err != nil {+ t.Fatal(err)+ }+ root, reason := f.e.LocalRunWorkspace(run)+ if reason != "" {+ t.Fatal(reason)+ }+ checkout := filepath.Join(root, "app")+ if origin := sshTestGit(t, checkout, "remote", "get-url", "origin"); origin != remote {+ t.Fatalf("origin = %q", origin)+ }+ if got, err := runtime.ExecuteLocalCommand(ctx, root, runtime.CommandSpec{+ Argv: []string{"git", "-C", "app", "fetch", "origin", "main"}, CredentialBindings: []runtime.CredentialBinding{runtime.BindGit},+ }, runtime.RunCredentials{GitSSHKeys: map[string]string{remote: privateKey}}, nil); err != nil {+ t.Fatalf("sandbox Git fetch: %v (%s)", err, got)+ }+ if entries, err := filepath.Glob(filepath.Join(root, ".agentflow", "runtime", "lf-ssh-*")); err != nil || len(entries) != 0 {+ t.Fatalf("SSH command left a signing agent behind: %v %v", entries, err)+ }+ if err := os.WriteFile(filepath.Join(checkout, "app.txt"), []byte("ssh delivery\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ h := &agentToolGateway{deps: &deps{repo: f.s, engine: f.e}}+ session := &AgentToolSession{RunID: run.ID, ProjectID: "platform", UserID: f.user.ID, User: f.user, Mode: AgentToolAssistant}+ raw, err := h.workspaceSubmitMR(ctx, session, map[string]any{"title": "SSH delivery"})+ if err != nil {+ t.Fatal(err)+ }+ var output struct{ Results []workspaceMRResult }+ if err := json.Unmarshal([]byte(raw), &output); err != nil || len(output.Results) != 1 {+ t.Fatalf("invalid delivery result: %s", raw)+ }+ result := output.Results[0]+ if !result.Pushed || !result.PushOnly || result.MRURL != "" || result.RepositoryURL != repository.WebURL || result.Commit != sshTestGit(t, bare, "rev-parse", "refs/heads/feature/ssh-test") {+ t.Fatalf("SSH delivery = %+v", result)+ }+ if resp := cvBRequest(t, f, http.MethodDelete, keyURL+"/"+keys[0].ID, nil, true); resp.Code != http.StatusOK || f.s.GitSSHKeysForRemotes(f.user.ID, []string{remote})[remote] != "" {+ t.Fatalf("remove key: HTTP %d", resp.Code)+ }+ if _, err := h.workspaceSubmitMR(ctx, session, map[string]any{"title": "No key"}); err == nil || !strings.Contains(err.Error(), "未配置 Git SSH 密钥") {+ t.Fatalf("missing SSH key must explain the fix: %v", err)+ }+}++func TestGitSSHKeysMatchHostAndPort(t *testing.T) {+ if _, err := exec.LookPath("ssh"); err != nil {+ t.Skip("OpenSSH client is not installed")+ }+ const otherPath = "/team/other.git"+ app, firstKey, _, knownHosts := localSSHGit(t, map[string]ssh.PublicKey{otherPath: nil})+ second, secondKey, _, secondPins := localSSHGit(t, nil)+ pins, _ := os.ReadFile(knownHosts)+ extraPins, _ := os.ReadFile(secondPins)+ if err := os.WriteFile(knownHosts, append(pins, extraPins...), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv(gitwork.SSHKnownHostsEnv, knownHosts)+ other := strings.TrimSuffix(app, "/team/app.git") + otherPath+ firstHost, _ := gitwork.SSHHostScope(app)+ secondHost, _ := gitwork.SSHHostScope(second)+ f := cvBNewHTTPFixture(t)+ endpoint := fmt.Sprintf("/api/users/%d/git-ssh-keys", f.user.ID)+ if resp := cvBRequest(t, f, http.MethodGet, "/api/users/999/git-ssh-keys", nil, true); resp.Code != http.StatusForbidden {+ t.Fatalf("another account's credentials returned HTTP %d", resp.Code)+ }+ putKey := func(input map[string]string) []domain.GitSSHKey {+ t.Helper()+ resp := cvBRequest(t, f, http.MethodPut, endpoint, input, true)+ var keys []domain.GitSSHKey+ if resp.Code != http.StatusOK || json.Unmarshal(resp.Body.Bytes(), &keys) != nil || strings.Contains(resp.Body.String(), "PRIVATE KEY") || strings.Contains(resp.Body.String(), `"scope"`) {+ t.Fatalf("save SSH host key metadata: HTTP %d", resp.Code)+ }+ return keys+ }+ keys := putKey(map[string]string{"host": app, "name": "First host", "privateKey": firstKey})+ firstID := keys[0].ID+ keys = putKey(map[string]string{"host": second, "name": "Second host", "privateKey": secondKey})+ if len(keys) != 2 || keys[0].Host != firstHost || keys[1].Host != secondHost {+ t.Fatalf("saved host metadata = %+v", keys)+ }+ duplicate := map[string]string{"host": other, "name": "Duplicate", "privateKey": secondKey}+ if resp := cvBRequest(t, f, http.MethodPut, endpoint, duplicate, true); resp.Code != http.StatusConflict {+ t.Fatalf("a second key for the same host returned HTTP %d", resp.Code)+ }+ if resp := cvBRequest(t, f, http.MethodPut, endpoint, map[string]string{"scope": "default", "privateKey": secondKey}, true); resp.Code != http.StatusBadRequest {+ t.Fatalf("an unbound default key returned HTTP %d", resp.Code)+ }+ keys = putKey(map[string]string{"id": firstID, "host": firstHost, "name": "First host renamed"})+ if keys[0].Name != "First host renamed" {+ t.Fatalf("renamed key metadata = %+v", keys)+ }+ const unrelated = "[email protected]:team/app.git"+ selected := f.s.GitSSHKeysForRemotes(f.user.ID, []string{app, other, second, unrelated})+ if selected[app] != firstKey || selected[other] != firstKey || selected[second] != secondKey || selected[unrelated] != "" {+ t.Fatal("keys must match the host and port, with no fallback for unconfigured hosts")+ }+ if f.s.GitSSHKeysForRemotes(f.user.ID+1, []string{app})[app] != "" {+ t.Fatal("a different user borrowed the host key")+ }+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ out, err := runtime.ExecuteLocalCommand(ctx, t.TempDir(), runtime.CommandSpec{+ Argv: []string{"sh", "-c", `git ls-remote --exit-code -- "$1" refs/heads/main && git ls-remote --exit-code -- "$2" refs/heads/main && git ls-remote --exit-code -- "$3" refs/heads/main`, "git-ssh-test", app, other, second},+ CredentialBindings: []runtime.CredentialBinding{runtime.BindGit},+ }, runtime.RunCredentials{GitSSHKeys: map[string]string{app: selected[app], other: selected[other], second: selected[second]}}, nil)+ if err != nil || strings.Count(out, "refs/heads/main") != 3 {+ t.Fatalf("one sandbox must authenticate to both hosts and share the first host key: %v (%s)", err, out)+ }+ if resp := cvBRequest(t, f, http.MethodDelete, endpoint+"/"+firstID, nil, true); resp.Code != http.StatusOK {+ t.Fatalf("delete host key: HTTP %d", resp.Code)+ }+ selected = f.s.GitSSHKeysForRemotes(f.user.ID, []string{app, other, second})+ if selected[app] != "" || selected[other] != "" || selected[second] != secondKey {+ t.Fatal("deleting a host key must affect that host's repositories only")+ }+}++func TestGitSSHRunnerClaimUsesTaskActorCredential(t *testing.T) {+ f := cvBNewHTTPFixture(t)+ actor := domain.User{LoginName: "ssh-delivery-actor"}+ if err := f.s.PutUser(actor); err != nil {+ t.Fatal(err)+ }+ actor, _ = f.s.UserByLoginName(actor.LoginName)+ const key = "transient-other-host-identity"+ const gitlabKey = "transient-gitlab-host-identity"+ const gitlabRepo = "[email protected]:team/app.git"+ const otherHostRepo = "[email protected]:team/app.git"+ if err := f.s.SaveGitSSHKey(actor.ID, "", otherHostRepo, "Other Git host", key); err != nil {+ t.Fatal(err)+ }+ if err := f.s.SaveGitSSHKey(actor.ID, "", gitlabRepo, "GitLab", gitlabKey); err != nil {+ t.Fatal(err)+ }+ runnerID, session := registerTestRunner(t, f.h)+ registered, _ := f.s.Runner(runnerID)+ now := time.Now().UTC()+ if err := f.s.RunnerHeartbeat(runnerID, registered.Runtimes, domain.RunnerVersionGitSSH, now, now.Add(time.Hour)); err != nil {+ t.Fatal(err)+ }+ task := domain.RunnerTask{ID: "ssh-task", RunnerID: runnerID, Provider: "mock", Status: domain.RunnerTaskQueued, MaxAttempts: 1, Invocation: &domain.RunnerInvocation{+ GitSSHUserID: actor.ID,+ Repositories: []domain.RunnerRepository{{CloneURL: gitlabRepo, UseSSH: true}, {CloneURL: otherHostRepo, UseSSH: true}},+ }}+ if err := f.s.PutRunnerTask(task); err != nil {+ t.Fatal(err)+ }+ resp := requestWithHeaders(t, f.h, http.MethodPost, "/api/runners/tasks/claim", map[string]any{"availableRuntimes": []string{"mock"}, "noWait": true}, map[string]string{"Authorization": "Bearer " + session})+ var result struct{ Task domain.RunnerTask }+ if err := json.Unmarshal(resp.Body.Bytes(), &result); err != nil || resp.Code != http.StatusOK || result.Task.ID != task.ID || result.Task.Invocation == nil || result.Task.Invocation.GitSSHKeys[gitlabRepo] != gitlabKey || result.Task.Invocation.GitSSHKeys[otherHostRepo] != key || result.Task.Invocation.GitSSHUserID != 0 {+ t.Fatalf("authenticated claim did not hydrate the task actor's keys (HTTP %d)", resp.Code)+ }+ stored, _ := f.s.RunnerTask(task.ID)+ if stored.Invocation == nil || len(stored.Invocation.GitSSHKeys) != 0 {+ t.Fatal("claimed key was persisted")+ }+ if resp := requestWithHeaders(t, f.h, http.MethodGet, "/api/runners/tasks/"+task.ID, nil, map[string]string{"Authorization": "Bearer " + session}); resp.Code != http.StatusOK || strings.Contains(resp.Body.String(), "gitSsh") || strings.Contains(resp.Body.String(), key) {+ t.Fatalf("runner status response must omit credential fields (HTTP %d)", resp.Code)+ }+}++func sshTestGit(t *testing.T, dir string, args ...string) string {+ t.Helper()+ cmd := exec.Command("git", args...)+ cmd.Dir = dir+ output, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %v: %v (%s)", args, err, output)+ }+ return strings.TrimSpace(string(output))+}++func sshTestIdentity(t *testing.T) (string, ssh.PublicKey) {+ t.Helper()+ public, identity, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ key, err := ssh.NewPublicKey(public)+ if err != nil {+ t.Fatal(err)+ }+ block, err := ssh.MarshalPrivateKey(identity, "loopforge integration test")+ if err != nil {+ t.Fatal(err)+ }+ return string(pem.EncodeToMemory(block)), key+}++// A loopback SSH server runs Git on one disposable bare repository, with a+// separate public-key permission for each SSH repository path.+func localSSHGit(t *testing.T, extraKeys map[string]ssh.PublicKey) (remote, privateKey, bare, knownHosts string) {+ t.Helper()+ root := t.TempDir()+ bare = filepath.Join(root, "app.git")+ sshTestGit(t, root, "init", "-b", "main")+ sshTestGit(t, root, "-c", "user.name=Test", "-c", "[email protected]", "commit", "--allow-empty", "-m", "base")+ sshTestGit(t, root, "clone", "--bare", ".", bare)+ _, hostKey, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ host, err := ssh.NewSignerFromKey(hostKey)+ if err != nil {+ t.Fatal(err)+ }+ privateKey, user := sshTestIdentity(t)+ expected := map[string]string{"/team/app.git": ssh.FingerprintSHA256(user)}+ for path, key := range extraKeys {+ if key == nil {+ key = user+ }+ expected[path] = ssh.FingerprintSHA256(key)+ }+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = listener.Close() })+ config := &ssh.ServerConfig{PublicKeyCallback: func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {+ if conn.User() == "git" {+ fingerprint := ssh.FingerprintSHA256(key)+ for _, allowed := range expected {+ if fingerprint == allowed {+ return &ssh.Permissions{Extensions: map[string]string{"key": fingerprint}}, nil+ }+ }+ }+ return nil, fmt.Errorf("unknown key")+ }}+ config.AddHostKey(host)+ knownHosts = filepath.Join(root, "known_hosts")+ if err := os.WriteFile(knownHosts, []byte(knownhosts.Line([]string{listener.Addr().String()}, host.PublicKey())+"\n"), 0o600); err != nil {+ t.Fatal(err)+ }+ go func(repo string) {+ for {+ conn, err := listener.Accept()+ if err != nil {+ return+ }+ go serveSSHGit(conn, config, repo, expected)+ }+ }(bare)+ return "ssh://git@" + listener.Addr().String() + "/team/app.git", privateKey, bare, knownHosts+}++func serveSSHGit(raw net.Conn, config *ssh.ServerConfig, bare string, expected map[string]string) {+ defer raw.Close()+ _ = raw.SetDeadline(time.Now().Add(30 * time.Second))+ conn, sessions, requests, err := ssh.NewServerConn(raw, config)+ if err != nil {+ return+ }+ defer conn.Close()+ go ssh.DiscardRequests(requests)+ for session := range sessions {+ if session.ChannelType() != "session" {+ _ = session.Reject(ssh.UnknownChannelType, "session required")+ continue+ }+ channel, commands, err := session.Accept()+ if err != nil {+ return+ }+ defer channel.Close()+ for request := range commands {+ var command struct{ Value string }+ if request.Type != "exec" || ssh.Unmarshal(request.Payload, &command) != nil {+ _ = request.Reply(false, nil)+ continue+ }+ program, path, _ := strings.Cut(command.Value, " ")+ if expected[strings.Trim(path, "'")] != conn.Permissions.Extensions["key"] || (program != "git-upload-pack" && program != "git-receive-pack") {+ _ = request.Reply(false, nil)+ return+ }+ _ = request.Reply(true, nil)+ cmd := exec.Command(program, bare)+ cmd.Stdin, cmd.Stdout, cmd.Stderr = channel, channel, channel.Stderr()+ var exitCode uint32+ if err := cmd.Run(); err != nil {+ exitCode = 1+ }+ _, _ = channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Code uint32 }{exitCode}))+ return+ }+ }+}++// GitHub SSH-style addresses keep the GitHub provider (HTTPS + token and+// automatic pull requests); only an explicit provider "ssh" switches transport.+func TestGitHubSSHAddressStaysGitHubRepository(t *testing.T) {+ f := cvBNewHTTPFixture(t)+ for _, address := range []string{"[email protected]:octo/widgets.git", "ssh://[email protected]/octo/widgets.git", "git clone [email protected]:octo/widgets.git"} {+ resp := cvBRequest(t, f, http.MethodPost, "/api/repositories", map[string]string{"projectId": "platform", "repoUrl": address}, true)+ var repository domain.Repository+ if err := json.Unmarshal(resp.Body.Bytes(), &repository); err != nil || resp.Code != http.StatusOK {+ t.Fatalf("%s: HTTP %d, %s", address, resp.Code, resp.Body.String())+ }+ if repository.Provider != "github" || repository.GongfengProjectID != "github:octo/widgets" || repository.CloneURL != "https://github.com/octo/widgets.git" {+ t.Fatalf("%s saved as provider=%q id=%q clone=%q", address, repository.Provider, repository.GongfengProjectID, repository.CloneURL)+ }+ }+ resp := cvBRequest(t, f, http.MethodPost, "/api/repositories", map[string]string{"projectId": "platform", "provider": domain.RepositoryProviderSSH, "repoUrl": "[email protected]:octo/gadgets.git"}, true)+ var explicit domain.Repository+ if err := json.Unmarshal(resp.Body.Bytes(), &explicit); err != nil || resp.Code != http.StatusOK || explicit.Provider != domain.RepositoryProviderSSH || explicit.CloneURL != "[email protected]:octo/gadgets.git" {+ t.Fatalf("explicit SSH provider: HTTP %d, %s", resp.Code, resp.Body.String())+ }+}diff --git a/internal/httpapi/run_workspace_edit.go b/internal/httpapi/run_workspace_edit.goindex 09553cff..a9105e76 100644--- a/internal/httpapi/run_workspace_edit.go+++ b/internal/httpapi/run_workspace_edit.go@@ -227,7 +227,7 @@ func (h *runsHandlers) workspaceTerminal(c *gin.Context) {result = json.RawMessage(response.Payload)return nil}- r, err := h.engine.HandlePreparedWorkspaceTerminal(c.Request.Context(), run.ID, &h.terminals, fmt.Sprintf("%s:%d", run.ID, user), req)+ r, err := h.engine.HandlePreparedWorkspaceTerminal(c.Request.Context(), run.ID, &h.terminals, fmt.Sprintf("%s:%d", run.ID, user), req, user)result = rreturn err})diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.goindex 7e06301b..7162a5e3 100644--- a/internal/httpapi/runners.go+++ b/internal/httpapi/runners.go@@ -845,6 +845,11 @@ func (h *runnersHandlers) runnerTaskClaim(c *gin.Context) {c.JSON(http.StatusOK, map[string]bool{"taskAvailable": true})return}+ if task.Invocation != nil && task.Invocation.GitSSHUserID > 0 && runner.SupportsGitSSH() && len(task.Invocation.GitSSHRemotes()) > 0 {+ task.Invocation.GitSSHKeys = h.repo.GitSSHKeysForRemotes(task.Invocation.GitSSHUserID, task.Invocation.GitSSHRemotes())+ task.Invocation.GitSSHUserID = 0+ c.Header("Cache-Control", "no-store")+ }c.JSON(http.StatusOK, map[string]any{"task": resolveRunnerTaskSandbox(task, runner.OS)})}deadline := time.Now().Add(runnerLongPollTimeout())diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.goindex cb950ea9..3c1e2f70 100644--- a/internal/httpapi/schedule.go+++ b/internal/httpapi/schedule.go@@ -264,7 +264,7 @@ func (h *scheduleHandlers) guardScheduledBaseline(job domain.ScheduleJob, issues}continue}- err := h.engine.AlignBaseline(ctx, engine.ResolveClarifyGitToken(h.repo, responsible.ID))+ err := h.engine.AlignBaselineForUser(ctx, responsible.ID)if err == nil {h.cancelStaleAlignRuns(repo.ID)continuediff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 3ac5a35d..8c6677c5 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -276,6 +276,9 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv// 工蜂 Git Token 校验:只允许当前登录用户校验自己的令牌。g.GET("/api/users/:id/git-token/verify", api.users.verifyGitToken)g.POST("/api/users/:id/git-token/verify", api.users.verifyGitToken)+ g.GET("/api/users/:id/git-ssh-keys", api.users.gitSSHKeys)+ g.PUT("/api/users/:id/git-ssh-keys", api.users.gitSSHKeys)+ g.DELETE("/api/users/:id/git-ssh-keys/:keyID", api.users.gitSSHKeys)g.POST("/api/users/:id/cli-models/probe", api.users.probeCLIModels)g.Any("/api/users/:id", func(c *gin.Context) {c.JSON(http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.goindex e1bbc75a..dfb06c58 100644--- a/internal/httpapi/stream.go+++ b/internal/httpapi/stream.go@@ -16,6 +16,7 @@ import ("agentflow/internal/domain""agentflow/internal/engine"+ "agentflow/internal/gitwork""agentflow/internal/managedcli""agentflow/internal/runtime"@@ -308,7 +309,20 @@ func (h *streamHandlers) prepareClarifyRepo(ctx context.Context, repo domain.Rep}// Resolve the configured default before choosing a cache. Changing a// repository's main branch must not reuse its previous branch's checkout.- identity := sha256.Sum256([]byte(repo.ID + "\x00" + resolvedBranch))+ cacheKey := repo.ID + "\x00" + resolvedBranch+ ssh := repo.Provider == domain.RepositoryProviderSSH+ if ssh {+ keys := h.repo.GitSSHKeysForRemotes(responsibleUserID, []string{repo.CloneURL})+ key := keys[repo.CloneURL]+ if key == "" {+ return "", false, gitwork.ErrSSHKeyRequired.Error()+ }+ ctx = gitwork.WithSSHKeys(ctx, keys)+ // A private SSH checkout is never shared across users, changed+ // repository bindings, or a removed or replaced key.+ cacheKey += fmt.Sprintf("\x00%d\x00%s\x00%x", responsibleUserID, repo.CloneURL, sha256.Sum256([]byte(key)))+ }+ identity := sha256.Sum256([]byte(cacheKey))dirName += fmt.Sprintf("-%x", identity[:8])cacheDir := filepath.Join(clarifyRepoCacheRoot(), dirName)@@ -319,7 +333,7 @@ func (h *streamHandlers) prepareClarifyRepo(ctx context.Context, repo domain.RephadCheckout := statDir(filepath.Join(cacheDir, ".git"))// Reuse an existing checkout without refreshing on later turns.- if hadCheckout && !refresh {+ if hadCheckout && !refresh && !ssh {return cacheDir, true, ""}@@ -328,7 +342,7 @@ func (h *streamHandlers) prepareClarifyRepo(ctx context.Context, repo domain.Repdefer cancel()if _, err := engine.PrepareClarifyWorkspaceAtBranch(prepCtx, cacheDir, repo, baseBranch, token); err != nil {- if hadCheckout && baseBranch == "" {+ if hadCheckout && baseBranch == "" && !ssh {// Degrade to the previous (possibly stale) checkout.return cacheDir, true, ""}@@ -341,6 +355,9 @@ func (h *streamHandlers) prepareClarifyRepo(ctx context.Context, repo domain.Rep// Git checkouts are cloned before selecting a branch. Never switch the user's// original checkout to the configured main branch.func clarifyRepositorySource(repository domain.Repository, selectedBaseBranch string) (domain.Repository, bool) {+ if repository.Provider == domain.RepositoryProviderSSH {+ return repository, false+ }localPath := strings.TrimSpace(repository.LocalPath)if localPath != "" && statDir(localPath) {if _, err := os.Stat(filepath.Join(localPath, ".git")); err == nil {diff --git a/internal/repo/git_ssh_credentials.go b/internal/repo/git_ssh_credentials.gonew file mode 100644index 00000000..b0cf8f13--- /dev/null+++ b/internal/repo/git_ssh_credentials.go@@ -0,0 +1,106 @@+package repo++import (+ "crypto/sha256"+ "errors"+ "fmt"++ "agentflow/internal/domain"+ "agentflow/internal/gitwork"++ "gorm.io/gorm"+)++func gitSSHKeyID(host string) string {+ return fmt.Sprintf("%x", sha256.Sum256([]byte(host)))+}++// GitSSHKeyDescriptions never reads private keys into the public response.+func (r *UsersRepo) GitSSHKeyDescriptions(userID int64) ([]domain.GitSSHKey, error) {+ keys := make([]domain.GitSSHKey, 0)+ err := r.DB.Model(&gitSSHKeyRow{}).Select("id", "name", "host").Where("user_id = ?", userID).Order("name, id").Find(&keys).Error+ return keys, err+}++var ErrGitSSHKeyExists = errors.New("该 SSH 主机已有密钥,请编辑现有密钥")++func (r *UsersRepo) SaveGitSSHKey(userID int64, existingID, host, name, privateKey string) error {+ host, err := gitwork.SSHHostScope(host)+ if err != nil {+ return err+ }+ id := gitSSHKeyID(host)+ if existingID == "" {+ if privateKey == "" {+ return gitwork.ErrSSHKeyRequired+ }+ row := gitSSHKeyRow{UserID: userID, ID: id, Host: host, Name: name, PrivateKey: privateKey}+ err := r.DB.Create(&row).Error+ if errors.Is(err, gorm.ErrDuplicatedKey) {+ return ErrGitSSHKeyExists+ }+ return err+ }+ if existingID != id {+ return gorm.ErrRecordNotFound+ }+ row := r.DB.Model(&gitSSHKeyRow{}).Where("user_id = ? AND id = ?", userID, id)+ updates := map[string]any{"name": name}+ if privateKey != "" {+ updates["private_key"] = privateKey+ }+ result := row.Session(&gorm.Session{}).Updates(updates)+ if result.Error != nil || result.RowsAffected != 0 {+ return result.Error+ }+ // MySQL can report zero affected rows for an unchanged value.+ var count int64+ if err := row.Count(&count).Error; err != nil {+ return err+ }+ if count == 0 {+ return gorm.ErrRecordNotFound+ }+ return nil+}++func (r *UsersRepo) DeleteGitSSHKey(userID int64, id string) error {+ return r.DB.Where("user_id = ? AND id = ?", userID, id).Delete(&gitSSHKeyRow{}).Error+}++// GitSSHKeysForRemotes matches only the user's key for each SSH host and port.+// Unconfigured repositories retain empty values so they cannot borrow another+// host's identity or fall back to the execution machine's credentials.+func (r *UsersRepo) GitSSHKeysForRemotes(userID int64, urls []string) map[string]string {+ if len(urls) == 0 {+ return nil+ }+ keys := make(map[string]string, len(urls))+ ids := make([]string, 0, len(urls))+ targets := make(map[string]string, len(urls))+ for _, raw := range urls {+ keys[raw] = ""+ remote, err := gitwork.ParseSSHRemote(raw)+ if err != nil {+ continue+ }+ id := gitSSHKeyID(remote.Endpoint())+ targets[raw] = id+ ids = append(ids, id)+ }+ if userID <= 0 || len(ids) == 0 {+ return keys+ }+ var matches []gitSSHKeyRow+ if err := r.DB.Select("id", "private_key").Where("user_id = ? AND id IN ?", userID, ids).Find(&matches).Error; err != nil {+ return keys+ }+ byID := make(map[string]string, len(matches))+ for _, key := range matches {+ byID[key.ID] = key.PrivateKey+ }+ for remote, id := range targets {+ keys[remote] = byID[id]+ }+ return keys+}diff --git a/internal/repo/models.go b/internal/repo/models.goindex f0add9d8..71b26a75 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -52,6 +52,16 @@ type userConfigRow struct {func (userConfigRow) TableName() string { return "user_configs" }+type gitSSHKeyRow struct {+ UserID int64 `gorm:"primaryKey;autoIncrement:false"`+ ID string `gorm:"primaryKey;size:64"`+ Name string `gorm:"size:80;not null"`+ Host string `gorm:"type:text;not null"`+ PrivateKey string `gorm:"type:text;not null"`+}++func (gitSSHKeyRow) TableName() string { return "user_git_ssh_keys" }+type apiTokenRow struct {ID string `gorm:"column:id;primaryKey;size:64"`UserID int64 `gorm:"column:user_id;index:idx_api_tokens_user"`@@ -689,7 +699,7 @@ func (knowledgeSubmissionRow) TableName() string { return "knowledge_submissions// allModels lists every table for the sqlite test schema (AutoMigrate).func allModels() []any {return []any{domain.BotUserBinding{}, domain.BotBindingChallenge{}, domain.BotConnection{}, domain.BotConversation{}, domain.BotInteraction{}, notificationBotRow{}, botCredentialRow{}, domain.NotificationDelivery{},- userRow{}, localAccountRow{}, userConfigRow{}, authIntegrationRow{}, platformCodeBuddyKeyRow{}, apiTokenRow{}, genericTemplateRow{},+ userRow{}, localAccountRow{}, userConfigRow{}, gitSSHKeyRow{}, authIntegrationRow{}, platformCodeBuddyKeyRow{}, apiTokenRow{}, genericTemplateRow{},insightSourceRow{}, insightExecutionRow{},projectRow{}, projectMemberRow{}, repositoryRow{}, businessDomainRow{}, businessDomainAssignmentRow{},agentRow{}, ruleRow{}, skillRow{}, skillFileRow{}, mcpServerRow{}, mcpFileRow{}, executorRow{},diff --git a/internal/repo/mysql_live_test.go b/internal/repo/mysql_live_test.goindex d6e00662..c34fe6af 100644--- a/internal/repo/mysql_live_test.go+++ b/internal/repo/mysql_live_test.go@@ -2,6 +2,7 @@ package repoimport ("encoding/json"+ "errors""fmt""os""strings"@@ -172,6 +173,8 @@ func TestMySQLRunnerTaskCompletionScrubsCredentials(t *testing.T) {CodexAPIKey: "codex-secret",CodexBaseURL: "https://gateway.example/v1",Repository: &domain.RunnerRepository{CloneURL: "https://example.com/repo.git", GitToken: "git-secret"},+ GitSSHUserID: 42,+ GitSSHKeys: map[string]string{"[email protected]:team/app.git": "ssh-key-must-not-be-queued"},},}if err := s.PutRunnerTask(task); err != nil {@@ -184,6 +187,9 @@ func TestMySQLRunnerTaskCompletionScrubsCredentials(t *testing.T) {if claimed.Sandbox == nil || claimed.Sandbox.Profile.Driver != "docker" {t.Fatalf("claimed task lost runner sandbox: %+v", claimed.Sandbox)}+ if claimed.Invocation == nil || len(claimed.Invocation.GitSSHKeys) != 0 || claimed.Invocation.GitSSHUserID != 42 {+ t.Fatal("queue must retain the SSH credential reference only")+ }if err := s.CompleteRunnerTask(claimed.ID, runnerID, domain.RunnerTaskSuccess, nil, "done", "", nil, nil, time.Now().UTC()); err != nil {t.Fatal(err)}@@ -191,7 +197,77 @@ func TestMySQLRunnerTaskCompletionScrubsCredentials(t *testing.T) {if err := s.DB.Raw(`SELECT payload FROM runner_tasks WHERE id=?`, taskID).Scan(&payload).Error; err != nil {t.Fatal(err)}- if strings.Contains(payload, "codex-secret") || strings.Contains(payload, "git-secret") || strings.Contains(payload, "gateway.example") {+ if strings.Contains(payload, "codex-secret") || strings.Contains(payload, "git-secret") || strings.Contains(payload, "gateway.example") || strings.Contains(payload, "gitSsh") {t.Fatalf("completed task retained credential material: %s", payload)}}++func TestMySQLGitSSHCredentialLifecycle(t *testing.T) {+ dsn := os.Getenv("AGENTFLOW_TEST_MYSQL_DSN")+ if dsn == "" {+ t.Skip("AGENTFLOW_TEST_MYSQL_DSN is not set")+ }+ s, err := Open(dsn)+ if err != nil {+ t.Fatal(err)+ }+ defer s.Close()+ login := fmt.Sprintf("git-ssh-%d", time.Now().UnixNano())+ if err := s.PutUser(domain.User{LoginName: login}); err != nil {+ t.Fatal(err)+ }+ user, ok := s.UserByLoginName(login)+ if !ok {+ t.Fatal("test user not found")+ }+ defer func() {+ _ = s.DB.Exec(`DELETE FROM user_git_ssh_keys WHERE user_id=?`, user.ID).Error+ _ = s.DB.Exec(`DELETE FROM user_configs WHERE user_id=?`, user.ID).Error+ _ = s.DB.Exec(`DELETE FROM users WHERE id=?`, user.ID).Error+ }()+ if _, err := s.UpdateUserCredentials(user.ID, UserCredentialUpdate{GitToken: "test-only token"}); err != nil {+ t.Fatal(err)+ }+ const first = "[email protected]:team/app.git"+ const sameHost = "[email protected]:other/repo.git"+ const second = "ssh://[email protected]:2222/team/app.git"+ const missing = "[email protected]:team/app.git"+ if err := s.SaveGitSSHKey(user.ID, "", "gitlab.example.org", "GitLab", "test-only first key"); err != nil {+ t.Fatal(err)+ }+ if stored, ok := s.User(user.ID); !ok || !stored.GitSSHKeyConfigured {+ t.Fatal("stored SSH host key is missing its configured flag")+ }+ if err := s.SaveGitSSHKey(user.ID, "", "GITLAB.EXAMPLE.ORG:22", "Duplicate", "test-only duplicate key"); !errors.Is(err, ErrGitSSHKeyExists) {+ t.Fatalf("duplicate host: %v", err)+ }+ if err := s.SaveGitSSHKey(user.ID, "", "git.example.org:2222", "Other host", "test-only second key"); err != nil {+ t.Fatal(err)+ }+ keys, err := s.GitSSHKeyDescriptions(user.ID)+ if err != nil || len(keys) != 2 || keys[0].Host != "gitlab.example.org:22" || keys[1].Host != "git.example.org:2222" {+ t.Fatalf("list SSH host key metadata: %+v (%v)", keys, err)+ }+ if err := s.SaveGitSSHKey(user.ID, keys[0].ID, keys[0].Host, "GitLab", ""); err != nil {+ t.Fatalf("unchanged key update: %v", err)+ }+ selected := s.GitSSHKeysForRemotes(user.ID, []string{first, sameHost, second, missing})+ if selected[first] != "test-only first key" || selected[sameHost] != selected[first] || selected[second] != "test-only second key" || selected[missing] != "" {+ t.Fatal("host matching, shared key or port isolation failed")+ }+ if err := s.SaveGitSSHKey(user.ID, keys[0].ID, keys[0].Host, "New name", "rotated key"); err != nil {+ t.Fatal(err)+ }+ selected = s.GitSSHKeysForRemotes(user.ID, []string{first, second})+ if selected[first] != "rotated key" || selected[second] != "test-only second key" {+ t.Fatal("rotation changed a different host's key")+ }+ for _, key := range keys {+ if err := s.DeleteGitSSHKey(user.ID, key.ID); err != nil {+ t.Fatal(err)+ }+ }+ if user, _ := s.User(user.ID); user.GitSSHKeyConfigured || user.GitToken != "test-only token" {+ t.Fatal("deleting SSH keys changed the token or left the configured flag set")+ }+}diff --git a/internal/repo/runners.go b/internal/repo/runners.goindex d733f2a6..74e998ed 100644--- a/internal/repo/runners.go+++ b/internal/repo/runners.go@@ -130,6 +130,11 @@ func runnerTaskFromRow(row runnerTaskRow) domain.RunnerTask {}func runnerTaskPayloadBytes(v domain.RunnerTask) []byte {+ if v.Invocation != nil && len(v.Invocation.GitSSHKeys) > 0 {+ invocation := *v.Invocation+ invocation.GitSSHKeys = nil+ v.Invocation = &invocation+ }return mustJSON(runnerTaskPayload{Prompt: v.Prompt, Workspace: v.Workspace, Args: v.Args, ExitCode: v.ExitCode,Result: v.Result, Error: v.Error, StartedAt: newRunnerTaskTime(v.StartedAt),@@ -671,6 +676,8 @@ func scrubRunnerTaskCredentials(task *domain.RunnerTask) {task.Invocation.ClaudeCodeBaseURL = ""task.Invocation.AgentCLIAPIKey = ""task.Invocation.AgentCLIBaseURL = ""+ task.Invocation.GitSSHUserID = 0+ task.Invocation.GitSSHKeys = nilif task.Invocation.Repository != nil {task.Invocation.Repository.GitToken = ""}diff --git a/internal/repo/users.go b/internal/repo/users.goindex 6b7d98be..e15ec2c6 100644--- a/internal/repo/users.go+++ b/internal/repo/users.go@@ -23,6 +23,7 @@ type userWithConfig struct {DeptName string `gorm:"column:dept_name"`PlatformRole string `gorm:"column:platform_role"`GitToken *string `gorm:"column:git_token"`+ GitSSHKeyConfigured bool `gorm:"column:git_ssh_key_configured"`GongfengRefreshToken *string `gorm:"column:gongfeng_refresh_token"`GongfengTokenExpiresAt *time.Time `gorm:"column:gongfeng_token_expires_at"`CodeBuddyAPIKey *string `gorm:"column:codebuddy_api_key"`@@ -40,7 +41,8 @@ type userWithConfig struct {const userSelectColumns = `u.id, u.staff_id, u.login_name, u.chinese_name, u.dept_id, u.dept_name,COALESCE(u.platform_role, '') AS platform_role,- c.git_token, c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment,+ c.git_token, EXISTS (SELECT 1 FROM user_git_ssh_keys k WHERE k.user_id = u.id) AS git_ssh_key_configured,+ c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment,c.codex_api_key, c.codex_base_url, c.codex_models, c.claude_code_api_key, c.claude_code_base_url, c.claude_code_models,c.agent_cli_credentials,u.created_at, u.updated_at`@@ -50,6 +52,7 @@ func (r userWithConfig) toDomain() domain.User {ID: r.ID, StaffID: r.StaffID, LoginName: r.LoginName, ChineseName: r.ChineseName,DeptID: r.DeptID, DeptName: r.DeptName, PlatformRole: r.PlatformRole,CodeBuddyInternetEnvironment: r.CodeBuddyInternetEnvironment,+ GitSSHKeyConfigured: r.GitSSHKeyConfigured,}if r.GitToken != nil {u.GitToken = *r.GitToken@@ -342,7 +345,7 @@ func (r *UsersRepo) SaveGongfengOAuth(id int64, accessToken, refreshToken string}func (r *UsersRepo) writeUserConfig(v domain.User) error {- return upsert(r.DB, "user_configs", map[string]any{+ values := map[string]any{"user_id": v.ID,"git_token": nullableString(v.GitToken),"gongfeng_refresh_token": nullableString(v.GongfengRefreshToken), "gongfeng_token_expires_at": timePtr(v.GongfengTokenExpiresAt),@@ -352,7 +355,8 @@ func (r *UsersRepo) writeUserConfig(v domain.User) error {"claude_code_api_key": nullableString(v.ClaudeCodeAPIKey), "claude_code_base_url": nullableString(v.ClaudeCodeBaseURL), "claude_code_models": encodeCLIModels(v.ClaudeCodeModels),"agent_cli_credentials": encodeAgentCLICredentials(v.AgentCLICredentials),"created_at": timePtr(v.CreatedAt), "updated_at": timePtr(v.UpdatedAt),- })+ }+ return upsert(r.DB, "user_configs", values)}func nullableString(v string) any {diff --git a/internal/runner/align.go b/internal/runner/align.goindex 443dcc92..68adb6bb 100644--- a/internal/runner/align.go+++ b/internal/runner/align.go@@ -34,6 +34,7 @@ func alignBaseline(ctx context.Context, dir string, inv *domain.RunnerInvocationreturn domain.RunnerAlignResult{}, errors.New("align_baseline needs exactly one repository")}repo := inv.Repositories[0]+ ctx = gitwork.WithSSHKeys(ctx, inv.GitSSHKeys)integrate, def := strings.TrimSpace(repo.IntegrateBranch), strings.TrimSpace(repo.DefaultBranch)if integrate == "" || def == "" {return domain.RunnerAlignResult{}, errors.New("align_baseline needs integrate and default branches")@@ -47,7 +48,7 @@ func alignBaseline(ctx context.Context, dir string, inv *domain.RunnerInvocationif err := checkoutRepository(ctx, dir, &clone); err != nil {return domain.RunnerAlignResult{}, err}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(ctx, repo)gitwork.EnsureIdentity(repoCtx, dir)conflicts, err := gitwork.MergeLatestRemoteBranch(repoCtx, dir, def)if err != nil {diff --git a/internal/runner/daemon.go b/internal/runner/daemon.goindex 64ec3b00..006d92f9 100644--- a/internal/runner/daemon.go+++ b/internal/runner/daemon.go@@ -753,6 +753,11 @@ func (d *Daemon) executeTerminal(ctx context.Context, task domain.RunnerTask) exif err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("prepare git credentials: %v", err)}}+ cleanup, err := runtime.BindGitSSH(sandbox, workspace, gitEnv, task.Invocation.GitSSHKeys)+ if err != nil {+ return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("prepare git credentials: %v", err)}+ }+ defer cleanup()command = runtime.WithCommandEnvironment(command, gitEnv)}var result execResult@@ -809,7 +814,10 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)}defer release()}- boundAssets, _, err := runtime.PrepareMCPServers(inv.Assets, d.mcpTarget(true, invocationGitToken(inv)))+ target := d.mcpTarget(true, invocationGitToken(inv))+ sshRepoCount := len(inv.GitSSHRemotes())+ target.SSHRepositoriesOnly = sshRepoCount > 0 && sshRepoCount == max(len(inv.Repositories), 1)+ boundAssets, _, err := runtime.PrepareMCPServers(inv.Assets, target)if err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("bind MCP credentials: %v", err)}, nil}@@ -880,6 +888,11 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)if gitErr != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("prepare git credentials: %v", gitErr)}, nil}+ cleanup, gitErr := runtime.BindGitSSH(sandbox, workspace, gitEnv, inv.GitSSHKeys)+ if gitErr != nil {+ return execResult{status: domain.RunnerTaskFailed, errMsg: fmt.Sprintf("prepare git credentials: %v", gitErr)}, nil+ }+ defer cleanup()for key, value := range gitEnv {commandEnv[key] = value}@@ -1105,6 +1118,7 @@ func checkoutInvocationRepositories(ctx context.Context, workspace string, inv *if inv == nil {return nil}+ ctx = gitwork.WithSSHKeys(ctx, inv.GitSSHKeys)repos := inv.Repositoriesif len(repos) == 0 && inv.Repository != nil {if strings.TrimSpace(inv.Repository.CloneURL) == "" {@@ -1189,6 +1203,9 @@ func cloneRepository(ctx context.Context, workspace string, repo *domain.RunnerRif repo.RequireExistingWorkBranch && strings.TrimSpace(repo.WorkBranch) == "" {return fmt.Errorf("继续已有分支时必须指定工作分支")}+ if info, err := os.Stat(workspace); err != nil || !info.IsDir() {+ return fmt.Errorf("clone workspace is not a directory: %s", workspace)+ }url := strings.TrimSpace(repo.CloneURL)if err := gitwork.ValidateRemoteURL(url, true); err != nil {return fmt.Errorf("git clone: %w", err)@@ -1196,7 +1213,7 @@ func cloneRepository(ctx context.Context, workspace string, repo *domain.RunnerR// `-c` auth is scoped to this command, so origin stays the clean URL and// the token never lands in .git/config. --progress: without a terminal git// prints nothing until it finishes, so a slow clone looked hung.- args := append(gitwork.AuthConfigArgs(repo.GitToken), "clone", "--progress")+ args := []string{"clone", "--progress"}if ref := strings.TrimSpace(repo.Ref); ref != "" {args = append(args, "--branch", ref)}@@ -1204,12 +1221,7 @@ func cloneRepository(ctx context.Context, workspace string, repo *domain.RunnerRwatch := runnerCloneWatch(repo)// The platform cannot see this host's output yet; the operator can.ctx = procwatch.WithObserver(ctx, func(event procwatch.Event) { log.Printf("runner checkout: %s", event.Message) })- tail, err := procwatch.Run(ctx, func(ctx context.Context) *exec.Cmd {- cmd := exec.CommandContext(ctx, "git", args...)- cmd.Dir = workspace- cmd.Env = gitwork.Env(repo.GitToken)- return cmd- }, watch)+ tail, err := gitwork.Watch(repositoryGitContext(ctx, *repo), workspace, watch, args...)if err != nil {return fmt.Errorf("git clone %s: %w (%s)", repo.CloneURL, err, cloneOutput([]byte(tail), repo.GitToken))}@@ -1239,6 +1251,13 @@ func cloneRepository(ctx context.Context, workspace string, repo *domain.RunnerRreturn nil}+func repositoryGitContext(ctx context.Context, repo domain.RunnerRepository) context.Context {+ if repo.UseSSH {+ return gitwork.WithSSHRemote(ctx, repo.CloneURL)+ }+ return gitwork.WithToken(ctx, repo.GitToken)+}+// checkoutExistingRepositoryBranch validates the remote head even when the// run reuses a checkout. A normal tracking checkout may create a local ref;// it never invents a remote branch or resets existing local work.@@ -1247,7 +1266,7 @@ func checkoutExistingRepositoryBranch(ctx context.Context, workspace string, repif branch == "" {return fmt.Errorf("继续已有分支时必须指定工作分支")}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(ctx, *repo)trackingRef := "refs/remotes/origin/" + branchif _, err := gitwork.C(repoCtx, workspace, "fetch", "--no-tags", "origin", "+refs/heads/"+branch+":"+trackingRef); err != nil {return fmt.Errorf("无法读取已有远端分支 %s,请确认分支存在且有访问权限: %w", branch, err)@@ -1276,7 +1295,7 @@ func createNewRepositoryBranch(ctx context.Context, workspace string, repo *domaif branch == "" {return fmt.Errorf("新建分支时必须指定工作分支")}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(ctx, *repo)out, err := gitwork.C(repoCtx, workspace, "ls-remote", "--heads", "origin", "refs/heads/"+branch)if err != nil {return fmt.Errorf("无法确认远端分支 %s 是否存在: %w", branch, err)@@ -1300,7 +1319,7 @@ func checkoutCreatedRepositoryBranch(ctx context.Context, workspace string, repoif branch == "" {return fmt.Errorf("新建分支时必须指定工作分支")}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(ctx, *repo)if current, _ := gitwork.C(repoCtx, workspace, "branch", "--show-current"); strings.TrimSpace(current) == branch {return nil}@@ -1381,7 +1400,7 @@ func (d *Daemon) defaultWorkspace(taskID string) string {}// runnerVersion is reported at registration; it matches the module build.-var runnerVersion = "0.9.2"+var runnerVersion = domain.RunnerVersionGitSSH// Version returns the runner build version reported at registration.func Version() string { return runnerVersion }diff --git a/internal/runner/integrate.go b/internal/runner/integrate.goindex a7f9c1f1..ebdb6067 100644--- a/internal/runner/integrate.go+++ b/internal/runner/integrate.go@@ -54,7 +54,7 @@ func integrateTaskRepositories(ctx context.Context, workspace string, inv *domaiif rel := safeRunnerRepoDir(repo.Dir); rel != "" {dir = filepath.Join(workspace, rel)}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(gitwork.WithSSHKeys(ctx, inv.GitSSHKeys), repo)gitwork.EnsureIdentity(repoCtx, dir)result := domain.RunnerIntegrationResult{RepositoryID: repo.RepositoryID, Name: repo.Name, WorkBranch: work, IntegrateBranch: integrate}conflicts, err := gitwork.MergeLatestIntegration(repoCtx, dir, work, integrate, label)diff --git a/internal/runner/work_branch.go b/internal/runner/work_branch.goindex bae41a77..d4caca8d 100644--- a/internal/runner/work_branch.go+++ b/internal/runner/work_branch.go@@ -53,6 +53,7 @@ func syncTaskWorkBranches(ctx context.Context, workspace string, inv *domain.Runif inv == nil {return heads, nil}+ ctx = gitwork.WithSSHKeys(ctx, inv.GitSSHKeys)if strings.TrimSpace(message) == "" {message = "agentflow: " + inv.NodeID + " (" + inv.RunID + ")"}@@ -64,7 +65,7 @@ func syncTaskWorkBranches(ctx context.Context, workspace string, inv *domain.Runif rel := safeRunnerRepoDir(repo.Dir); rel != "" {dir = filepath.Join(workspace, rel)}- repoCtx := gitwork.WithToken(ctx, repo.GitToken)+ repoCtx := repositoryGitContext(ctx, repo)// A continued branch must still exist remotely even when nothing changed.if push && !repo.RequireExistingWorkBranch && !gitwork.HasWork(repoCtx, dir, repo.Ref) {continuediff --git a/internal/runner/workspace_preparation.go b/internal/runner/workspace_preparation.goindex 512f59e9..4ab568c6 100644--- a/internal/runner/workspace_preparation.go+++ b/internal/runner/workspace_preparation.go@@ -148,7 +148,7 @@ func (d *Daemon) handleRunnerWorkspaceTerminal(ctx context.Context, root, scopegate.RLock()release = onceRelease(releaseSandbox, gate.RUnlock)}- result, err := d.workspaceTerminals.HandleSandbox(ctx, execution, scope, *request.Terminal, release)+ result, err := d.workspaceTerminals.HandleSandboxWithGitSSH(ctx, execution, scope, *request.Terminal, release, request.TerminalGitSSHKeys)if err != nil {release()}@@ -163,6 +163,7 @@ func (d *Daemon) workspaceExecutionSandbox(ctx context.Context, sb runtime.Sandbinv := request.PreparationInvocationif inv != nil {credentials.GitToken = invocationGitToken(inv)+ credentials.GitSSHKeys = inv.GitSSHKeyscredentials.GitUserName = inv.GitUserNamecredentials.GitUserEmail = inv.GitUserEmailservers := inv.MCPCallServers@@ -245,7 +246,7 @@ func (d *Daemon) openBusyGroupTerminal(ctx context.Context, root, scope string,credentials.GitUserName = inv.GitUserNamecredentials.GitUserEmail = inv.GitUserEmail}- result, err := d.workspaceTerminals.HandleSandbox(ctx, runtime.WithSandboxCredentials(sb, credentials), scope, *request.Terminal, release)+ result, err := d.workspaceTerminals.HandleSandboxWithGitSSH(ctx, runtime.WithSandboxCredentials(sb, credentials), scope, *request.Terminal, release, request.TerminalGitSSHKeys)if err != nil {release()}diff --git a/internal/runtime/git_ssh.go b/internal/runtime/git_ssh.gonew file mode 100644index 00000000..eafd2dea--- /dev/null+++ b/internal/runtime/git_ssh.go@@ -0,0 +1,87 @@+package runtime++import (+ "os"+ "path/filepath"+ "slices"++ "agentflow/internal/gitwork"+)++// BindGitSSH keeps the SSH agent alive for exactly one command. Only the+// public configuration and socket are visible in the sandbox's control dir.+func BindGitSSH(sandbox Sandbox, workspace string, environment map[string]string, keys map[string]string) (func(), error) {+ if len(keys) == 0 {+ return func() {}, nil+ }+ root, err := EnsureControlDirectory(workspace, "runtime")+ if err != nil {+ return nil, err+ }+ clientRoot := ""+ if sandboxDriver(sandbox) == "docker" {+ clientRoot = "/workspace/.agentflow/runtime"+ }+ environment["GIT_ALLOW_PROTOCOL"] = gitwork.AllowedProtocols+ return gitwork.StartSSH(environment, keys, root, clientRoot)+}++func bindCommandGitSSH(sandbox Sandbox, workspace string, command CommandSpec, credentials RunCredentials) (func(), error) {+ if !slices.Contains(command.CredentialBindings, BindGit) {+ return func() {}, nil+ }+ return BindGitSSH(sandbox, filepath.Clean(workspace), command.environment, credentials.GitSSHKeys)+}++// terminalGitSSHUnavailable is the GIT_SSH_COMMAND of a terminal whose sandbox+// cannot keep the requester's SSH agent private to that one terminal.+const terminalGitSSHUnavailable = `sh -c 'echo "当前工作区环境无法把个人 Git SSH 密钥只开放给这个终端,终端内不能直接用 SSH 访问仓库;请使用平台的提交/推送" >&2; exit 1' --`++// BindTerminalGitSSH gives one interactive terminal its requester's SSH+// identity. Unlike BindGitSSH, the agent socket never lives in the workspace:+// the workspace is shared by every terminal and Agent of the run, all running+// as the same uid, so a socket there would let anyone sign as the requester.+//+// - bwrap: the session lives in a fresh 0700 directory under the host /tmp.+// Every bwrap process gets its own tmpfs /tmp, and only this terminal's+// process binds the directory back in.+// - local: no filesystem isolation exists; the session at least stays+// outside the workspace in a 0700 directory.+// - docker, seatbelt and anything else share one filesystem view among all+// processes of the workspace, so the requester's key is not offered and+// SSH remotes fail with a hint to use the platform's submit/push.+func BindTerminalGitSSH(sandbox Sandbox, command *CommandSpec, keys map[string]string) (func(), error) {+ if len(keys) == 0 {+ return func() {}, nil+ }+ if command.environment == nil {+ command.environment = map[string]string{}+ }+ command.environment["GIT_ALLOW_PROTOCOL"] = gitwork.AllowedProtocols+ driver := sandboxDriver(sandbox)+ if driver != "bwrap" && driver != "local" {+ command.environment["GIT_SSH_VARIANT"] = "ssh"+ command.environment["GIT_SSH_COMMAND"] = terminalGitSSHUnavailable+ return func() {}, nil+ }+ root, err := os.MkdirTemp("/tmp", "lf-term-ssh-")+ if err != nil {+ return nil, err+ }+ if err := os.Chmod(root, 0o700); err != nil {+ _ = os.RemoveAll(root)+ return nil, err+ }+ stop, err := gitwork.StartSSH(command.environment, keys, root, "")+ if err != nil {+ _ = os.RemoveAll(root)+ return nil, err+ }+ if driver == "bwrap" {+ command.privateBinds = append(command.privateBinds, root)+ }+ return func() {+ stop()+ _ = os.RemoveAll(root)+ }, nil+}diff --git a/internal/runtime/git_ssh_terminal_test.go b/internal/runtime/git_ssh_terminal_test.gonew file mode 100644index 00000000..82d7ace2--- /dev/null+++ b/internal/runtime/git_ssh_terminal_test.go@@ -0,0 +1,143 @@+package runtime++import (+ "crypto/ed25519"+ "crypto/rand"+ "encoding/pem"+ "os"+ "path/filepath"+ "slices"+ "strings"+ "testing"++ "agentflow/internal/gitwork"++ "golang.org/x/crypto/ssh"+)++func terminalSSHTestKeys(t *testing.T) map[string]string {+ t.Helper()+ _, identity, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ block, err := ssh.MarshalPrivateKey(identity, "terminal test")+ if err != nil {+ t.Fatal(err)+ }+ hostPublic, _, err := ed25519.GenerateKey(rand.Reader)+ if err != nil {+ t.Fatal(err)+ }+ hostKey, err := ssh.NewPublicKey(hostPublic)+ if err != nil {+ t.Fatal(err)+ }+ knownHosts := filepath.Join(t.TempDir(), "known_hosts")+ if err := os.WriteFile(knownHosts, []byte("git.example.org "+string(ssh.MarshalAuthorizedKey(hostKey))), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv(gitwork.SSHKnownHostsEnv, knownHosts)+ return map[string]string{"[email protected]:team/app.git": string(pem.EncodeToMemory(block))}+}++// The requester's agent must never be reachable through the shared workspace.+func TestTerminalGitSSHAgentStaysOutOfWorkspace(t *testing.T) {+ keys := terminalSSHTestKeys(t)+ for _, driver := range []string{"local", "bwrap"} {+ t.Run(driver, func(t *testing.T) {+ workspace := t.TempDir()+ var sb Sandbox = &localSandbox{workspace: workspace, environment: map[string]string{}}+ if driver == "bwrap" {+ sb = &processSandbox{workspace: workspace, driver: "bwrap"}+ }+ command := CommandSpec{environment: map[string]string{}}+ stop, err := BindTerminalGitSSH(sb, &command, keys)+ if err != nil {+ t.Fatal(err)+ }+ sockets, _ := filepath.Glob(filepath.Join("/tmp", "lf-term-ssh-*", "lf-ssh-*", "agent"))+ var session string+ for _, socket := range sockets {+ if strings.Contains(command.environment["GIT_SSH_COMMAND"], filepath.Dir(socket)) {+ session = filepath.Dir(filepath.Dir(socket))+ }+ }+ if session == "" {+ t.Fatalf("terminal agent socket not found for %q", command.environment["GIT_SSH_COMMAND"])+ }+ if info, err := os.Stat(session); err != nil || info.Mode().Perm() != 0o700 {+ t.Fatalf("session directory mode: %v %v", info, err)+ }+ if strings.HasPrefix(session, workspace) || strings.Contains(command.environment["GIT_SSH_COMMAND"], workspace) {+ t.Fatalf("terminal agent lives in the workspace: %s", command.environment["GIT_SSH_COMMAND"])+ }+ var found []string+ _ = filepath.Walk(workspace, func(path string, info os.FileInfo, err error) error {+ if err == nil && info.Mode()&os.ModeSocket != 0 {+ found = append(found, path)+ }+ return nil+ })+ if len(found) != 0 {+ t.Fatalf("sockets in the workspace: %v", found)+ }+ wantBinds := []string(nil)+ if driver == "bwrap" {+ wantBinds = []string{session}+ }+ if !slices.Equal(command.privateBinds, wantBinds) {+ t.Fatalf("private binds = %v, want %v", command.privateBinds, wantBinds)+ }+ stop()+ if _, err := os.Stat(session); !os.IsNotExist(err) {+ t.Fatalf("session directory left behind: %v", err)+ }+ })+ }+}++// Only the terminal that owns the agent binds it back over its private /tmp;+// every other bwrap process of the workspace sees an empty tmpfs there.+func TestBwrapPrivateBindsReachOnlyTheirProcess(t *testing.T) {+ workspace := t.TempDir()+ base, err := bwrapArgsCommand(workspace, SandboxRequirements{}, false)+ if err != nil {+ t.Fatal(err)+ }+ owner := bwrapPrivateBinds(base, []string{"/tmp/lf-term-ssh-1"})+ if owner[len(owner)-1] != "--" || !slices.Equal(owner[len(owner)-4:len(owner)-1], []string{"--bind", "/tmp/lf-term-ssh-1", "/tmp/lf-term-ssh-1"}) {+ t.Fatalf("owner args: %q", owner)+ }+ if tmpfs, bind := slices.Index(owner, "/tmp"), slices.Index(owner, "/tmp/lf-term-ssh-1"); tmpfs < 0 || bind < tmpfs {+ t.Fatalf("private bind must follow --tmpfs /tmp: %q", owner)+ }+ other := bwrapPrivateBinds(base, nil)+ if slices.Contains(other, "/tmp/lf-term-ssh-1") {+ t.Fatalf("another process got the terminal's agent: %q", other)+ }+}++// Docker and seatbelt share one filesystem view among every process of the+// workspace, so the requester's key is not offered at all.+func TestTerminalGitSSHWithoutPrivateFilesystemOffersNoKey(t *testing.T) {+ keys := terminalSSHTestKeys(t)+ for _, sb := range []Sandbox{&dockerSandbox{workspace: t.TempDir()}, &processSandbox{workspace: t.TempDir(), driver: "seatbelt"}} {+ before, _ := filepath.Glob("/tmp/lf-term-ssh-*")+ command := CommandSpec{environment: map[string]string{}}+ stop, err := BindTerminalGitSSH(sb, &command, keys)+ if err != nil {+ t.Fatal(err)+ }+ stop()+ after, _ := filepath.Glob("/tmp/lf-term-ssh-*")+ if command.environment["GIT_SSH_COMMAND"] != terminalGitSSHUnavailable || len(command.privateBinds) != 0 || len(after) != len(before) {+ t.Fatalf("%s offered a key: env=%v binds=%v", sandboxDriver(sb), command.environment, command.privateBinds)+ }+ for key, value := range command.environment {+ if strings.HasPrefix(key, "GIT_CONFIG_") || strings.Contains(value, "BEGIN") {+ t.Fatalf("%s leaked SSH configuration %s=%s", sandboxDriver(sb), key, value)+ }+ }+ }+}diff --git a/internal/runtime/platform_mcp.go b/internal/runtime/platform_mcp.goindex b1a014c4..a8233d48 100644--- a/internal/runtime/platform_mcp.go+++ b/internal/runtime/platform_mcp.go@@ -18,6 +18,8 @@ type MCPTarget struct {// token. Agent invocations require it; scripts and gates bind// opportunistically.RequireCredentials bool+ // SSH-only workflows can deliver branches without GitHub API access.+ SSHRepositoriesOnly bool}// PrepareMCPServers is the single place that turns a resolved asset bundle@@ -26,6 +28,17 @@ type MCPTarget struct {// returned warnings name servers that had to be dropped.func PrepareMCPServers(assets domain.AgentAssetBundle, target MCPTarget) (domain.AgentAssetBundle, []string, error) {var warnings []string+ if target.SSHRepositoriesOnly && strings.TrimSpace(target.GitToken) == "" {+ servers := assets.MCPServers+ assets.MCPServers = nil+ for _, server := range servers {+ if server.AuthType == "github-token" {+ warnings = append(warnings, "Git SSH 仓库可直接推送分支;未配置 GitHub Token,已跳过 "+server.ID)+ continue+ }+ assets.MCPServers = append(assets.MCPServers, server)+ }+ }var githubErr errorassets, githubErr = BindGitHubMCPHeaders(assets, target.GitToken, target.RequireCredentials)if githubErr != nil {diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.goindex d12cdc4d..4b3c7e9c 100644--- a/internal/runtime/runtime.go+++ b/internal/runtime/runtime.go@@ -45,6 +45,7 @@ type RunCredentials struct {ClaudeCode ProviderCredentialAgentCLI map[string]ProviderCredentialGitToken string+ GitSSHKeys map[string]string `json:"-"`GitUserName stringGitUserEmail stringMCPServers []domain.MCPServerDefinition@@ -86,6 +87,9 @@ type CommandSpec struct {// Codex chat uses it for the app-server JSON-RPC session.Stdin io.Readerenvironment map[string]string+ // privateBinds are host directories bwrap binds into this one process+ // only (for example a terminal's own SSH agent).+ privateBinds []string}// WithPrivateHomeDir keeps CodeBuddy/Claude isolated from the operator HOMEdiff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.goindex 308206bc..69067d12 100644--- a/internal/runtime/sandbox_docker.go+++ b/internal/runtime/sandbox_docker.go@@ -820,7 +820,7 @@ func isolatedRuntimeImage(dockerfile domain.DockerfileDefinition) string {// IsolatedDockerfile matches the public "generic-backend" environment so both// share one cached image.-const IsolatedDockerfile = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n"+const IsolatedDockerfile = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n"// PrebuildIsolatedImage warms the shared sandbox image in the background so// the first SOP on a fresh container install does not wait for the build.diff --git a/internal/runtime/sandbox_local.go b/internal/runtime/sandbox_local.goindex 739987d7..d1a3dc8c 100644--- a/internal/runtime/sandbox_local.go+++ b/internal/runtime/sandbox_local.go@@ -88,5 +88,10 @@ func ExecuteLocalCommand(ctx context.Context, workspace string, command CommandSif err != nil {return "", err}+ stopSSH, err := bindCommandGitSSH(sandbox, workspace, bound, credentials)+ if err != nil {+ return "", err+ }+ defer stopSSH()return sandbox.Exec(ctx, bound, sink)}diff --git a/internal/runtime/sandbox_manager.go b/internal/runtime/sandbox_manager.goindex 62058b7e..7fca4fb3 100644--- a/internal/runtime/sandbox_manager.go+++ b/internal/runtime/sandbox_manager.go@@ -433,5 +433,10 @@ func (s *managedSandbox) Exec(ctx context.Context, command CommandSpec, sink Eveif err != nil {return "", err}+ cleanup, err := bindCommandGitSSH(s.Sandbox, s.workspace, bound, credentials)+ if err != nil {+ return "", err+ }+ defer cleanup()return s.Sandbox.Exec(ctx, bound, sink)}diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.goindex 272318bc..3b244bb4 100644--- a/internal/runtime/sandbox_process.go+++ b/internal/runtime/sandbox_process.go@@ -163,6 +163,10 @@ func controlledBaseEnvironment(base []string) []string {"GIT_CONFIG_VALUE_","GIT_ASKPASS=","SSH_ASKPASS=",+ "SSH_AUTH_SOCK=",+ "GIT_SSH=",+ "GIT_SSH_COMMAND=",+ "GIT_SSH_VARIANT=",}filtered := make([]string, 0, len(base))for _, entry := range base {@@ -244,6 +248,7 @@ func (s *processSandbox) command(ctx context.Context, command CommandSpec, baseif err != nil {return nil, err}+ args = bwrapPrivateBinds(args, command.privateBinds)args = append(args, command.Argv...)cmd = exec.CommandContext(ctx, s.binary, args...)default:@@ -412,6 +417,20 @@ func bwrapArgsRequirements(workspace string, requirements SandboxRequirements) (return bwrapArgsCommand(workspace, requirements, true)}+// bwrapPrivateBinds adds per-process binds before the "--" that ends the+// bwrap options. They come after --tmpfs /tmp, so a directory under the host+// /tmp is visible to this process only.+func bwrapPrivateBinds(args, binds []string) []string {+ if len(binds) == 0 || len(args) == 0 || args[len(args)-1] != "--" {+ return args+ }+ out := append([]string{}, args[:len(args)-1]...)+ for _, dir := range binds {+ out = append(out, "--bind", dir, dir)+ }+ return append(out, "--")+}+func bwrapArgsCommand(workspace string, requirements SandboxRequirements, maskAgentConfig bool) ([]string, error) {root, err := filepath.Abs(workspace)if err != nil {diff --git a/internal/runtime/workspace_terminal.go b/internal/runtime/workspace_terminal.goindex 6b2ca720..5670a613 100644--- a/internal/runtime/workspace_terminal.go+++ b/internal/runtime/workspace_terminal.go@@ -68,17 +68,37 @@ func (p *TerminalPool) Handle(root, scope string, req domain.WorkspaceTerminalRe// On a failed open release is NOT called; the caller still owns that cleanup.// Non-open operations do not need a sandbox and ignore release.func (p *TerminalPool) HandleSandbox(ctx context.Context, sandbox Sandbox, scope string, req domain.WorkspaceTerminalRequest, release func()) (TerminalResult, error) {+ return p.HandleSandboxWithGitSSH(ctx, sandbox, scope, req, release, nil)+}++// HandleSandboxWithGitSSH gives the terminal its caller's SSH identity when the+// sandbox can keep it private to this terminal (see BindTerminalGitSSH). The+// pool owns the agent for the same lifetime as the terminal, including expiry.+func (p *TerminalPool) HandleSandboxWithGitSSH(ctx context.Context, sandbox Sandbox, scope string, req domain.WorkspaceTerminalRequest, release func(), keys map[string]string) (TerminalResult, error) {if req.Operation != "open" {return p.handle(scope, req, nil, nil)}if _, err := terminalTTL(req); err != nil {return TerminalResult{}, err}- cmd, home, err := sandboxTerminalCommand(ctx, sandbox)+ stopSSH := func() {}+ var bind func(*CommandSpec) error+ if len(keys) > 0 && sandbox != nil {+ bind = func(command *CommandSpec) error {+ stop, err := BindTerminalGitSSH(sandbox, command, keys)+ if err == nil {+ stopSSH = stop+ }+ return err+ }+ }+ cmd, home, err := sandboxTerminalCommandWithBinding(ctx, sandbox, bind)if err != nil {+ stopSSH()return TerminalResult{}, err}ownedRelease := func() {+ stopSSH()sandboxTerminalCleanup(sandbox, home)if release != nil {release()@@ -86,6 +106,7 @@ func (p *TerminalPool) HandleSandbox(ctx context.Context, sandbox Sandbox, scope}result, err := p.handle(scope, req, ownedRelease, func() (*exec.Cmd, string, error) { return cmd, home, nil })if err != nil {+ stopSSH()sandboxTerminalCleanup(sandbox, home)_ = removeTerminalHome(home)}diff --git a/internal/runtime/workspace_terminal_sandbox.go b/internal/runtime/workspace_terminal_sandbox.goindex ce76e199..54970a26 100644--- a/internal/runtime/workspace_terminal_sandbox.go+++ b/internal/runtime/workspace_terminal_sandbox.go@@ -44,6 +44,10 @@ exec "$SHELL" -i// sandboxTerminalCommand deliberately supports only concrete platform drivers.// An unknown Sandbox must fail closed instead of silently opening a host shell.func sandboxTerminalCommand(ctx context.Context, sandbox Sandbox) (*exec.Cmd, string, error) {+ return sandboxTerminalCommandWithBinding(ctx, sandbox, nil)+}++func sandboxTerminalCommandWithBinding(ctx context.Context, sandbox Sandbox, bind func(*CommandSpec) error) (*exec.Cmd, string, error) {if sandbox == nil {return nil, "", fmt.Errorf("工作区执行环境不可用")}@@ -78,7 +82,7 @@ func sandboxTerminalCommand(ctx context.Context, sandbox Sandbox) (*exec.Cmd, stprintf '%s\n' "$$" > "$HOME/.terminal-pid" || exit` + terminalShellLaunch}- cmd, err := sandboxTerminalCommandBound(ctx, sandbox, command, terminalBaseEnvironment(home))+ cmd, err := sandboxTerminalCommandBound(ctx, sandbox, command, terminalBaseEnvironment(home), bind)if err != nil {_ = removeTerminalHome(home)return nil, "", err@@ -90,12 +94,11 @@ printf '%s\n' "$$" > "$HOME/.terminal-pid" || exitreturn cmd, home, nil}-func sandboxTerminalCommandBound(ctx context.Context, sandbox Sandbox, command CommandSpec, base []string) (*exec.Cmd, error) {+func sandboxTerminalCommandBound(ctx context.Context, sandbox Sandbox, command CommandSpec, base []string, bind func(*CommandSpec) error) (*exec.Cmd, error) {// A terminal is user-directed and needs the run's Git binding, never its model// provider keys. Overlay variables are the same explicit sandbox configuration// that SOP commands receive; unrelated server environment is not inherited.- switch s := sandbox.(type) {- case *managedSandbox:+ if s, ok := sandbox.(*managedSandbox); ok {s.credentialsMu.RLock()credentials := s.credentialss.credentialsMu.RUnlock()@@ -104,7 +107,14 @@ func sandboxTerminalCommandBound(ctx context.Context, sandbox Sandbox, command Cif err != nil {return nil, err}- return sandboxTerminalCommandBound(ctx, s.Sandbox, bound, base)+ return sandboxTerminalCommandBound(ctx, s.Sandbox, bound, base, bind)+ }+ if bind != nil {+ if err := bind(&command); err != nil {+ return nil, err+ }+ }+ switch s := sandbox.(type) {case *localSandbox:return s.command(context.Background(), command, base)case *processSandbox:diff --git a/migrations/028_git_ssh_credentials.sql b/migrations/028_git_ssh_credentials.sqlnew file mode 100644index 00000000..0b16e815--- /dev/null+++ b/migrations/028_git_ssh_credentials.sql@@ -0,0 +1,10 @@+-- One personal Git SSH key per host and port. Private keys are never shared+-- through repository configuration or returned by the credential API.+CREATE TABLE IF NOT EXISTS user_git_ssh_keys (+ user_id BIGINT NOT NULL,+ id VARCHAR(64) NOT NULL,+ name VARCHAR(80) NOT NULL,+ host TEXT NOT NULL,+ private_key TEXT NOT NULL,+ PRIMARY KEY (user_id, id)+);diff --git a/web/app.js b/web/app.jsindex 239a0bd3..3caa56f3 100644--- a/web/app.js+++ b/web/app.js@@ -1547,7 +1547,7 @@ function mountNativeChat(){}).catch(()=>{});}if(message.type==='agentflow-chat-open-view'&&['settings','runners','sops','projects','runs','agents','environments','dockerfiles','sandboxes','flow','mcp'].includes(message.view)){- if(message.view==='settings'&&CREDENTIAL_FIELDS[message.credential])gotoCredential(message.credential);+ if(message.view==='settings'&&CREDENTIAL_FIELDS[message.credential])gotoCredential(message.credential,message.sshRemote);else if(message.view==='sandboxes'&&message.action==='create')createConversationSandbox(message.projectId).catch(error=>toast(error.message));else if(message.view==='runs'&&/^run-[\w-]+$/.test(message.runId||''))location.hash='#/runs/'+encodeURIComponent(message.runId);else switchView(message.view);diff --git a/web/app/access.js b/web/app/access.jsindex 5fcfe8ee..15635d4c 100644--- a/web/app/access.js+++ b/web/app/access.js@@ -37,9 +37,10 @@ function accessPublicBaseURL(configured, page){}function accessViewActive(){return !!$('#guideView')?.classList.contains('active')}let credentialFocusRequest=0;-function gotoCredential(name){+function gotoCredential(name,sshRemote){const request=++credentialFocusRequest;if(!CREDENTIAL_FIELDS[name]){switchView('settings');return}+ if(name==='gitSshKey')return openGitSSHKeys(sshRemote);switchView('settings');const requestedRoute=settingsRouteTransition;const focusAfter=performance.now()+150;@@ -64,11 +65,12 @@ function gotoCredential(name){}// 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'};+const CREDENTIAL_FIELDS={codeBuddyApiKey:'CodeBuddy API Key',codexApiKey:'Codex API Key',claudeCodeApiKey:'Claude Code API Key',gitToken:'GitHub Git Token',gitSshKey:'Git SSH 密钥'};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],['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/git-ssh-keys.js b/web/app/git-ssh-keys.jsnew file mode 100644index 00000000..8db7e8b3--- /dev/null+++ b/web/app/git-ssh-keys.js@@ -0,0 +1,212 @@+let gitSSHKeyCache = null;++function loadGitSSHKeys(refresh = false) {+ const userId = state.currentUser?.id;+ if (!userId || state.currentUser.isGuest) return Promise.resolve([]);+ if (!gitSSHKeyCache || gitSSHKeyCache.userId !== userId) gitSSHKeyCache = {userId, keys:null, pending:null};+ const cache = gitSSHKeyCache;+ if (cache.pending) return cache.pending;+ if (!refresh && cache.keys) return Promise.resolve(cache.keys);+ cache.pending = api(`/api/users/${encodeURIComponent(userId)}/git-ssh-keys`, {silent:true})+ .then(keys => cache.keys = Array.isArray(keys) ? keys : [])+ .finally(() => { cache.pending = null; });+ return cache.pending;+}++async function renderGitSSHMissingHint(element, remote) {+ if (!element) return;+ const version = element.sshHintVersion = (element.sshHintVersion || 0) + 1;+ const userId = state.currentUser?.id;+ element.hidden = true;+ element.textContent = '';+ if (remote?.provider !== 'ssh') return;+ try {+ const keys = await loadGitSSHKeys();+ if (element.sshHintVersion !== version || state.currentUser?.id !== userId) return;+ if (keys.some(key => globalThis.LoopForgeGitSSHHost(key.host) === remote.host)) return;+ element.textContent = window.lfT?.(+ `尚未配置 ${remote.host} 的 SSH 密钥,可稍后在「个人配置 → Git SSH 密钥」添加。`,+ `No SSH key configured for ${remote.host}. You can add one later in Personal settings → Git SSH keys.`,+ ) || `尚未配置 ${remote.host} 的 SSH 密钥,可稍后在「个人配置 → Git SSH 密钥」添加。`;+ } catch {+ if (element.sshHintVersion !== version || state.currentUser?.id !== userId) return;+ element.textContent = '无法读取 SSH 密钥配置,请稍后重试。';+ }+ element.hidden = false;+}++function refreshGitSSHWarnings() {+ if (repoDrawerOpen()) syncRepoDrawerDetect();+ if ($('#repositoryModal')?.classList.contains('open')) renderRepositoryCredentialHint();+}++window.addEventListener('focus', () => {+ gitSSHKeyCache = null;+ refreshGitSSHWarnings();+});++function openGitSSHKeys(remote = '') {+ const user = state.currentUser;+ if (!user?.id || user.isGuest) return;++ const previous = $('#gitSSHKeyDialog');+ if (previous?.open) return;+ const opener = document.activeElement;+ const repository = globalThis.LoopForgeGitSSH?.(remote);+ const endpoint = `/api/users/${encodeURIComponent(user.id)}/git-ssh-keys`;+ let keys = [];+ let editing = null;+ let deleting = '';+ let busy = false;++ const dialog = document.createElement('dialog');+ dialog.id = 'gitSSHKeyDialog';+ dialog.className = 'git-ssh-dialog';+ dialog.setAttribute('aria-labelledby', 'gitSSHKeyTitle');+ dialog.innerHTML = `+ <header class="git-ssh-dialog-head">+ <h2 id="gitSSHKeyTitle">Git SSH 密钥</h2>+ <button type="button" class="credential-btn ghost icon" data-ssh-key-close aria-label="关闭">${credentialGlyph('close', 16)}</button>+ </header>+ <p class="git-ssh-description">每个 SSH 主机配置一把个人密钥,同一主机的仓库自动共用。</p>+ <p class="git-ssh-status" role="status">正在读取密钥…</p>+ <div class="git-ssh-key-list"></div>+ <button type="button" class="credential-btn primary" data-ssh-key-add disabled>添加密钥</button>+ <form class="git-ssh-key-form" hidden>+ <h3></h3>+ ${credentialFieldHTML({label:'密钥名称', name:'name', type:'text', placeholder:'例如 GitLab 或 Gitea', hint:null})}+ ${credentialFieldHTML({label:'SSH 主机', name:'host', type:'text', placeholder:'gitlab.com 或 git.example.org:2222', hint:'不填写端口时使用 22。'})}+ ${credentialFieldHTML({label:'SSH 私钥', name:'privateKey', multiline:true, placeholder:'粘贴完整的 OpenSSH 或 PEM 私钥', hint:'把对应公钥添加到代码托管账号,并授予仓库访问权限。推送需要写权限。'})}+ <footer class="git-ssh-form-actions">+ <button type="button" class="credential-btn secondary" data-ssh-key-cancel>取消</button>+ <button type="submit" class="credential-btn primary">保存密钥</button>+ </footer>+ </form>`;++ const list = dialog.querySelector('.git-ssh-key-list');+ const status = dialog.querySelector('.git-ssh-status');+ const add = dialog.querySelector('[data-ssh-key-add]');+ const form = dialog.querySelector('form');+ const name = form.elements.namedItem('name');+ const host = form.elements.namedItem('host');+ const privateKey = form.elements.namedItem('privateKey');+ name.maxLength = 80;+ host.maxLength = 2048;+ name.required = host.required = true;++ function setStatus(message = '', error = false) {+ status.textContent = message;+ status.classList.toggle('is-error', error);+ status.hidden = !message;+ }++ function renderList() {+ list.innerHTML = keys.map(key => {+ const id = escapeHTML(key.id);+ return `<div class="git-ssh-key-row">+ <div class="git-ssh-key-summary"><b>${escapeHTML(key.name)}</b><small><code>${escapeHTML(key.host)}</code></small></div>+ ${deleting === key.id+ ? `<span>删除这把密钥?</span><button type="button" class="credential-btn ghost" data-ssh-key-keep>取消</button><button type="button" class="credential-btn danger-solid" data-ssh-key-remove="${id}">确认删除</button>`+ : `<button type="button" class="credential-btn ghost" data-ssh-key-edit="${id}">编辑</button><button type="button" class="credential-btn ghost" data-ssh-key-delete="${id}">删除</button>`}+ </div>`;+ }).join('');+ }++ function openForm(key, prefill) {+ editing = key;+ deleting = '';+ renderList();+ form.reset();+ form.hidden = false;+ add.hidden = true;+ form.querySelector('h3').textContent = key ? '编辑密钥' : '添加密钥';+ name.value = key?.name || prefill?.host || '';+ host.value = key?.host || prefill?.host || '';+ host.readOnly = !!key;+ privateKey.required = !key;+ privateKey.placeholder = key ? '留空保留现有私钥' : '粘贴完整的 OpenSSH 或 PEM 私钥';+ (prefill ? privateKey : name).focus();+ }++ function closeForm() {+ form.reset();+ form.hidden = true;+ add.hidden = false;+ editing = null;+ add.focus();+ }++ async function request(method, body, id) {+ if (busy) return;+ busy = true;+ dialog.setAttribute('aria-busy', 'true');+ const save = form.querySelector('button[type="submit"]');+ save.disabled = true;+ setStatus(method === 'PUT' ? '正在保存…' : '正在删除…');+ try {+ keys = await api(id ? `${endpoint}/${encodeURIComponent(id)}` : endpoint, {+ method, silent:true, ...(body ? {body:JSON.stringify(body)} : {}),+ });+ gitSSHKeyCache = {userId:user.id, keys, pending:null};+ storeCredentialUser({...credentialUser(), id:user.id, gitSshKeyConfigured:keys.length > 0});+ renderCredentialPanel();+ notifyCredentialsChanged();+ refreshGitSSHWarnings();+ deleting = '';+ renderList();+ if (method === 'PUT') closeForm();+ setStatus(method === 'PUT' ? '密钥已保存' : '密钥已删除');+ } catch (error) {+ setStatus(error.message, true);+ } finally {+ busy = false;+ save.disabled = false;+ dialog.removeAttribute('aria-busy');+ }+ }++ dialog.onclick = event => {+ const button = event.target.closest('button');+ if (!button || busy) return;+ const action = button.dataset;+ if ('sshKeyClose' in action) return dialog.close();+ if ('sshKeyCancel' in action) return closeForm();+ if ('sshKeyAdd' in action) return openForm(null, null);+ if (action.sshKeyEdit) return openForm(keys.find(key => key.id === action.sshKeyEdit), null);+ if (action.sshKeyRemove) return request('DELETE', null, action.sshKeyRemove);+ if (action.sshKeyDelete || 'sshKeyKeep' in action) {+ deleting = action.sshKeyDelete || '';+ renderList();+ const confirmation = list.querySelector('[data-ssh-key-remove]');+ (confirmation || add).focus();+ }+ };+ form.onsubmit = event => {+ event.preventDefault();+ return request('PUT', {id:editing?.id, name:name.value, host:host.value, privateKey:privateKey.value});+ };+ dialog.addEventListener('keydown', event => {+ if (event.key === 'Escape' || event.metaKey || event.ctrlKey) event.stopPropagation();+ });+ dialog.addEventListener('cancel', event => { if (busy) event.preventDefault(); });+ dialog.addEventListener('close', () => {+ form.reset();+ dialog.remove();+ if (opener?.isConnected) opener.focus({preventScroll:true});+ else $('#credentialPanel [data-credential-row="gitSshKey"] [data-credential-act="setup"]')?.focus({preventScroll:true});+ });+ document.body.append(dialog);+ dialog.showModal();+ hydrateCredentialIcons(dialog);+ loadGitSSHKeys(true).then(items => {+ if (!dialog.open) return;+ keys = items;+ add.disabled = false;+ setStatus(keys.length ? '' : '还没有配置 Git SSH 密钥');+ renderList();+ if (repository) {+ const existing = keys.find(key => globalThis.LoopForgeGitSSHHost(key.host) === repository.host);+ openForm(existing || null, repository);+ }+ }).catch(error => setStatus(error.message, true));+}diff --git a/web/app/git-ssh.js b/web/app/git-ssh.jsnew file mode 100644index 00000000..aad04bdf--- /dev/null+++ b/web/app/git-ssh.js@@ -0,0 +1,40 @@+// Canonicalize IPv6 spellings for comparisons with the server's host metadata.+globalThis.LoopForgeGitSSHHost = function normalizeSSHHost(endpoint) {+ const match = /^(\[[^\]]+\]|[^:]+):(\d+)$/.exec(String(endpoint || ''));+ if (!match) return '';+ let host = match[1].toLowerCase();+ if (host.startsWith('[')) {+ try { host = new URL(`http://${host}`).hostname; } catch { return ''; }+ }+ return `${host}:${Number(match[2])}`;+};++// Address preview only. The repository API validates and pins the SSH host.+globalThis.LoopForgeGitSSH = function parseSSHRepository(raw) {+ const address = String(raw || '').trim().replace(/^['"]|['"]$/g, '').replace(/^git clone /, '').replace(/^['"]|['"]$/g, '');+ if (!address || /[\s%?#\\]/.test(address)) return null;+ let user, host, port = '22', path, cloneUrl;+ if (address.startsWith('ssh://')) {+ const parsed = /^ssh:\/\/([^@]+)@(\[[^\]]+\]|[^:/]+)(?::(\d+))?(\/.+)$/.exec(address);+ if (!parsed) return null;+ [, user, host, , path] = parsed;+ if (parsed[3]) port = String(Number(parsed[3]));+ cloneUrl = `ssh://${user}@${host.toLowerCase()}:${port}${path}`;+ } else {+ const parsed = /^([^@]+)@(\[[^\]]+\]|[^:/]+):(.+)$/.exec(address);+ if (!parsed) return null;+ [, user, host, path] = parsed;+ cloneUrl = `${user}@${host.toLowerCase()}:${path}`;+ }+ if (!/^[a-z0-9_][a-z0-9_.-]*$/i.test(user) || !/^(?:[a-z0-9][a-z0-9.-]*|\[[a-f0-9:]+\])$/i.test(host) || host.includes('..') || Number(port) < 1 || Number(port) > 65535) return null;+ const segments = path.replace(/^\//, '').split('/');+ if (segments.some(segment => !/^[a-z0-9_.~-]+$/i.test(segment) || segment === '.' || segment === '..')) return null;+ const name = segments[segments.length - 1].replace(/\.git$/, '');+ if (!name) return null;+ const endpoint = globalThis.LoopForgeGitSSHHost(`${host}:${port}`);+ if (!endpoint) return null;+ // [email protected]: stays a GitHub repository (HTTPS + token, automatic PRs),+ // the same as on the server; only an explicit provider "ssh" uses SSH there.+ if (endpoint === 'github.com:22') return null;+ return { provider: 'ssh', host: endpoint, project: `${host.toLowerCase()}${port === '22' ? '' : ':' + port}/${segments.join('/')}`, name, cloneUrl, webUrl: '' };+};diff --git a/web/app/issues.js b/web/app/issues.jsindex 68724915..544368d9 100644--- a/web/app/issues.js+++ b/web/app/issues.js@@ -543,10 +543,11 @@ function issueFromForm(){// 工蜂链接(web / ssh / scp / 纯项目路径)解析成统一的仓库信息,让"粘一个链接"// 就能完成仓库配置。// repoDisplayPath shows host/path for a parsed repository, e.g. github.com/owner/name.-function repoDisplayPath(info,fallback=''){return info?.webUrl?String(info.webUrl).replace(/^https?:\/\//,''):String(fallback||'')}-function repoProviderLabel(info){return info?.provider==='github'?'GitHub':'工蜂'}+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 parseGongfengRepoURL(raw){- let publicURL=String(raw||'').trim().replace(/^git clone /,'').replace(/^github:/,'https://github.com/').replace(/^[email protected]:/,'https://github.com/');+ 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/');if(publicURL.startsWith('github.com/'))publicURL='https://'+publicURL;try{const u=new URL(publicURL);if(u.hostname==='github.com'&&!u.username&&!u.password&&['http:','https:'].includes(u.protocol)){const parts=u.pathname.split('/').filter(Boolean),owner=parts[0],name=(parts[1]||'').replace(/\.git$/,'');if(parts.length>=2&&/^[A-Za-z0-9_.-]+$/.test(owner)&&/^[A-Za-z0-9_.-]+$/.test(name)&&!['.','..'].includes(owner)&&!['.','..'].includes(name))return {project:'github:'+owner+'/'+name,name,webUrl:'https://github.com/'+owner+'/'+name,cloneUrl:'https://github.com/'+owner+'/'+name+'.git',provider:'github'}}}catch(_){}@@ -584,15 +585,22 @@ function parseGongfengRepoURL(raw){function fillRepositoryFromLink(url,fill){const info=parseGongfengRepoURL(url);if(!info)return false;- fill.gongfengProjectId=info.project;+ fill.gongfengProjectId=info.provider==='ssh'?'':info.project;if(!String(fill.name||'').trim())fill.name=info.name;- fill.webUrl=info.webUrl;+ fill.webUrl=info.provider==='ssh'&&fill.cloneUrl===info.cloneUrl?fill.webUrl:info.webUrl;fill.cloneUrl=info.cloneUrl;return true;}function renderRepositoryCredentialHint(){const host=$('#repositoryCredentialHint');if(!host)return;- const configured=!!(userById(state.currentUser?.id)||{}).gitTokenConfigured;+ const remote=parseGongfengRepoURL($('#repositoryForm')?.elements.repoUrl?.value),ssh=remote?.provider==='ssh',user=userById(state.currentUser?.id)||{};+ host.classList.toggle('git-ssh-missing',ssh);+ host.classList.toggle('repository-credential-hint',!ssh);+ if(ssh){host.setAttribute('role','alert');return renderGitSSHMissingHint(host,remote)}+ host.sshHintVersion=(host.sshHintVersion||0)+1;+ host.hidden=false;+ host.removeAttribute('role');+ const configured=!!user.gitTokenConfigured;const title=configured?'已配置 GitHub Token':'仓库可以先保存,代码任务还需要 Token';const message=configured?'请确认 Token 已获得目标仓库的访问和写入权限。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。':'使用仓库进行需求分析、访问私有代码或提交 PR 前,请先配置 GitHub Token。SOP 使用需求责任人的 Token,未指定时使用项目 Owner 的 Token。';host.dataset.configured=String(configured);@@ -601,11 +609,11 @@ function renderRepositoryCredentialHint(){$('#repositoryModal').classList.remove('open');gotoCredential('gitToken');};}-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 地址即可;集成分支用于检查多个 SOP 执行后是否存在合并冲突,可留空。`;$('#repositoryList').innerHTML=repos.map(r=>`<button type="button" data-edit-repo="${escapeHTML(r.id)}"><b>${escapeHTML(r.name)}</b><span>${escapeHTML(r.gongfengProjectId)} · 主分支 ${escapeHTML(r.defaultBranch||'master')} · 集成分支 ${escapeHTML(r.integrateBranch||'未配置')}</span><em>${project?.defaultRepositoryId===r.id?'默认仓库':'编辑'}</em></button>`).join('')||'<p>当前项目还没有绑定代码仓库。</p>';$('#repositoryList').querySelectorAll('[data-edit-repo]').forEach(b=>b.onclick=()=>fillRepositoryForm((state.data.repositories||[]).find(r=>r.id===b.dataset.editRepo)))}-function fillRepositoryForm(repo={}){const f=$('#repositoryForm');['id','name','gongfengProjectId','webUrl','cloneUrl','localPath'].forEach(k=>{if(f.elements[k])f.elements[k].value=repo[k]||''});if(f.elements.repoUrl)f.elements.repoUrl.value=repo.webUrl||repo.cloneUrl||repo.gongfengProjectId||'';- const nameField=$('#repositoryNameField');if(nameField)nameField.hidden=!repo.id;f.elements.defaultBranch.value=repo.defaultBranch||'master';f.elements.integrateBranch.value=repo.integrateBranch||'';const project=(state.data.projects||[]).find(p=>p.id===state.projectFilter);f.elements.makeDefault.checked=!project?.defaultRepositoryId||project.defaultRepositoryId===repo.id;if(f.elements.repoUrl)f.elements.repoUrl.onchange=()=>{const form=f.elements,fill={name:form.name.value,gongfengProjectId:form.gongfengProjectId.value,webUrl:form.webUrl.value,cloneUrl:form.cloneUrl.value};if(fillRepositoryFromLink(form.repoUrl.value,fill)){form.name.value=fill.name;form.gongfengProjectId.value=fill.gongfengProjectId;form.webUrl.value=fill.webUrl;form.cloneUrl.value=fill.cloneUrl}}}-function openRepositoryModal(){if(!state.projectFilter)return toast('请先选择项目');fillRepositoryForm();renderRepositoryList();$('#repositoryModal').classList.add('open')}-async function saveRepository(e){e.preventDefault();const f=e.currentTarget,project=(state.data.projects||[]).find(p=>p.id===state.projectFilter);if(f.elements.repoUrl){const fill={name:f.elements.name.value,gongfengProjectId:f.elements.gongfengProjectId.value,webUrl:f.elements.webUrl.value,cloneUrl:f.elements.cloneUrl.value};if(fillRepositoryFromLink(f.elements.repoUrl.value,fill)){f.elements.name.value=fill.name;f.elements.gongfengProjectId.value=fill.gongfengProjectId;f.elements.webUrl.value=fill.webUrl;f.elements.cloneUrl.value=fill.cloneUrl}}const payload={id:f.elements.id.value,projectId:state.projectFilter,provider:(parseGongfengRepoURL(f.elements.repoUrl?.value)?.provider||'gongfeng'),name:f.elements.name.value.trim(),gongfengProjectId:f.elements.gongfengProjectId.value.trim(),webUrl:f.elements.webUrl.value.trim(),cloneUrl:f.elements.cloneUrl.value.trim(),defaultBranch:f.elements.defaultBranch.value.trim(),integrateBranch:f.elements.integrateBranch.value.trim(),localPath:f.elements.localPath.value.trim(),repoUrl:f.elements.repoUrl?f.elements.repoUrl.value.trim():''};try{const repo=await api('/api/repositories',{method:payload.id?'PUT':'POST',body:JSON.stringify(payload)}),idx=(state.data.repositories||[]).findIndex(r=>r.id===repo.id);if(idx>=0)state.data.repositories[idx]=repo;else(state.data.repositories||(state.data.repositories=[])).push(repo);if(f.elements.makeDefault.checked&&project){const saved=await api('/api/projects',{method:'PUT',body:JSON.stringify({...project,defaultRepositoryId:repo.id})});if(saved&&saved.id){const pi=(state.data.projects||[]).findIndex(p=>p.id===saved.id);if(pi>=0)state.data.projects[pi]=saved;project.defaultRepositoryId=repo.id}else project.defaultRepositoryId=repo.id}fillRepositoryForm(repo);renderRepositoryList();renderIssues();toast((userById(state.currentUser?.id)||{}).gitTokenConfigured?'Git 仓库绑定已保存':'仓库已保存;配置 GitHub Token 后才能进行代码交付。')}catch(err){toast(err.message)}}+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=>`<button type="button" data-edit-repo="${escapeHTML(r.id)}"><b>${escapeHTML(r.name)}</b><span>${escapeHTML(r.gongfengProjectId||r.cloneUrl)} · 主分支 ${escapeHTML(r.defaultBranch||'master')} · 集成分支 ${escapeHTML(r.integrateBranch||'未配置')}</span><em>${project?.defaultRepositoryId===r.id?'默认仓库':'编辑'}</em></button>`).join('')||'<p>当前项目还没有绑定代码仓库。</p>';$('#repositoryList').querySelectorAll('[data-edit-repo]').forEach(b=>b.onclick=()=>fillRepositoryForm((state.data.repositories||[]).find(r=>r.id===b.dataset.editRepo)))}+function fillRepositoryForm(repo={}){const f=$('#repositoryForm');['id','name','gongfengProjectId','webUrl','cloneUrl','localPath'].forEach(k=>{if(f.elements[k])f.elements[k].value=repo[k]||''});if(f.elements.repoUrl)f.elements.repoUrl.value=repo.provider==='ssh'?repo.cloneUrl:repo.webUrl||repo.cloneUrl||repo.gongfengProjectId||'';+ const nameField=$('#repositoryNameField');if(nameField)nameField.hidden=!repo.id;f.elements.defaultBranch.value=repo.defaultBranch||'master';f.elements.integrateBranch.value=repo.integrateBranch||'';const project=(state.data.projects||[]).find(p=>p.id===state.projectFilter);f.elements.makeDefault.checked=!project?.defaultRepositoryId||project.defaultRepositoryId===repo.id;if(f.elements.repoUrl){f.elements.repoUrl.oninput=renderRepositoryCredentialHint;f.elements.repoUrl.onchange=()=>{renderRepositoryCredentialHint();const form=f.elements,fill={name:form.name.value,gongfengProjectId:form.gongfengProjectId.value,webUrl:form.webUrl.value,cloneUrl:form.cloneUrl.value};if(fillRepositoryFromLink(form.repoUrl.value,fill)){form.name.value=fill.name;form.gongfengProjectId.value=fill.gongfengProjectId;form.webUrl.value=fill.webUrl;form.cloneUrl.value=fill.cloneUrl}}};renderRepositoryCredentialHint()}+function openRepositoryModal(){if(!state.projectFilter)return toast('请先选择项目');gitSSHKeyCache=null;fillRepositoryForm();renderRepositoryList();$('#repositoryModal').classList.add('open')}+async function saveRepository(e){e.preventDefault();const f=e.currentTarget,project=(state.data.projects||[]).find(p=>p.id===state.projectFilter);if(f.elements.repoUrl){const fill={name:f.elements.name.value,gongfengProjectId:f.elements.gongfengProjectId.value,webUrl:f.elements.webUrl.value,cloneUrl:f.elements.cloneUrl.value};if(fillRepositoryFromLink(f.elements.repoUrl.value,fill)){f.elements.name.value=fill.name;f.elements.gongfengProjectId.value=fill.gongfengProjectId;f.elements.webUrl.value=fill.webUrl;f.elements.cloneUrl.value=fill.cloneUrl}}const payload={id:f.elements.id.value,projectId:state.projectFilter,provider:(parseGongfengRepoURL(f.elements.repoUrl?.value)?.provider||'gongfeng'),name:f.elements.name.value.trim(),gongfengProjectId:f.elements.gongfengProjectId.value.trim(),webUrl:f.elements.webUrl.value.trim(),cloneUrl:f.elements.cloneUrl.value.trim(),defaultBranch:f.elements.defaultBranch.value.trim(),integrateBranch:f.elements.integrateBranch.value.trim(),localPath:f.elements.localPath.value.trim(),repoUrl:f.elements.repoUrl?f.elements.repoUrl.value.trim():''};try{const repo=await api('/api/repositories',{method:payload.id?'PUT':'POST',body:JSON.stringify(payload)}),idx=(state.data.repositories||[]).findIndex(r=>r.id===repo.id);if(idx>=0)state.data.repositories[idx]=repo;else(state.data.repositories||(state.data.repositories=[])).push(repo);if(f.elements.makeDefault.checked&&project){const saved=await api('/api/projects',{method:'PUT',body:JSON.stringify({...project,defaultRepositoryId:repo.id})});if(saved&&saved.id){const pi=(state.data.projects||[]).findIndex(p=>p.id===saved.id);if(pi>=0)state.data.projects[pi]=saved;project.defaultRepositoryId=repo.id}else project.defaultRepositoryId=repo.id}fillRepositoryForm(repo);renderRepositoryList();renderIssues();toast(repo.provider==='ssh'?'仓库已保存;检出和推送使用 Git SSH 密钥。':(userById(state.currentUser?.id)||{}).gitTokenConfigured?'Git 仓库绑定已保存':'仓库已保存;配置 GitHub Token 后才能进行代码交付。')}catch(err){toast(err.message)}}function fillImportTAPDWorkflow(){const select=$('#importTAPDWorkflow');if(!select)return;diff --git a/web/app/project-wizard.js b/web/app/project-wizard.jsindex 25530dd2..8c2ef2e5 100644--- a/web/app/project-wizard.js+++ b/web/app/project-wizard.js@@ -104,8 +104,8 @@ 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 仓库地址,请检查后重试':'请先粘贴 GitHub 仓库地址','repoUrl');- if(projectWizardRepos().some(r=>r.gongfengProjectId===info.project))return projectWizardFail(`仓库 ${info.project} 已经绑定到这个项目`,'repoUrl');+ if(!info)return projectWizardFail(url?'请输入 GitHub 链接或有效的 Git SSH 地址。CNB 只支持 HTTPS + 访问令牌。':'请先粘贴 GitHub 链接或 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);let defaultError='';@@ -244,19 +244,20 @@ function projectWizardBasicHTML(w){}function projectWizardRepoHint(url){const raw=String(url||'').trim(),info=raw?parseGongfengRepoURL(raw):null;- if(!raw)return '支持 https / ssh 地址,例如 https://github.com/owner/repo';- return info?`识别为 <b>${escapeHTML(info.name)}</b> · ${escapeHTML(repoDisplayPath(info,info.project))}`:'无法识别为 GitHub 仓库地址';+ if(!raw)return '例如 https://github.com/owner/repo 或 [email protected]:group/repo.git';+ if(info?.provider==='ssh')return `识别为 Git SSH · <b>${escapeHTML(info.name)}</b>。请管理员信任该主机,并在个人配置中添加 Git SSH 密钥。`;+ return info?`识别为 <b>${escapeHTML(info.name)}</b> · ${escapeHTML(repoDisplayPath(info,info.project))}`:'请输入 GitHub 链接或 Git SSH 地址';}function projectWizardReposHTML(w){const project=projectWizardProject()||{},repos=projectWizardRepos();- const list=repos.map(r=>{const path=r.gongfengProjectId||'',name=r.name||path||r.id,shown=repoDisplayPath(parseGongfengRepoURL(r.webUrl||r.cloneUrl||path),path);return `<div class="pw-repo" data-pw-repo="${escapeHTML(r.id)}"><span class="pw-repo-ic">${pwIcon('repo',14,1.9)}</span><b title="${escapeHTML(name)}">${escapeHTML(name)}</b><code title="${escapeHTML(shown)}">${escapeHTML(shown)}</code><small>${escapeHTML(r.defaultBranch||'main')}</small>${r.integrateBranch?`<small title="集成分支">${escapeHTML(r.integrateBranch)}</small>`:''}${r.id===project.defaultRepositoryId?'<small class="is-def">默认</small>':''}<button type="button" class="pw-repo-rm" data-pw-repo-remove="${escapeHTML(r.id)}" title="移除" aria-label="移除仓库 ${escapeHTML(name)}">${pwIcon('x',14)}</button></div>`}).join('');+ 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 `<div class="pw-repo" data-pw-repo="${escapeHTML(r.id)}"><span class="pw-repo-ic">${pwIcon('repo',14,1.9)}</span><b title="${escapeHTML(name)}">${escapeHTML(name)}</b><code title="${escapeHTML(shown)}">${escapeHTML(shown)}</code><small>${escapeHTML(r.defaultBranch||'main')}</small>${r.integrateBranch?`<small title="集成分支">${escapeHTML(r.integrateBranch)}</small>`:''}${r.id===project.defaultRepositoryId?'<small class="is-def">默认</small>':''}<button type="button" class="pw-repo-rm" data-pw-repo-remove="${escapeHTML(r.id)}" title="移除" aria-label="移除仓库 ${escapeHTML(name)}">${pwIcon('x',14)}</button></div>`}).join('');const body=(list?`<div class="pw-repo-list">${list}</div>`:'')+'<div data-github-repositories></div>'- +pwField('GitHub 仓库地址',`<input class="pw-input pw-mono" id="pwRepoUrl" name="repoUrl" value="${escapeHTML(w.repo.url)}" placeholder="https://github.com/owner/repo" spellcheck="false" autocomplete="off">`,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})+ +pwField('GitHub 链接或 Git SSH 地址',`<input class="pw-input pw-mono" id="pwRepoUrl" name="repoUrl" value="${escapeHTML(w.repo.url)}" placeholder="https://github.com/owner/repo" spellcheck="false" autocomplete="off">`,{for:'pwRepoUrl',hint:projectWizardRepoHint(w.repo.url),hintAttrs:' data-pw-repo-hint'})+`<div class="pw-row2">${pwField('主分支',`<input class="pw-input pw-mono" id="pwRepoBranch" name="repoBranch" value="${escapeHTML(w.repo.branch)}" placeholder="main" spellcheck="false">`,{for:'pwRepoBranch'})}${pwField('集成分支',`<input class="pw-input pw-mono" id="pwRepoIntegrate" name="repoIntegrate" value="${escapeHTML(w.repo.integrate)}" placeholder="可选" spellcheck="false">`,{for:'pwRepoIntegrate'})}</div>`+`<div><button type="button" class="pw-btn pw-btn-outline pw-btn-sm" data-pw-action="add-repo"${w.saving?' disabled':''}>+ 添加仓库</button></div>`;return projectWizardHeadHTML(w,'代码仓库','Agent 执行 SOP 时会克隆这些仓库并在工作分支上提交。第一个仓库会自动设为默认。')- +`<div class="pw-pane"><p class="pw-note is-ok">✓ 项目「${escapeHTML(project.name||'')}」已创建。仓库添加后立即生效,也可以先跳过。</p>${pwCard('绑定 GitHub 仓库','粘贴仓库地址,自动识别名称',pwPill(repos.length?`已绑定 ${repos.length} 个`:'未绑定',repos.length?'ok':''),body)}</div>`;+ +`<div class="pw-pane"><p class="pw-note is-ok">✓ 项目「${escapeHTML(project.name||'')}」已创建。仓库添加后立即生效,也可以先跳过。</p>${pwCard('绑定代码仓库','粘贴仓库地址,自动识别名称',pwPill(repos.length?`已绑定 ${repos.length} 个`:'未绑定',repos.length?'ok':''),body)}</div>`;}function projectWizardPeoplePill(d){const count=projectPeopleIds(d).length;return pwPill(`${count} 位`,count>1?'ok':'',' data-pw-people-pill')}function projectWizardMembersHTML(w){diff --git a/web/app/projects.js b/web/app/projects.jsindex 1cab865c..5982afa8 100644--- a/web/app/projects.js+++ b/web/app/projects.js@@ -159,7 +159,7 @@ function projectColorHTML(color){return `<div class="pa-swatches">${PROJECT_SWATCHES.map(c=>`<button type="button" class="pa-sw${c===String(cur).toLowerCase()?' on':''}" data-pa-color="${c}" style="background:${c};color:${c}" aria-label="品牌色 ${c}" aria-pressed="${c===String(cur).toLowerCase()}"></button>`).join('')}<label class="pa-sw pa-sw-custom${preset?'':' on'}" title="自定义颜色" style="color:${cur}${preset?'':`;background:${cur}`}"><input type="color" data-pa-color-custom value="${cur.length===7?cur:'#536dfe'}" aria-label="自定义品牌色"></label><code class="pa-sw-hex" data-pa-color-hex>${escapeHTML(String(cur).toUpperCase())}</code><input type="hidden" name="color" value="${escapeHTML(cur)}"></div>`;}function repoCardHTML(r,isDefault){- const info=parseGongfengRepoURL(r.webUrl||r.cloneUrl||r.gongfengProjectId||''),path=info?.project||r.gongfengProjectId||'',web=info?.webUrl||'',name=r.name||info?.name||path||r.id;+ const info=parseGongfengRepoURL(r.provider==='ssh'?r.cloneUrl:r.webUrl||r.cloneUrl||r.gongfengProjectId||''),path=info?.project||r.gongfengProjectId||'',web=r.provider==='ssh'?r.webUrl||'':info?.webUrl||'',name=r.name||info?.name||path||r.id;const updated=typeof knownTime==='function'?knownTime(r.updatedAt):null;return `<article class="pa-rc" data-repo-card="${escapeHTML(r.id)}"><div class="pa-rc-top"><span class="pa-rc-ic">${paIcon('repo',15)}</span><div class="pa-rc-m"><h4 title="${escapeHTML(name)}">${escapeHTML(name)}</h4><code title="${escapeHTML(repoDisplayPath(info,path))}">${escapeHTML(repoDisplayPath(info,path))}</code></div><div class="pa-rc-acts"><button type="button" class="pa-icon-btn" data-repo-edit="${escapeHTML(r.id)}" title="编辑" aria-label="编辑仓库 ${escapeHTML(name)}">${paIcon('edit')}</button><button type="button" class="pa-icon-btn danger" data-repo-delete="${escapeHTML(r.id)}" title="删除" aria-label="删除仓库 ${escapeHTML(name)}">${paIcon('trash')}</button></div></div>@@ -168,7 +168,7 @@ function repoCardHTML(r,isDefault){</article>`;}function projectRepoListHTML(repos,defaultId){- if(!repos.length)return projectAdminEmptyHTML('repo','还没有绑定代码仓库','绑定后,Agent 执行 SOP 时会自动克隆仓库并在工作分支上提交。第一个仓库会自动设为默认。',`<ol class="pa-steps"><li><span>1</span>粘贴 GitHub 仓库地址</li><li><span>2</span>确认分支</li><li><span>3</span>保存即生效</li></ol><button type="button" class="button primary" data-repo-add>+ 添加第一个仓库</button>`);+ if(!repos.length)return projectAdminEmptyHTML('repo','还没有绑定代码仓库','绑定后,Agent 执行 SOP 时会自动克隆仓库并在工作分支上提交。第一个仓库会自动设为默认。',`<ol class="pa-steps"><li><span>1</span>粘贴 GitHub 链接或 Git SSH 地址</li><li><span>2</span>确认分支</li><li><span>3</span>保存即生效</li></ol><button type="button" class="button primary" data-repo-add>+ 添加第一个仓库</button>`);return `<div class="pa-rgrid">${repos.map(r=>repoCardHTML(r,r.id===defaultId)).join('')}<button type="button" class="pa-rc-add" data-repo-add><i>${paIcon('plus',14)}</i><b>添加仓库</b></button></div>`;}function projectAdminFormHTML(d,ctx){diff --git a/web/app/repo_drawer.js b/web/app/repo_drawer.jsindex 158957c6..558a2e31 100644--- a/web/app/repo_drawer.js+++ b/web/app/repo_drawer.js@@ -11,6 +11,8 @@ function repoDrawerError(show){function syncRepoDrawerDetect(){const f=$('#repoDrawerForm');if(!f)return;const info=parseGongfengRepoURL(f.elements.repoUrl.value),box=$('#repoDrawerDetect');+ $('#repoDrawerSSH').hidden=info?.provider!=='ssh';+ renderGitSSHMissingHint($('#repoDrawerSSHMissing'),info);if(!info){box.hidden=true;return}repoDrawerError(false);if(!repoDrawerState.nameTouched)f.elements.name.value=info.name;@@ -26,10 +28,12 @@ function openRepoDrawer(repoId=''){if(repoId&&!repo)return toast('仓库不存在或已被删除','err');const f=$('#repoDrawerForm');if(!f)return;const hasDefault=!projectNeedsDefaultRepository(project);- const parsedName=parseGongfengRepoURL(repo?.webUrl||repo?.cloneUrl||repo?.gongfengProjectId||'')?.name||'';+ const repoAddress=repo?.provider==='ssh'?repo.cloneUrl:repo?.webUrl||repo?.cloneUrl||repo?.gongfengProjectId||'';+ const parsedName=parseGongfengRepoURL(repoAddress)?.name||'';Object.assign(repoDrawerState,{projectId,repoId:repo?.id||'',nameTouched:!!repo&&!!repo.name&&repo.name!==parsedName,saving:false,returnFocus:document.activeElement});f.elements.id.value=repo?.id||'';- f.elements.repoUrl.value=repo?(repo.webUrl||repo.cloneUrl||repo.gongfengProjectId||''):'';+ f.elements.repoUrl.value=repoAddress;+ f.elements.webUrl.value=repo?.provider==='ssh'?repo.webUrl||'':'';f.elements.name.value=repo?.name||'';f.elements.defaultBranch.value=repo?.defaultBranch||'main';f.elements.integrateBranch.value=repo?.integrateBranch||'';@@ -39,6 +43,7 @@ function openRepoDrawer(repoId=''){$('#repoDrawerTitle').textContent=repo?'编辑代码仓库':'添加代码仓库';$('#repoDrawerSave').disabled=false;setRepoDrawerSwitch(repo?project.defaultRepositoryId===repo.id:!hasDefault);+ gitSSHKeyCache=null;repoDrawerError(false);syncRepoDrawerDetect();const drawer=$('#repoDrawer');drawer.inert=false;drawer.setAttribute('aria-hidden','false');@@ -60,6 +65,7 @@ function closeRepoDrawer(opt){function repoDrawerPayload(f,info){const existing=(state.data.repositories||[]).find(r=>r.id===repoDrawerState.repoId)||{};const payload={...existing,id:existing.id||undefined,projectId:repoDrawerState.projectId,provider:info.provider||'gongfeng',name:f.elements.name.value.trim()||info.name,gongfengProjectId:info.project,webUrl:info.webUrl,cloneUrl:info.cloneUrl,defaultBranch:f.elements.defaultBranch.value.trim()||'main',integrateBranch:f.elements.integrateBranch.value.trim(),localPath:f.elements.localPath.value.trim(),repoUrl:f.elements.repoUrl.value.trim()};+ if(info.provider==='ssh'){payload.gongfengProjectId='';payload.webUrl=f.elements.webUrl.value.trim()}delete payload.gitToken;if(!payload.id)delete payload.id;return payload;}@@ -111,7 +117,7 @@ function bindRepoDrawer(){$$('[data-repo-drawer-close]').forEach(b=>b.onclick=closeRepoDrawer);$('#repoDrawerScrim').onclick=closeRepoDrawer;document.addEventListener('keydown',e=>{- if(e.key!=='Escape'||!repoDrawerOpen()||$('#confirmModal')?.classList.contains('open'))return;+ if(e.key!=='Escape'||!repoDrawerOpen()||$('#gitSSHKeyDialog')?.open||$('#confirmModal')?.classList.contains('open'))return;e.preventDefault();e.stopImmediatePropagation();closeRepoDrawer();},true);}diff --git a/web/app/workbench.js b/web/app/workbench.jsindex 2a7b57cd..b2c7b93f 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -62,6 +62,8 @@ const CREDENTIAL_KINDS=[guide:[['打开 GitHub「Settings → Developer settings → Personal access tokens」','https://github.com/settings/tokens','前往 GitHub 申请个人访问令牌'],['新建令牌,为目标仓库授予 <code>Contents</code> 和 <code>Pull requests</code> 的读写权限'],['复制令牌粘贴到下方,保存前会自动校验权限']],placeholder:'请输入个人访问令牌(PAT)',hint:'保存前会先校验令牌有效性与权限',impact:'依赖私有仓库的 SOP 将无法克隆或推送仓库。'},+ {key:'gitSshKey',group:'platform',name:'Git SSH',short:'Git SSH 密钥',icon:'key',+ use:'按 SSH 主机管理个人密钥,仓库自动匹配'},{key:'codeBuddyApiKey',group:'model',name:'CodeBuddy',short:'CodeBuddy API Key',logo:'codebuddy',use:'AI 对话与 SOP 的 CodeBuddy 执行器',description:'AI 对话(含 Claude、GPT 等模型)和 SOP 的 CodeBuddy 执行器都使用它;网络环境按账号所在环境配置。',@@ -299,7 +301,7 @@ function closeCredentialCatalogProbe(catalog){}async function probeCredentialCatalog(row,catalog,button){const kind=credentialKind(row.dataset.credentialRow),form=row.querySelector('.credential-editor-form'),panel=catalog.querySelector('[data-catalog-probe]');- const extra=form.querySelector('input[name="extra"]'),secret=form.querySelector('input[name="secret"]')?.value.trim()||'',protocol=form.querySelector('select[name="protocol"]')?.value;+ const extra=form.querySelector('input[name="extra"]'),secret=form.querySelector('[name="secret"]')?.value.trim()||'',protocol=form.querySelector('select[name="protocol"]')?.value;const extraError=extra?credentialExtraError(kind,extra.value,protocol):'';if(extraError){toast(extraError,'err');extra.focus();return}const token=(catalog.probeToken||0)+1;catalog.probeToken=token;catalog.probe=null;@@ -382,7 +384,7 @@ 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 `<svg class="agent-icon harness-icon${cls?' '+cls:''}" data-icon="${name}" width="${size}" height="${size}" aria-hidden="true" focusable="false"></svg>`}function credentialSpinner(size=14){return credentialGlyph('arc-spinner',size,'credential-spin')}-function credentialLogo(kind,cls=''){return `<span class="credential-logo${kind.monochrome?' monochrome':''}${cls?' '+cls:''}"><img src="/images/credentials/${kind.logo}.svg" alt=""></span>`}+function credentialLogo(kind,cls=''){return `<span class="credential-logo${kind.monochrome?' monochrome':''}${cls?' '+cls:''}">${kind.icon?credentialGlyph(kind.icon,18):`<img src="/images/credentials/${kind.logo}.svg" alt="">`}</span>`}function hydrateCredentialIcons(root){if(root)window.AgentFlowHarnessIcons?.hydrate?.(root)}function credentialNextKind(user){return CREDENTIAL_RECOMMENDED.map(credentialKind).find(kind=>!credentialConfigured(kind,user))||null}function credentialSecretError(kind,value){@@ -495,7 +497,8 @@ function credentialSubline(kind,user){}return use;}-function credentialFieldHTML({label,note='',name,type='password',value='',placeholder='',hint='',hintTone='',id=''}){+function credentialFieldHTML({label,note='',name,type='password',value='',placeholder='',hint='',hintTone='',id='',multiline=false}){+ if(multiline)return `<label class="credential-field"><span>${escapeHTML(label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input"><textarea${id?` id="${id}"`:''} name="${name}" rows="5" maxlength="16384" spellcheck="false" autocomplete="off" placeholder="${escapeHTML(placeholder)}"></textarea></div><small data-credential-hint="${name}" class="${hintTone?'is-'+hintTone:''}">${escapeHTML(hint)}</small></label>`;const secret=type==='password';// Secrets are never serialized into markup; callers assign input.value after rendering.return `<label class="credential-field"><span>${escapeHTML(label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input${secret?'':' is-plain'}${hintTone?' is-'+(hintTone==='err'?'bad':hintTone==='ok'?'good':hintTone):''}"><input${id?` id="${id}"`:''} name="${name}" type="${type}" ${secret?'autocomplete="new-password"':'autocomplete="off" spellcheck="false"'}${secret?'':` value="${escapeHTML(value)}"`} placeholder="${escapeHTML(placeholder)}">${secret?`<button type="button" class="credential-eye" data-credential-eye aria-label="显示">${credentialGlyph('eye',15)}</button>`:''}</div>${hint!==null?`<small data-credential-hint="${name}"${hintTone?` class="is-${hintTone}"`:''}>${escapeHTML(hint)}</small>`:''}</label>`;@@ -562,15 +565,17 @@ function credentialEditorHTML(kind,user){</div>`;}function credentialRowMainHTML(kind,user){- const on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key,status=credentialStatus(kind,user);- const end=on+ const ssh=kind.key==='gitSshKey',on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key,status=credentialStatus(kind,user);+ const end=on&&!ssh?`${credentialBadgeHTML(status)}${kind.key==='gitToken'?`<span class="credential-tip" data-tip="重新校验"><button type="button" class="credential-btn ghost icon credential-ink git-token-verify" data-credential-act="verify" aria-label="重新校验"${status==='busy'?' disabled':''}>${credentialGlyph('refresh',15)}</button></span>`:''}<span class="credential-chevron">${credentialGlyph('chevron-down',16)}</span>`- :`${credentialBadgeHTML(status)}<button type="button" class="credential-btn secondary credential-ink" data-credential-act="setup">去配置<span class="credential-nudge">${credentialGlyph('chevron-right',13)}</span></button>`;- return `<div class="credential-row-main credential-ink" role="button" tabindex="0"${on?` aria-expanded="${open}"`:''}>${credentialLogo(kind,on?'':'is-dim')}<div class="credential-row-who"><b>${escapeHTML(kind.name)}<span>${escapeHTML(kind.short)}</span></b><small>${credentialSubline(kind,user)}</small></div><div class="credential-row-end">${end}</div></div>`;+ :`${credentialBadgeHTML(status)}<button type="button" class="credential-btn secondary credential-ink" data-credential-act="setup"${ssh?' aria-haspopup="dialog"':''}>${ssh?'管理密钥':'去配置'}<span class="credential-nudge">${credentialGlyph('chevron-right',13)}</span></button>`;+ const interaction=ssh?'':` role="button" tabindex="0"${on?` aria-expanded="${open}"`:''}`;+ return `<div class="credential-row-main credential-ink"${interaction}>${credentialLogo(kind,on?'':'is-dim')}<div class="credential-row-who"><b>${escapeHTML(kind.name)}<span>${escapeHTML(kind.short)}</span></b><small>${credentialSubline(kind,user)}</small></div><div class="credential-row-end">${end}</div></div>`;}function credentialRowHTML(kind,user){const on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key;- return `<div class="credential-row${on?' is-configured':''}${open?' is-open':''}" data-credential-row="${kind.key}">${credentialRowMainHTML(kind,user)}<div class="credential-editor"><div><div class="credential-editor-inner">${on?credentialEditorHTML(kind,user):''}</div></div></div></div>`;+ const editor=on&&kind.key!=='gitSshKey'?credentialEditorHTML(kind,user):'';+ return `<div class="credential-row${on?' is-configured':''}${open?' is-open':''}" data-credential-row="${kind.key}">${credentialRowMainHTML(kind,user)}<div class="credential-editor"><div><div class="credential-editor-inner">${editor}</div></div></div></div>`;}function credentialGroupHTML(group,user){const kinds=CREDENTIAL_KINDS.filter(kind=>kind.group===group.id),done=kinds.filter(kind=>credentialConfigured(kind,user)).length,closed=!!credentialUI().closed[group.id];@@ -641,7 +646,7 @@ function setCredentialRowOpen(key,open){}}function resetCredentialEditor(row){- row.querySelectorAll('input[name="secret"]').forEach(input=>{input.value='';input.type='password'});+ row.querySelectorAll('[name="secret"]').forEach(input=>{input.value='';if(input.tagName==='INPUT')input.type='password'});const form=row.querySelector('.credential-editor-form');if(!form)return;const extra=form.querySelector('[name="extra"]');if(extra)extra.value=form.dataset.original||'';if(extra?.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,extra.value);@@ -659,9 +664,9 @@ 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}"] input[name="secret"]`)?.focus({preventScroll:true}),200);+ if(next&&key!=='gitToken')setTimeout(()=>$(`#credentialPanel [data-credential-row="${key}"] [name="secret"]`)?.focus({preventScroll:true}),200);}-const CREDENTIAL_PANE_FOCUS={form:'input[name="secret"]',confirm:'[data-credential-act="undelete"]'};+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.function showCredentialPane(row,name,focus=CREDENTIAL_PANE_FOCUS[name]){const panes=['bar','foot','form','confirm'].map(pane=>row.querySelector(`[data-credential-pane="${pane}"]`)).filter(Boolean);if(!panes.length)return;@@ -670,11 +675,11 @@ function showCredentialPane(row,name,focus=CREDENTIAL_PANE_FOCUS[name]){if(focus)setTimeout(()=>target.querySelector(focus)?.focus({preventScroll:true}),60);}function updateCredentialEditorDirty(form){- const secret=form.querySelector('input[name="secret"]')?.value.trim()||'',extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('select[name="protocol"]'),save=form.querySelector('[data-credential-act="save"]');+ const secret=form.querySelector('[name="secret"]')?.value.trim()||'',extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('select[name="protocol"]'),save=form.querySelector('[data-credential-act="save"]');if(save&&!save.dataset.busy)save.disabled=!secret&&!form.dataset.legacy&&!(extra&&extra.value.trim()!==(form.dataset.original||''))&&!(protocol&&protocol.value!==(form.dataset.originalProtocol||''))&&!credentialCatalogDirty(form.querySelector('[data-credential-catalog]'));}function setCredentialHint(scope,name,text,tone=''){- const hint=scope.querySelector(`[data-credential-hint="${name}"]`),box=scope.querySelector(`input[name="${name}"]`)?.closest('.credential-input');+ const hint=scope.querySelector(`[data-credential-hint="${name}"]`),box=scope.querySelector(`[name="${name}"]`)?.closest('.credential-input');if(hint){hint.textContent=text;hint.className=tone?'is-'+tone:''}if(box){box.classList.toggle('is-bad',tone==='err');box.classList.toggle('is-good',tone==='ok');box.classList.toggle('is-warn',tone==='warn');if(tone==='err'){box.classList.remove('is-shake');void box.offsetWidth;box.classList.add('is-shake')}}}@@ -738,7 +743,7 @@ function credentialSaved(key,message){}async function submitCredentialEditor(row,button){const key=row.dataset.credentialRow,kind=credentialKind(key),form=row.querySelector('.credential-editor-form');- const secret=form.querySelector('input[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('[name="protocol"]');+ const secret=form.querySelector('[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('[name="protocol"]');const secretError=credentialSecretError(kind,secret),extraError=extra?credentialExtraError(kind,extra.value,protocol?.value):'';if(secretError){setCredentialHint(form,'secret',secretError,'err');return}if(extraError){toast(extraError,'err');extra.focus();return}@@ -810,6 +815,7 @@ function toggleCredentialGroup(head){}function activateCredentialRow(row){const key=row.dataset.credentialRow;+ if(key==='gitSshKey')return openGitSSHKeys();return row.classList.contains('is-configured')?toggleCredentialRow(key):openCredentialWizard(key);}function bindCredentialPanel(panel){@@ -864,7 +870,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('input[name="secret"]')?.focus({preventScroll:true}),200);+ else if(key!=='gitToken')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);@@ -876,6 +882,7 @@ function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraVfunction openCredentialWizard(key){const user=credentialUser();if(!state.currentUser||state.currentUser.isGuest||!$('#credentialPanel'))return;+ if(key==='gitSshKey')return openGitSSHKeys();const preset=key?credentialKind(key):null;if(preset&&credentialConfigured(preset,user))return revealCredentialRow(key);const kind=preset||CREDENTIAL_RECOMMENDED.map(credentialKind).find(k=>!credentialConfigured(k,user))||CREDENTIAL_KINDS.find(k=>!credentialConfigured(k,user))||null;@@ -931,7 +938,7 @@ function credentialWizardStepOneHTML(user){const wizard=credentialWizard,all=CREDENTIAL_KINDS.every(kind=>credentialConfigured(kind,user));const groups=CREDENTIAL_GROUPS.map(group=>`<p class="credential-opt-label">${escapeHTML(group.name)}</p><div class="credential-opts" role="radiogroup" aria-label="${escapeHTML(group.name)}">${CREDENTIAL_KINDS.filter(kind=>kind.group===group.id).map((kind,index)=>{const on=credentialConfigured(kind,user),selected=wizard.kind===kind.key;- return `<button type="button" class="credential-opt${selected?' is-selected':''}" style="--i:${index}" role="radio" aria-checked="${selected}" data-wizard-kind="${kind.key}"${on?' disabled':''}><span class="credential-radio">${credentialGlyph('check',10)}</span>${credentialLogo(kind)}<span class="credential-opt-text"><b>${escapeHTML(kind.name)}</b><small>${escapeHTML(kind.short)}</small></span>${on?'<span class="credential-pill is-ok">已配置</span>':CREDENTIAL_RECOMMENDED.includes(kind.key)?'<span class="credential-pill">推荐</span>':''}</button>`;+ return `<button type="button" class="credential-opt${selected?' is-selected':''}" style="--i:${index}" role="radio" aria-checked="${selected}" data-wizard-kind="${kind.key}"${on&&kind.key!=='gitSshKey'?' disabled':''}><span class="credential-radio">${credentialGlyph('check',10)}</span>${credentialLogo(kind)}<span class="credential-opt-text"><b>${escapeHTML(kind.name)}</b><small>${escapeHTML(kind.short)}</small></span>${on?'<span class="credential-pill is-ok">已配置</span>':CREDENTIAL_RECOMMENDED.includes(kind.key)?'<span class="credential-pill">推荐</span>':''}</button>`;}).join('')}</div>`).join('');return `<div class="credential-question">${credentialGlyph('key',16)}<span>要添加哪一项凭证?</span><small>选择一项 · 已配置的可在列表中编辑</small></div>${groups}${all?`<div class="credential-note">${credentialGlyph('check',14)}<span>已全部配置,可在列表中编辑。</span></div>`:''}`;}@@ -977,7 +984,7 @@ function credentialWizardFootHTML(){?'<span class="credential-kbd"><kbd>Esc</kbd> 关闭</span>':`<button type="button" class="credential-btn ghost credential-ink" data-wizard-back${wizard.saving?' disabled':''}><span class="credential-nudge is-left">${credentialGlyph('arrow-left',13)}</span>上一步</button>`;if(wizard.step<3){- const ok=wizard.step===1?!!wizard.kind&&!credentialConfigured(credentialKind(wizard.kind),credentialUser()):credentialWizardValid().ok;+ const ok=wizard.step===1?!!wizard.kind&&(wizard.kind==='gitSshKey'||!credentialConfigured(credentialKind(wizard.kind),credentialUser())):credentialWizardValid().ok;return `${back}<button type="button" class="credential-btn secondary credential-ink" data-wizard-next${ok?'':' disabled'}>下一步<span class="credential-nudge">${credentialGlyph('chevron-right',13)}</span></button>`;}const gongfeng=wizard.kind==='gitToken';@@ -995,10 +1002,10 @@ function paintCredentialWizard(direction){const pane=document.createElement('div');pane.className='credential-pane'+(direction>0?' is-forward':direction<0?' is-back':'');pane.innerHTML=credentialWizardPaneHTML();- if(old&&direction){old.className=`credential-pane is-leaving ${direction>0?'is-forward':'is-back'}`;old.querySelectorAll('input').forEach(input=>{input.value=''});setTimeout(()=>old.remove(),180)}+ if(old&&direction){old.className=`credential-pane is-leaving ${direction>0?'is-forward':'is-back'}`;old.querySelectorAll('input,textarea').forEach(input=>{input.value=''});setTimeout(()=>old.remove(),180)}else old?.remove();body.append(pane);- const secretInput=pane.querySelector('input[name="secret"]');if(secretInput)secretInput.value=wizard.secret||'';+ const secretInput=pane.querySelector('[name="secret"]');if(secretInput)secretInput.value=wizard.secret||'';if(before&&direction){body.style.height=before+'px';requestAnimationFrame(()=>{body.style.height=pane.offsetHeight+'px';setTimeout(()=>{body.style.height=''},300)})}scrim.querySelectorAll('.credential-dots span').forEach((dot,index)=>{dot.className=wizard.done||index+1<wizard.step?'is-done':index+1===wizard.step?'is-current':''});scrim.querySelector('[data-wizard-step]').textContent=wizard.done?'已完成':`${wizard.step} / 3`;@@ -1017,7 +1024,7 @@ function focusCredentialWizard(){const pane=$('#credentialWizard .credential-pane:not(.is-leaving)');// Deferred calls must not pull focus back once the user is already in this pane, or typing lands in the wrong field.if(pane?.contains(document.activeElement))return;- (pane?.querySelector('input, .credential-opt.is-selected:not(:disabled), .credential-opt:not(:disabled)')+ (pane?.querySelector('input, textarea, .credential-opt.is-selected:not(:disabled), .credential-opt:not(:disabled)')||$('#credentialWizard [data-wizard-next]:not(:disabled), #credentialWizard [data-wizard-done]')||$('#credentialWizard [data-wizard-close]:not(:disabled)')||$('#credentialWizard .credential-dialog'))?.focus({preventScroll:true});@@ -1086,7 +1093,11 @@ function credentialWizardClick(event){async function advanceCredentialWizard(){const wizard=credentialWizard;if(!wizard||wizard.saving||wizard.done)return;if(wizard.step===1){- if(!wizard.kind||credentialConfigured(credentialKind(wizard.kind),credentialUser()))return;+ if(!wizard.kind||(wizard.kind!=='gitSshKey'&&credentialConfigured(credentialKind(wizard.kind),credentialUser())))return;+ if(wizard.kind==='gitSshKey'){+ closeCredentialWizard(true);+ return openGitSSHKeys();+ }wizard.step=2;paintCredentialWizard(1);setTimeout(focusCredentialWizard,220);return;}if(wizard.step===2){diff --git a/web/i18n-en.js b/web/i18n-en.jsindex fe8d1083..05980321 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -140,3 +140,32 @@ Object.assign(window.LF_I18N_EN,{"读取设置失败":"Could not load settings"});Object.assign(window.LF_I18N_EN,{"平台目录":"Platform catalog","通用模板按名称绑定这些 MCP,添加到本项目后即可使用。":"Generic templates bind these MCPs by name. Add one to this project to use it.","已添加到当前项目":"Added to this project","添加中…":"Adding…"});+Object.assign(window.LF_I18N_EN,{+ "Git SSH 密钥":"Git SSH keys",+ "按 SSH 主机管理个人密钥,仓库自动匹配":"Manage personal keys by SSH host; repositories match automatically",+ "管理密钥":"Manage keys",+ "每个 SSH 主机配置一把个人密钥,同一主机的仓库自动共用。":"Configure one personal key per SSH host. Repositories on the same host share it automatically.",+ "密钥名称":"Key name",+ "例如 GitLab 或 Gitea":"For example, GitLab or Gitea",+ "SSH 主机":"SSH host",+ "不填写端口时使用 22。":"The default port is 22.",+ "gitlab.com 或 git.example.org:2222":"gitlab.com or git.example.org:2222",+ "SSH 私钥":"SSH private key",+ "粘贴完整的 OpenSSH 或 PEM 私钥":"Paste the complete OpenSSH or PEM private key",+ "留空保留现有私钥":"Leave blank to keep the current private key",+ "把对应公钥添加到代码托管账号,并授予仓库访问权限。推送需要写权限。":"Add the public key to your hosting account and grant repository access. Pushing requires write access.",+ "正在读取密钥…":"Loading keys…",+ "还没有配置 Git SSH 密钥":"No Git SSH keys configured yet",+ "无法读取 SSH 密钥配置,请稍后重试。":"Unable to load SSH key settings. Please try again later.",+ "添加密钥":"Add key",+ "编辑密钥":"Edit key",+ "保存密钥":"Save key",+ "密钥已保存":"Key saved",+ "删除这把密钥?":"Delete this key?",+ "密钥已删除":"Key deleted",+ "GitHub 链接或 Git SSH 地址":"GitHub link or Git SSH address",+ "仓库网页地址":"Repository web URL",+ "配置 Git SSH 密钥":"Configure Git SSH key",+ "请输入有效的 GitHub 链接或 Git SSH 克隆地址。CNB 只支持 HTTPS + 访问令牌。":"Enter a GitHub link or a Git SSH clone address. CNB supports HTTPS with an access token.",+ "粘贴 GitHub 链接或 Git SSH 地址":"Paste a GitHub link or Git SSH address"+});diff --git a/web/index.html b/web/index.htmlindex 9c88bac9..4d37d7c3 100644--- a/web/index.html+++ b/web/index.html@@ -1008,13 +1008,17 @@<div class="pa-fs"><h5>仓库地址</h5><div data-github-repositories></div>- <label class="pa-field"><span class="pa-field-l">GitHub 仓库地址</span>+ <label class="pa-field"><span class="pa-field-l">GitHub 链接或 Git SSH 地址</span><input class="pa-input mono" name="repoUrl" spellcheck="false" placeholder="https://github.com/owner/repo">- <span class="pa-fmt"><code>https://github.com/owner/repo</code><code>[email protected]:owner/repo.git</code><code>git clone …</code></span>- <span class="pa-field-e" id="repoDrawerUrlError" hidden>无法识别为 GitHub 仓库链接,请粘贴 github.com 的 Web / SSH / clone 地址。</span>+ <span class="pa-fmt"><code>https://github.com/owner/repo</code><code>[email protected]:group/repo.git</code></span>+ <span class="pa-field-e" id="repoDrawerUrlError" hidden>请输入有效的 GitHub 链接或 Git SSH 克隆地址。CNB 只支持 HTTPS + 访问令牌。</span></label><div class="pa-detect" id="repoDrawerDetect" hidden><span class="pa-detect-ok"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5 9-10"/></svg></span><div class="pa-detect-m"><b id="repoDrawerDetectName"></b><code id="repoDrawerDetectPath"></code></div><button type="button" class="button ghost small" id="repoDrawerRename">改名</button></div><label class="pa-field" id="repoDrawerNameField" hidden><span class="pa-field-l">仓库名称</span><input class="pa-input mono" name="name" placeholder="留空则自动取项目路径末段"></label>+ <div id="repoDrawerSSH" hidden>+ <label class="pa-field"><span class="pa-field-l">仓库网页地址 <i>可选</i></span><input class="pa-input mono" name="webUrl" placeholder="https://gitlab.com/group/repo" autocomplete="off"></label>+ <p id="repoDrawerSSHMissing" class="git-ssh-missing" role="alert" hidden></p>+ </div></div><div class="pa-fs"><h5>分支</h5>@@ -1301,6 +1305,7 @@<script src="/app/hui-date.js"></script><script src="/app/hui-upload.js"></script><script src="/app/hui-tooltip.js"></script>+ <script src="/app/git-ssh.js"></script><script src="/app/issues.js"></script><script src="/app/issue-bulk-delete.js"></script><script src="/app/sync-schedule.js"></script>@@ -1320,6 +1325,7 @@<script src="/app/runs.js"></script><script src="/app/run-activation.js"></script><script src="/app/workbench.js?v=20261030theme1"></script>+ <script src="/app/git-ssh-keys.js"></script><script src="/app/approvals.js"></script><script src="/app/obs-charts.js"></script><script src="/app/observability.js"></script>diff --git a/web/platform.css b/web/platform.cssindex 4dd1fdf7..3d9b399f 100644--- a/web/platform.css+++ b/web/platform.css@@ -2234,7 +2234,7 @@ html[data-theme="light"] body{color-scheme:light}html[data-theme="light"] .platf.obs-card>.pager{margin:10px 0 2px;border:0;background:transparent;padding:8px 0 0}/* ================= 个人凭证(harness-ui 设计语言) ================= */-#personalSettingsContent,.credential-scrim,.github-connect{+#personalSettingsContent,.credential-scrim,.github-connect,.git-ssh-dialog{--cr-accent:var(--hui-accent);--cr-accent-hover:var(--hui-accent-hover);--cr-surface:var(--hui-surface);--cr-canvas:var(--hui-canvas);--cr-elevated:var(--hui-soft);--cr-text:var(--hui-text);--cr-text-2:var(--hui-secondary);--cr-muted:var(--hui-muted);--cr-tertiary:var(--hui-tertiary);@@ -2384,6 +2384,28 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}.credential-input select:focus{border-color:color-mix(in srgb,var(--cr-accent) 55%,transparent);box-shadow:0 0 0 3px color-mix(in srgb,var(--cr-accent) 12%,transparent)}.credential-input{position:relative;display:flex;align-items:center}.credential-input input{width:100%;height:36px;margin:0;padding:0 36px 0 11px;border:1px solid var(--cr-line);border-radius:8px;background:var(--cr-surface);color:var(--cr-text);font:inherit;font-size:13px;outline:none;box-shadow:none;transition:border-color .16s,box-shadow .25s var(--cr-flow)}+.credential-input textarea{width:100%;min-height:110px;resize:vertical;font-family:ui-monospace,monospace}+.git-ssh-dialog{width:min(600px,calc(100vw - 32px));max-height:calc(100dvh - 48px);margin:auto;padding:22px;border:1px solid var(--hui-border);border-radius:14px;background:var(--hui-surface);color:var(--hui-text);box-shadow:var(--hui-popover-shadow);overflow:auto}+.git-ssh-dialog::backdrop{background:var(--hui-scrim)}+.git-ssh-dialog[open]{animation:gitSSHDialogIn .18s ease-out}+@keyframes gitSSHDialogIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}+@media(prefers-reduced-motion:reduce){.git-ssh-dialog[open]{animation:none}}+.git-ssh-dialog [hidden]{display:none}+.git-ssh-dialog-head{display:flex;align-items:center;justify-content:space-between;gap:12px}+.git-ssh-dialog h2,.git-ssh-dialog h3{margin:0;font-weight:600}+.git-ssh-dialog h2{font-size:18px}.git-ssh-dialog h3{font-size:14px}+.git-ssh-description,.git-ssh-status{margin:8px 0 12px;color:var(--hui-muted);font-size:13px}+.git-ssh-status.is-error{color:var(--hui-error)}+.git-ssh-key-list:not(:empty){margin-bottom:14px;border:1px solid var(--hui-border);border-radius:9px}+.git-ssh-key-row{display:flex;align-items:center;flex-wrap:wrap;gap:6px;padding:9px 10px}+.git-ssh-key-row+.git-ssh-key-row{border-top:1px solid var(--hui-border)}+.git-ssh-key-summary{flex:1 1 170px;min-width:0;display:grid;gap:3px;font-size:13px}+.git-ssh-key-summary small{color:var(--hui-muted);overflow-wrap:anywhere}+.git-ssh-key-form{display:grid;gap:12px;padding-top:8px}+.git-ssh-form-actions{display:flex;flex-wrap:wrap;gap:8px}+.git-ssh-missing{margin:8px 0 0;color:var(--hui-error);font-size:12px;line-height:1.6}+.git-ssh-form-actions{justify-content:flex-end}+.git-ssh-dialog textarea{padding:8px 11px;border:1px solid var(--hui-border);border-radius:8px;background:var(--hui-surface);color:var(--hui-text);font-size:12px}.credential-input.is-plain input{padding-right:11px}.credential-input input::placeholder{color:var(--cr-tertiary)}.credential-input input:hover{border-color:var(--cr-line-strong)}diff --git a/web/project_admin_layout_test.js b/web/project_admin_layout_test.jsindex f45ac587..58576f8f 100644--- a/web/project_admin_layout_test.js+++ b/web/project_admin_layout_test.js@@ -150,7 +150,7 @@ assert.match(list,/pa-rc-add/);const empty=ctx.projectRepoListHTML([],"");assert.match(empty,/还没有绑定代码仓库/);assert.equal((empty.match(/<li>/g)||[]).length,3);-assert.match(empty,/粘贴 GitHub 仓库地址[^]*确认分支[^]*保存即生效/);+assert.match(empty,/粘贴 GitHub 链接或 Git SSH 地址[^]*确认分支[^]*保存即生效/);assert.match(empty,/添加第一个仓库/);// Detail panels.diff --git a/web/project_wizard_test.js b/web/project_wizard_test.jsindex b807eb3d..6166a5aa 100644--- a/web/project_wizard_test.js+++ b/web/project_wizard_test.js@@ -176,7 +176,7 @@ function assertFooterLayout(step){W().repo.url="https://bitbucket.org/foo/bar";assert.equal(await ctx.projectWizardAddRepo(),false);assert.equal(requests.length,0);- assert.match(html(),/无法识别为 GitHub 仓库地址/);+ assert.match(html(),/请输入 GitHub 链接或有效的 Git SSH 地址/);Object.assign(W().repo,{url:"https://github.com/example/web-console",branch:"",integrate:"agentflow/integration"});assert.equal(await ctx.projectWizardAddRepo(),true);assert.equal(requests[0].url,"/api/repositories");assert.equal(requests[0].method,"POST");diff --git a/web/syntax_test.go b/web/syntax_test.goindex ef7d70e9..38787305 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -499,21 +499,21 @@ eval(code.slice(code.indexOf('const CREDENTIAL_GROUPS='), code.indexOf('// 谁';globalThis.cred={CREDENTIAL_KINDS,CREDENTIAL_GROUPS,kind:credentialKind,get wizard(){return credentialWizard},set wizard(v){credentialWizard=v}};');const count = (html, needle) => html.split(needle).length - 1;-// Two groups list all four kinds in a fixed order.+// 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']);+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']);// Progress, next-step hint, filter counts and per-group counts.const html = credentialPanelHTML(user);-assert.ok(html.includes('<b>2</b> / 11 已配置'));+assert.ok(html.includes('<b>2</b> / 12 已配置'));assert.ok(html.includes('data-credential-setup="codeBuddyApiKey"'), 'next step follows Git → CodeBuddy');-assert.ok(html.includes('1 / 1') && html.includes('1 / 10'));-assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>9</span>'));-assert.equal(count(html, 'data-credential-row='), 11);+assert.ok(html.includes('1 / 2') && html.includes('1 / 10'));+assert.ok(html.includes('已配置<span>2</span>') && html.includes('未配置<span>10</span>'));+assert.equal(count(html, 'data-credential-row='), 12);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"'), 9);+assert.equal(count(html, 'data-credential-act="setup"'), 10);assert.equal(count(html, 'credential-editor-form'), 2);assert.equal(count(html, 'data-credential-act="delete"'), 2);for (const key of ['codeBuddyApiKey', 'claudeCodeApiKey']) {@@ -530,6 +530,9 @@ assert.equal(credentialNextKind({}).key, 'gitToken');// Each kind saves and deletes only its own fields.assert.deepEqual(credentialSavePayload(cred.kind('gitToken'), {secret: ' ghp_1 '}), {gitToken: 'ghp_1'});+const sshRow = credentialRowHTML(cred.kind('gitSshKey'), {...user, gitSshKeyConfigured: true});+assert.match(sshRow, /aria-haspopup="dialog">管理密钥/);+assert.ok(!sshRow.includes('credential-editor-form'));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'});diff --git a/webtest/lib/load-app.mjs b/webtest/lib/load-app.mjsindex 83ade4eb..da6905d3 100644--- a/webtest/lib/load-app.mjs+++ b/webtest/lib/load-app.mjs@@ -69,6 +69,7 @@ function defaultPayload(pathname, method) {};if (pathname === '/api/bootstrap') return sampleBootstrap();if (pathname === '/api/assistant/sessions') return [];+ if (/\/users\/[^/]+\/git-ssh-keys$/.test(pathname)) return [];if (/\/workflows\/metrics$/.test(pathname)) return sampleBootstrap().workflowMetrics;if (pathname === '/api/workflow-metrics') return sampleBootstrap().workflowMetrics;if (pathname === '/api/notification-bots') return sampleBootstrap().bots;diff --git a/webtest/tests/git-ssh-keys.test.mjs b/webtest/tests/git-ssh-keys.test.mjsnew file mode 100644index 00000000..bebed1ab--- /dev/null+++ b/webtest/tests/git-ssh-keys.test.mjs@@ -0,0 +1,154 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { loadApp, settle } from '../lib/load-app.mjs';++test('configured Git SSH credentials accept additional keys and support write-only edits and confirmed deletion', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ const endpoint = '/api/users/1/git-ssh-keys';+ let keys = [{ id: 'gitlab', name: 'GitLab', host: 'gitlab.example.org:22' }];+ app.router.get(endpoint, () => keys);+ app.router.put(endpoint, ({ body }) => {+ const key = { id: body.id || 'other-host', name: body.name, host: body.host };+ keys = [...keys.filter(item => item.id !== key.id), key];+ return keys;+ });+ app.router.delete(`${endpoint}/other-host`, () => {+ keys = keys.filter(item => item.id !== 'other-host');+ return keys;+ });+ app.evaluate(`+ state.currentUser={...state.data.users[0],id:1,isGuest:false,gitSshKeyConfigured:true,codeBuddyApiKeyConfigured:true};+ state.data.users=[state.currentUser];+ renderPersonalSettings();+ openCredentialWizard();+ `);+ const wizard = app.document.querySelector('#credentialWizard');+ assert.equal(wizard.querySelector('[data-wizard-kind="codeBuddyApiKey"]').disabled, true);+ const sshOption = wizard.querySelector('[data-wizard-kind="gitSshKey"]');+ assert.equal(sshOption.disabled, false, 'SSH supports adding more keys after the first one');+ sshOption.click();+ wizard.querySelector('[data-wizard-next]').click();+ await settle(6);++ const dialog = app.document.querySelector('#gitSSHKeyDialog');+ const form = dialog.querySelector('form');+ assert.equal(app.document.querySelector('#credentialWizard'), null);+ assert.equal(dialog.querySelectorAll('.git-ssh-key-row').length, 1);+ assert.equal(dialog.querySelector('[data-ssh-key-scope]'), null);+ dialog.querySelector('[data-ssh-key-add]').click();+ form.elements.name.value = 'Other Git host';+ form.elements.host.value = 'git.example.org:2222';+ form.elements.privateKey.value = 'test-only-private-key';+ form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle(6);+ const saves = () => app.router.calls.filter(call => call.method === 'PUT' && call.path === endpoint);+ assert.deepEqual(saves()[0].body, {+ name: 'Other Git host', host: 'git.example.org:2222', privateKey: 'test-only-private-key',+ });+ assert.equal(dialog.querySelectorAll('.git-ssh-key-row').length, 2);+ assert.equal(form.hidden, true);+ assert.equal(form.elements.privateKey.value, '', 'saving clears the temporary private key input');++ dialog.querySelector('[data-ssh-key-edit="gitlab"]').click();+ assert.equal(form.elements.privateKey.value, '', 'editing never reads back the stored private key');+ assert.match(form.elements.privateKey.placeholder, /留空保留/);+ assert.equal(form.elements.privateKey.required, false);+ assert.equal(form.elements.host.readOnly, true);+ form.elements.name.value = 'GitLab team';+ form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle(6);+ assert.deepEqual(saves()[1].body, {+ id: 'gitlab', name: 'GitLab team', host: 'gitlab.example.org:22', privateKey: '',+ });+ assert.equal(dialog.querySelectorAll('.git-ssh-key-row').length, 2);++ dialog.querySelector('[data-ssh-key-delete="other-host"]').click();+ assert.equal(app.router.calls.some(call => call.method === 'DELETE'), false);+ dialog.querySelector('[data-ssh-key-keep]').click();+ assert.equal(dialog.querySelector('[data-ssh-key-remove]'), null);+ dialog.querySelector('[data-ssh-key-delete="other-host"]').click();+ dialog.querySelector('[data-ssh-key-remove="other-host"]').click();+ await settle(6);+ assert.equal(dialog.querySelectorAll('.git-ssh-key-row').length, 1);+ assert.match(dialog.querySelector('.git-ssh-key-list').textContent, /GitLab team/);+ dialog.querySelector('[data-ssh-key-close]').click();+ assert.equal(app.document.querySelector('#gitSSHKeyDialog'), null);+ assert.equal(app.evaluate('state.currentUser.gitSshKeyConfigured'), true);+});++test('repository forms only warn for the current user missing the selected SSH host', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ app.router.get('/api/users/1/git-ssh-keys', [+ { id: 'gitlab', name: 'GitLab team', host: 'gitlab.example.org:22' },+ { id: 'ipv6', name: 'IPv6', host: '[2001:db8::1]:22' },+ ]);+ app.evaluate(`+ state.currentUser={...state.data.users[0],id:1,isGuest:false,gitSshKeyConfigured:true};+ state.data.users=[state.currentUser];+ state.projectAdminDetailId='project-1';+ state.projectDraftFor='project-1';+ state.projectDraft=projectDraftFrom(state.data.projects[0]);+ state.projectDraftBase=clone(state.projectDraft);+ openRepoDrawer('');+ `);+ const drawer = app.document.querySelector('#repoDrawer');+ const form = drawer.querySelector('form');+ const hint = drawer.querySelector('#repoDrawerSSHMissing');+ const remote = 'ssh://[email protected]:2222/team/inventory.git';+ const webUrl = 'https://git.example.org/team/inventory';+ const input = (value) => {+ form.elements.repoUrl.value = value;+ form.elements.repoUrl.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ };+ input(remote);+ form.elements.webUrl.value = webUrl;+ form.elements.integrateBranch.value = 'release';+ await settle(6);+ assert.equal(hint.hidden, false, 'a key for a different host does not match');+ assert.equal(hint.classList.contains('git-ssh-missing'), true);+ assert.match(hint.textContent, /尚未配置 git.example.org:2222 的 SSH 密钥/);+ assert.equal(drawer.querySelector('#repoDrawerSSHSettings'), null);+ assert.equal(hint.querySelector('button'), null);++ input('[email protected]:team/app.git');+ await settle(6);+ assert.equal(hint.hidden, true, 'the host key covers every repository on that host');+ input('ssh://[email protected]:2222/team/app.git');+ await settle(6);+ assert.equal(hint.hidden, false, 'a different port needs its own host key');+ input('git@[2001:0DB8:0000::1]:team/app.git');+ await settle(6);+ assert.equal(hint.hidden, true, 'equivalent IPv6 addresses match');+ input(remote);+ input('https://github.com/team/app');+ await settle(6);+ assert.equal(hint.hidden, true, 'a late SSH check must not overwrite a new HTTPS address');+ input(remote);+ await settle(6);+ assert.equal(form.elements.webUrl.value, webUrl);+ assert.equal(form.elements.integrateBranch.value, 'release');+ assert.equal(drawer.classList.contains('open'), true);+ assert.equal(app.router.calls.some(call => call.method !== 'GET' && call.path.includes('git-ssh-keys')), false);++ app.evaluate(`state.projectFilter='project-1';openRepositoryModal();`);+ const legacy = app.document.querySelector('#repositoryForm');+ const legacyHint = app.document.querySelector('#repositoryCredentialHint');+ legacy.elements.repoUrl.value = remote;+ legacy.elements.repoUrl.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ await settle(6);+ assert.equal(legacyHint.hidden, false);+ assert.match(legacyHint.textContent, /尚未配置 git.example.org:2222/);+ assert.equal(legacyHint.querySelector('button'), null);+ legacy.elements.repoUrl.value = '[email protected]:team/app.git';+ legacy.elements.repoUrl.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ await settle(6);+ assert.equal(legacyHint.hidden, true);++ app.router.get('/api/users/2/git-ssh-keys', []);+ app.evaluate(`state.currentUser={id:2,isGuest:false};renderRepositoryCredentialHint();`);+ await settle(6);+ assert.equal(legacyHint.hidden, false, 'another user cannot borrow the first user’s host metadata');+ assert.match(legacyHint.textContent, /尚未配置 gitlab.example.org:22/);+});diff --git a/webtest/tests/issues-list.test.mjs b/webtest/tests/issues-list.test.mjsindex 4a3e851b..c28158bd 100644--- a/webtest/tests/issues-list.test.mjs+++ b/webtest/tests/issues-list.test.mjs@@ -35,9 +35,11 @@ test('issue list helpers filter, format, parse repositories, and persist edits',parseGongfengRepoURL('https://git.example.com/team/service/-/merge_requests/9'),parseGongfengRepoURL('team/sub/repo'),parseGongfengRepoURL('https://evil.example/team/repo'),- parseGongfengRepoURL('../secret')+ parseGongfengRepoURL('../secret'),+ parseGongfengRepoURL('[email protected]:octo/widgets.git'),+ parseGongfengRepoURL('ssh://[email protected]/octo/widgets.git')];- const fill={name:''};const filled=fillRepositoryFromLink('ssh://[email protected]/team/api.git',fill);+ const fill={name:''};const filled=fillRepositoryFromLink('ssh://[email protected]:2222/team/api.git',fill);const title=issueTitleMarkup('[Bug] 【前端】 broken <button>');const keys=[issueKeyColumnWidth([{id:'x',projectId:'project-1',number:1}]),issueKeyColumnWidth([{source:'tapd',externalRef:{externalId:'1234567890'}}])];@@ -59,10 +61,16 @@ test('issue list helpers filter, format, parse repositories, and persist edits',assert.equal(result.parsed[2].name, 'repo');assert.equal(result.parsed[3], null);assert.equal(result.parsed[4], null);+ // GitHub SSH-style addresses stay GitHub repositories, as on the server.+ for (const github of result.parsed.slice(5)) {+ assert.equal(github.provider, 'github');+ assert.equal(github.project, 'github:octo/widgets');+ assert.equal(github.cloneUrl, 'https://github.com/octo/widgets.git');+ }assert.equal(result.filled, true);assert.deepEqual(result.fill, {- name: 'api', gongfengProjectId: 'team/api', webUrl: 'https://git.example.com/team/api',- cloneUrl: '[email protected]:team/api.git'+ name: 'api', gongfengProjectId: '', webUrl: '',+ cloneUrl: 'ssh://[email protected]:2222/team/api.git'});assert.match(result.title, /tone-danger/);assert.match(result.title, /tone-cyan/);diff --git a/webtest/tests/project-wizard.test.mjs b/webtest/tests/project-wizard.test.mjsindex c04f708e..a71f75f8 100644--- a/webtest/tests/project-wizard.test.mjs+++ b/webtest/tests/project-wizard.test.mjs@@ -68,7 +68,7 @@ test('wizard validates names and repository URLs with actionable errors', asyncassert.match(app.document.querySelector('#projectWizard [role="alert"]').textContent, /项目名称不能为空/);app.evaluate(`projectWizard.step='repos';projectWizard.projectId='project-1';renderProjectWizard()`);await app.evaluate(`projectWizardAddRepo()`);- assert.match(app.document.querySelector('#projectWizard [role="alert"]').textContent, /请先粘贴 GitHub 仓库地址/);+ assert.match(app.document.querySelector('#projectWizard [role="alert"]').textContent, /请先粘贴 GitHub 链接或 Git SSH 地址/);});test('without a TAPD integration the wizard goes from members straight to done', async (t) => {diff --git a/webtest/tests/projects-repos.test.mjs b/webtest/tests/projects-repos.test.mjsindex fc23a466..1a301a9a 100644--- a/webtest/tests/projects-repos.test.mjs+++ b/webtest/tests/projects-repos.test.mjs@@ -74,7 +74,7 @@ test('project identity, filtering, payload validation, and project form behaviorassert.equal(app.evaluate(`state.data.projects[0].description`), 'Updated project scope');});-test('repository drawer detects Gongfeng URLs and persists a default repository', async (t) => {+test('repository drawer detects Git SSH URLs and persists a default repository', async (t) => {const app = await loadApp();t.after(app.close);app.router.post('/api/repositories', (call) => ({ ...call.body, id: 'repo-new' }));@@ -89,16 +89,25 @@ test('repository drawer detects Gongfeng URLs and persists a default repository'openRepoDrawer('');`);const form = app.document.querySelector('#repoDrawerForm');- form.elements.repoUrl.value = '[email protected]:platform/payments.git';+ form.elements.repoUrl.value = '[email protected]:platform/payments.git';form.elements.repoUrl.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ await settle(6);+ assert.equal(app.document.querySelector('#repoDrawerSSHMissing').hidden, false);+ assert.match(app.document.querySelector('#repoDrawerSSHMissing').textContent, /可稍后/);+ assert.equal(app.document.querySelector('#repoDrawerSave').disabled, false, 'a missing key is advisory and does not block saving');assert.equal(app.document.querySelector('#repoDrawerDetect').hidden, false);assert.equal(form.elements.name.value, 'payments');+ assert.equal(app.document.querySelector('#repoDrawerSSH').hidden, false);+ form.elements.webUrl.value = 'https://gitlab.example.org/platform/payments';form.elements.defaultBranch.value = 'main';form.elements.integrateBranch.value = 'release';form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));await settle(8);const create = app.router.calls.find(c => c.method === 'POST' && c.path === '/api/repositories');- assert.equal(create.body.gongfengProjectId, 'platform/payments');+ assert.equal(create.body.provider, 'ssh');+ assert.equal(create.body.gongfengProjectId, '');+ assert.equal(create.body.cloneUrl, '[email protected]:platform/payments.git');+ assert.equal(create.body.webUrl, 'https://gitlab.example.org/platform/payments');assert.equal(create.body.defaultBranch, 'main');assert.equal(app.evaluate(`state.data.repositories[0].id`), 'repo-new');assert.equal(app.evaluate(`state.data.projects[0].defaultRepositoryId`), 'repo-new');