From 5a44ccb6159832beaf81a9a471bc23010e5abed4 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sat, 5 Dec 2026 11:47:52 +0800 Subject: [PATCH] feat(vcs): offer an HTTPS clone when the SSH key cannot reach the repository (#7966) When an SSH clone of a github.com, gitlab.com, bitbucket.org or codeberg.org repository fails with a refused key or "Repository not found", the dialog explains that the key may belong to another account and offers Clone with HTTPS, which uses the Git credential helper such as GitHub CLI. --- src/features/vcs/__tests__/clone.test.ts | 31 +++++- .../vcs/__tests__/cloneHttpsFallback.test.tsx | 104 ++++++++++++++++++ src/features/vcs/clone.module.css | 7 ++ src/features/vcs/clone.tsx | 70 +++++++++++- src/platform/locales/text/en.json | 4 +- src/platform/locales/text/zh.json | 4 +- 6 files changed, 210 insertions(+), 10 deletions(-) create mode 100644 src/features/vcs/__tests__/cloneHttpsFallback.test.tsx diff --git a/src/features/vcs/__tests__/clone.test.ts b/src/features/vcs/__tests__/clone.test.ts index 9090071ebd..d8033b96da 100644 --- a/src/features/vcs/__tests__/clone.test.ts +++ b/src/features/vcs/__tests__/clone.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { cloneDirName, joinPath, parseCloneDepth, validateClone } from "../clone"; +import { cloneDirName, httpsCloneUrl, isSshAccessError, joinPath, parseCloneDepth, validateClone } from "../clone"; import { outgoingQuery } from "../remoteUi"; describe("cloneDirName", () => { @@ -44,7 +44,34 @@ describe("parseCloneDepth", () => { describe("outgoingQuery", () => { it("uses the upstream range when tracked", () => { - expect(outgoingQuery("origin/main")).toEqual({ branch: "HEAD", range: "@{u}..HEAD", limit: 1000 }); + expect(outgoingQuery("origin/main")).toEqual({ + branch: "HEAD", + range: "@{u}..HEAD", + limit: 1000, + }); expect(outgoingQuery(null).range).toBeNull(); }); }); + +describe("httpsCloneUrl", () => { + it("turns SSH addresses of hosting services into HTTPS", () => { + expect(httpsCloneUrl("git@github.com:l0ng-ai/opengui.git")).toBe("https://github.com/l0ng-ai/opengui.git"); + expect(httpsCloneUrl("git@github.com:12345/repo.git")).toBe("https://github.com/12345/repo.git"); + expect(httpsCloneUrl("ssh://git@gitlab.com/group/sub/app.git")).toBe("https://gitlab.com/group/sub/app.git"); + expect(httpsCloneUrl("ssh://git@github.com:22/12345/repo.git")).toBe("https://github.com/12345/repo.git"); + }); + it("leaves HTTPS, self-hosted, and malformed addresses alone", () => { + expect(httpsCloneUrl("https://github.com/o/r.git")).toBeNull(); + expect(httpsCloneUrl("git@git.example.com:o/r.git")).toBeNull(); + expect(httpsCloneUrl("git@github.com/o/r.git")).toBeNull(); + expect(httpsCloneUrl("git@github.com:")).toBeNull(); + }); +}); + +describe("isSshAccessError", () => { + it("recognises refused keys and hidden repositories", () => { + expect(isSshAccessError("ERROR: Repository not found.\nfatal: Could not read from remote repository.")).toBe(true); + expect(isSshAccessError("git@github.com: Permission denied (publickey).")).toBe(true); + expect(isSshAccessError("fatal: destination path 'x' already exists")).toBe(false); + }); +}); diff --git a/src/features/vcs/__tests__/cloneHttpsFallback.test.tsx b/src/features/vcs/__tests__/cloneHttpsFallback.test.tsx new file mode 100644 index 0000000000..1e78026974 --- /dev/null +++ b/src/features/vcs/__tests__/cloneHttpsFallback.test.tsx @@ -0,0 +1,104 @@ +import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const desktop = vi.hoisted(() => vi.fn()); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + isTauri: () => false, + callDesktop: desktop, + nextRequestId: () => 4242, + commands: { ...real.commands, recentProjects: async () => [] }, + }; +}); + +vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ + ...(await importOriginal()), + Channel: class { + onmessage: ((line: string) => void) | null = null; + }, +})); + +import { CloneDialog } from "../clone"; + +beforeEach(() => { + localStorage.setItem("openidea.vcs.cloneParent", "/work"); +}); + +afterEach(() => { + localStorage.clear(); + desktop.mockReset(); +}); + +describe("CloneDialog HTTPS fallback", () => { + it("offers Clone with HTTPS on SSH access errors, retries over HTTPS, and hides when URL changes", async () => { + const onCloned = vi.fn(async () => {}); + desktop + .mockRejectedValueOnce(new Error("ERROR: Repository not found.\nfatal: Could not read from remote repository.")) + .mockResolvedValueOnce(undefined); + + render( {}} onCloned={onCloned} initialUrl="git@github.com:12345/private-repo.git" />); + + const cloneButton = screen.getByRole("button", { name: "Clone" }); + await waitFor(() => expect(cloneButton).toBeEnabled()); + await act(async () => fireEvent.click(cloneButton)); + + expect(desktop).toHaveBeenNthCalledWith( + 1, + "vcs_clone", + expect.objectContaining({ + url: "git@github.com:12345/private-repo.git", + dest: "/work/private-repo", + }), + ); + + const retryButton = await screen.findByRole("button", { name: "Clone with HTTPS" }); + expect(retryButton).toBeInTheDocument(); + + // Changing the URL hides the stale HTTPS fallback button. + const urlInput = screen.getByLabelText("URL:"); + fireEvent.change(urlInput, { target: { value: "git@github.com:12345/other.git" } }); + expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument(); + + // Restoring the failed URL shows the button again and clicking retries with HTTPS. + fireEvent.change(urlInput, { target: { value: "git@github.com:12345/private-repo.git" } }); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Clone with HTTPS" }))); + + expect(desktop).toHaveBeenNthCalledWith( + 2, + "vcs_clone", + expect.objectContaining({ + url: "https://github.com/12345/private-repo.git", + dest: "/work/private-repo", + }), + ); + expect(onCloned).toHaveBeenCalledWith("/work/private-repo"); + expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument(); + }); + + it("does not offer Clone with HTTPS for non-SSH errors", async () => { + desktop.mockRejectedValueOnce(new Error("fatal: destination path '/work/repo' already exists")); + + render( {}} initialUrl="git@github.com:org/repo.git" />); + const cloneButton = screen.getByRole("button", { name: "Clone" }); + await waitFor(() => expect(cloneButton).toBeEnabled()); + await act(async () => fireEvent.click(cloneButton)); + + expect(await screen.findByText(/already exists/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument(); + }); + + it("does not offer Clone with HTTPS for self-hosted SSH URLs", async () => { + desktop.mockRejectedValueOnce(new Error("git@git.example.com: Permission denied (publickey).")); + + render( {}} initialUrl="git@git.example.com:org/repo.git" />); + const cloneButton = screen.getByRole("button", { name: "Clone" }); + await waitFor(() => expect(cloneButton).toBeEnabled()); + await act(async () => fireEvent.click(cloneButton)); + + expect(await screen.findByText(/Permission denied/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Clone with HTTPS" })).not.toBeInTheDocument(); + }); +}); diff --git a/src/features/vcs/clone.module.css b/src/features/vcs/clone.module.css index be91696c48..3ccb684741 100644 --- a/src/features/vcs/clone.module.css +++ b/src/features/vcs/clone.module.css @@ -167,6 +167,13 @@ font-size: var(--fs-small); overflow-wrap: anywhere; } +.httpsRetry { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: var(--space-2); + margin-top: var(--space-2); +} .layout[data-compact] { flex-direction: column; diff --git a/src/features/vcs/clone.tsx b/src/features/vcs/clone.tsx index 0dfcb22df4..ca374489a2 100644 --- a/src/features/vcs/clone.tsx +++ b/src/features/vcs/clone.tsx @@ -80,6 +80,23 @@ export function validateClone(url: string, dir: string): string | null { return null; } +const HTTPS_HOSTS = new Set(["github.com", "gitlab.com", "bitbucket.org", "codeberg.org"]); + +/** The HTTPS address of an SSH `url` on a hosting service that serves both, or null. */ +export function httpsCloneUrl(url: string): string | null { + const u = url.trim(); + const m = /^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/(.+)$/i.exec(u) ?? /^[\w.-]+@([\w.-]+):(.+)$/.exec(u); + if (!m) return null; + const host = (m[1] ?? "").toLowerCase(); + const path = (m[2] ?? "").replace(/^\/+/, ""); + return HTTPS_HOSTS.has(host) && path ? `https://${host}/${path}` : null; +} + +/** Whether git's `message` says the SSH key it used was refused or cannot see the repository. */ +export function isSshAccessError(message: string): boolean { + return /Repository not found|Permission denied \(publickey|Could not read from remote repository/i.test(message); +} + /** A valid `git clone --depth` value, or null while the field is invalid. */ export function parseCloneDepth(value: string): number | null { const text = value.trim(); @@ -143,7 +160,11 @@ export const CLONED = "openidea://clone/cloned"; export function showCloneDialog(initialUrl = "", initialSystem?: "git" | "subversion", initialRevision = "") { if (!isTauri()) { - notifications().notify({ group: "vcs", level: "warning", title: "Cloning requires the desktop app" }); + notifications().notify({ + group: "vcs", + level: "warning", + title: "Cloning requires the desktop app", + }); return; } const inPage = () => @@ -283,8 +304,12 @@ export function CloneDialog({ const [svnRevision, setSvnRevision] = useState(initialRevision); const [svnDepth, setSvnDepth] = useState<"infinity" | "immediates" | "files" | "empty">("infinity"); const [svnIgnoreExternals, setSvnIgnoreExternals] = useState(false); - const [progress, setProgress] = useState<{ line: string; fraction: number | null }>({ line: "", fraction: null }); + const [progress, setProgress] = useState<{ + line: string; + fraction: number | null; + }>({ line: "", fraction: null }); const [error, setError] = useState(null); + const [httpsRetry, setHttpsRetry] = useState(null); const request = useRef(null); const urlField = useRef(null); const layout = useRef(null); @@ -326,7 +351,11 @@ export function CloneDialog({ if (!rect || !recentUrls.length) return; showContextMenu( { x: rect.left, y: rect.bottom }, - recentUrls.map((item) => ({ label: item, verbatim: true, run: () => setUrl(item) })), + recentUrls.map((item) => ({ + label: item, + verbatim: true, + run: () => setUrl(item), + })), ); }; @@ -373,6 +402,7 @@ export function CloneDialog({ if (validateClone(cloneUrl, target) || (shallow && !svn && depth === null) || svnRevInvalid || busy) return; setBusy(true); setError(null); + setHttpsRetry(null); const id = nextRequestId(); request.current = id; const channel = new Channel(); @@ -392,7 +422,13 @@ export function CloneDialog({ ignoreExternals: svnIgnoreExternals, }); else - await callDesktop("vcs_clone", { request: id, url: cloneUrl.trim(), dest: target, depth, onOutput: channel }); + await callDesktop("vcs_clone", { + request: id, + url: cloneUrl.trim(), + dest: target, + depth, + onOutput: channel, + }); writeParent(parentOf(target)); rememberUrl(cloneUrl.trim()); if (onCloned) { @@ -403,7 +439,11 @@ export function CloneDialog({ await openCloned(target); } catch (e) { if (isCancelled(e)) setError("Clone cancelled"); - else setError(e instanceof Error ? e.message : String(e)); + else { + const message = e instanceof Error ? e.message : String(e); + setError(message); + if (!svn && isSshAccessError(message)) setHttpsRetry(httpsCloneUrl(cloneUrl)); + } } finally { request.current = null; setBusy(false); @@ -412,7 +452,12 @@ export function CloneDialog({ }; const buttons: DialogButton[] = [ - { label: svn ? "Checkout" : "Clone", role: "default", disabled: !!invalid || busy, onClick: () => void clone() }, + { + label: svn ? "Checkout" : "Clone", + role: "default", + disabled: !!invalid || busy, + onClick: () => void clone(), + }, { label: "Cancel", role: "cancel", onClick: cancel }, ]; const sourceList = ( @@ -610,6 +655,19 @@ export function CloneDialog({ )} {error &&
{error}
} + {!busy && error && httpsRetry && httpsRetry === httpsCloneUrl(url) && ( +
+ + + The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, + such as GitHub CLI. + + + +
+ )} {!busy && !error && url.trim() && invalid && (
{invalid} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7712592e5a..601933de8b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -5785,5 +5785,7 @@ "Show Details": "Show Details", "Submit Request": "Submit Request", "{n} endpoint": "{n} endpoint", - "{n} endpoints": "{n} endpoints" + "{n} endpoints": "{n} endpoints", + "Clone with HTTPS": "Clone with HTTPS", + "The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI.": "The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index ef476db3dd..367ad9b866 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -12676,5 +12676,7 @@ "Show Details": "显示详情", "Submit Request": "提交请求", "{n} endpoint": "{n} 个端点", - "{n} endpoints": "{n} 个端点" + "{n} endpoints": "{n} 个端点", + "Clone with HTTPS": "通过 HTTPS 克隆", + "The SSH key may belong to another account. HTTPS uses the credentials of your Git credential helper, such as GitHub CLI.": "SSH 密钥可能属于另一个账号。HTTPS 会使用 Git 凭据助手(如 GitHub CLI)中的凭据。" }