diff --git a/e2e/projectGithubAccount.spec.ts b/e2e/projectGithubAccount.spec.ts index 280b447d10..f30a88e68a 100644 --- a/e2e/projectGithubAccount.spec.ts +++ b/e2e/projectGithubAccount.spec.ts @@ -51,6 +51,60 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]); }); +test("Update failure offers project-scoped GitHub account selection", async ({ workbench: page }) => { + await stubDesktop(page); + await page.evaluate(async () => { + let configuredAccount = ""; + const status = (): GhProjectAccountStatus => ({ + ghInstalled: true, + accounts: [ + { login: "alice", active: true }, + { login: "alice-work", active: false }, + ], + configuredAccount, + effectiveAccount: configuredAccount || "alice", + suggestedAccount: configuredAccount ? null : "alice-work", + }); + Object.assign(window.__ipc.handlers, { + vcs_branch_info: () => ({ head: "main", upstream: "origin/main", headCommit: "c1", operation: null }), + vcs_remote: () => { + throw { + kind: "invalid", + message: "remote: Repository not found.\nfatal: repository 'https://github.com/acme/private.git/' not found", + }; + }, + gh_project_account_status: () => status(), + gh_set_project_account: ({ account }: { account: string }) => { + configuredAccount = account; + return status(); + }, + settings_get_global: () => ({}), + window_open_settings: () => { + throw { kind: "unavailable", message: "separate settings window disabled in browser test" }; + }, + }); + const opsModule = "/src/features/vcs/ops.ts"; + const { runRemote } = await import(/* @vite-ignore */ opsModule); + await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/dev/acme-api"]); + }); + + await expect(page.getByText("Update failed", { exact: true })).toBeVisible(); + await expect(page.getByText(/Repository not found/)).toBeVisible(); + await expect(page.getByText(/alice may not have access/)).toBeVisible(); + expect(await ipcCalls(page, "gh_set_project_account")).toEqual([]); + const settingsLink = page.getByRole("button", { name: "GitHub Settings", exact: true }); + await expect(settingsLink).toBeVisible(); + if (process.env.CAPTURE_GH_AUTH_FAILURE) { + await page.screenshot({ path: process.env.CAPTURE_GH_AUTH_FAILURE, animations: "disabled" }); + } + await settingsLink.click(); + const dialog = page.getByRole("dialog", { name: "Settings", exact: true }); + await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)"); + await dialog.getByRole("button", { name: "Use alice-work for this project" }).click(); + await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work"); + expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]); +}); + test("adds a GitHub account in Settings › Version Control › GitHub with OAuth device-code banner", async ({ workbench: page, }) => { diff --git a/src/features/vcs/__tests__/remoteResults.test.ts b/src/features/vcs/__tests__/remoteResults.test.ts index 2c096bc5f4..82e5436e96 100644 --- a/src/features/vcs/__tests__/remoteResults.test.ts +++ b/src/features/vcs/__tests__/remoteResults.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { BranchInfo, FetchReport, PushReport, RemoteOp } from "@/bindings"; +import type { BranchInfo, FetchReport, GhProjectAccountStatus, PushReport, RemoteOp } from "@/bindings"; let branch: Partial = {}; /** What a pull brings in: the head moves to `c2`, with these changed files and commits. */ @@ -10,6 +10,7 @@ let reports: Record = {}; let partialReport: PushReport | null = null; let remoteGate: Promise | null = null; let remoteRepos: Array = []; +const ghAccountStatus = vi.fn(); vi.mock("@tauri-apps/api/core", async (importOriginal) => ({ ...(await importOriginal()), @@ -51,6 +52,7 @@ vi.mock("@/platform/ipc", async (importOriginal) => { vcsDiffRevisions: async () => ({ status: "ok", data: Array.from({ length: pulled.files }, (_, i) => ({ i })) }), vcsLog: async () => ({ status: "ok", data: Array.from({ length: pulled.commits }, (_, i) => ({ i })) }), vcsFinishShelfBatch: async () => ({ status: "ok", data: null }), + ghProjectAccountStatus: () => ghAccountStatus(), cancelRequest: async () => ({ status: "ok", data: null }), }, }; @@ -73,11 +75,13 @@ import { import { pushTargets } from "../remoteUi"; import { useVcs } from "../store"; -type Note = { title: string; level: string; body?: string }; +type Note = { title: string; level: string; body?: string; actions?: Array<{ label: string; run: () => void }> }; let notes: Note[] = []; beforeEach(() => { notes = []; + ghAccountStatus.mockReset(); + ghAccountStatus.mockResolvedValue({ status: "ok", data: null }); provideNotificationService({ notify: (n) => void notes.push(n as Note), expire: () => {} }); }); @@ -101,6 +105,108 @@ const pushTitle = async () => { return notes.at(-1)!.title; }; +describe("GitHub HTTPS authentication failure", () => { + const message = + "remote: Repository not found.\nfatal: repository 'https://github.com/example/private.git/' not found"; + const multiAccount: GhProjectAccountStatus = { + ghInstalled: true, + accounts: [ + { login: "personal", active: true }, + { login: "work", active: false }, + ], + configuredAccount: "", + effectiveAccount: "personal", + suggestedAccount: "work", + }; + + it("preserves the Git error and opens project GitHub settings without changing accounts", async () => { + failure = { kind: "invalid", message }; + ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount }); + const settings = vi.fn(); + const unregister = registerActions([{ id: "file.settings", title: "Settings", run: settings }]); + try { + expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false); + const note = notes.at(-1)!; + expect(note.title).toBe("Update failed"); + expect(note.body).toContain(message); + expect(note.body).toContain("personal may not have access"); + expect(ghAccountStatus).toHaveBeenCalledTimes(1); + expect(settings).not.toHaveBeenCalled(); + expect(remoteRepos).toEqual(["/p"]); + note.actions?.find((action) => action.label === "GitHub Settings")?.run(); + await vi.waitFor(() => expect(settings).toHaveBeenCalledWith(expect.objectContaining({ arg: "vcs.github" }))); + } finally { + unregister(); + } + }); + + it.each([ + "fatal: repository 'https://gitlab.com/example/private.git/' not found", + "fatal: repository 'https://github.com.evil.example/private.git/' not found", + "fatal: repository 'git@github.com:example/private.git' not found", + "remote: Repository not found.", + "fatal: unable to access 'https://github.com/example/private.git/': Could not resolve host: github.com", + ])("does not check gh for unrelated errors: %s", async (message) => { + failure = { kind: "invalid", message }; + expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false); + expect(ghAccountStatus).not.toHaveBeenCalled(); + expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message }); + }); + + it("keeps the original failure when only one account is signed in", async () => { + failure = { kind: "invalid", message }; + ghAccountStatus.mockResolvedValue({ + status: "ok", + data: { ...multiAccount, accounts: multiAccount.accounts.slice(0, 1) }, + }); + expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false); + expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined }); + }); + + it("keeps the original failure when account detection is unavailable", async () => { + failure = { kind: "invalid", message }; + ghAccountStatus.mockRejectedValue(new Error("gh unavailable")); + expect(await runRemote({ op: "updateProjectBranch", rebase: false }, undefined, ["/p"])).toBe(false); + expect(notes.at(-1)).toMatchObject({ title: "Update failed", body: message, actions: undefined }); + }); + + it("offers the same guidance for push failures without retrying", async () => { + failure = { kind: "invalid", message }; + ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount }); + expect( + await pushTargets([ + { + repo: "/p", + op: { + op: "pushSelected", + selection: { branch: "main", revision: null, remote: "origin", target: "main" }, + force_with_lease: false, + set_upstream: false, + tags: null, + no_verify: false, + }, + }, + ]), + ).toBe(false); + expect(notes.at(-1)).toMatchObject({ + title: "Push failed", + body: expect.stringContaining("personal may not have access"), + actions: [expect.objectContaining({ label: "GitHub Settings" })], + }); + expect(remoteRepos).toEqual(["/p"]); + }); + + it("offers the same guidance for fetch authentication failures", async () => { + failure = { + kind: "invalid", + message: "fatal: Authentication failed for 'https://github.com/example/private.git/'", + }; + ghAccountStatus.mockResolvedValue({ status: "ok", data: multiAccount }); + expect(await runRemote({ op: "fetch" }, undefined, ["/p"])).toBe(false); + expect(notes.at(-1)?.actions?.map(({ label }) => label)).toEqual(["Show Git Console", "GitHub Settings"]); + }); +}); + describe("fetch result notification", () => { it("keeps successful remotes and pruned refs visible when other remotes fail", async () => { const showConsole = vi.fn(); diff --git a/src/features/vcs/__tests__/updateBranches.test.ts b/src/features/vcs/__tests__/updateBranches.test.ts index 9c59093c91..90679fc929 100644 --- a/src/features/vcs/__tests__/updateBranches.test.ts +++ b/src/features/vcs/__tests__/updateBranches.test.ts @@ -9,6 +9,7 @@ const mocks = vi.hoisted(() => ({ checkout: vi.fn(), notify: vi.fn(), openWorktree: vi.fn(), + ghAccountStatus: vi.fn(), })); vi.mock("@/platform/actions", async (original) => ({ ...(await original()), @@ -23,7 +24,15 @@ vi.mock("../ops", async (original) => ({ vi.mock("../openWorktree", () => ({ openWorktree: mocks.openWorktree })); vi.mock("@/platform/ipc", async (original) => { const real = await original(); - return { ...real, commands: { ...real.commands, vcsBranchInfo: mocks.head, vcsCheckout: mocks.checkout } }; + return { + ...real, + commands: { + ...real.commands, + vcsBranchInfo: mocks.head, + vcsCheckout: mocks.checkout, + ghProjectAccountStatus: mocks.ghAccountStatus, + }, + }; }); vi.mock("@/workbench/contributions", async (original) => ({ ...(await original()), @@ -123,6 +132,28 @@ describe("Update Selected", () => { expect(mocks.openWorktree).toHaveBeenCalledWith("/worktrees/topic", true); }); + it("offers GitHub account settings for an unchecked branch's HTTPS failure", async () => { + mocks.update.mockResolvedValue([ + result("topic", "failed", "/p", "fatal: repository 'https://github.com/acme/private.git/' not found"), + ]); + mocks.ghAccountStatus.mockResolvedValue({ + status: "ok", + data: { + ghInstalled: true, + accounts: [ + { login: "personal", active: true }, + { login: "work", active: false }, + ], + effectiveAccount: "personal", + }, + }); + await updateBranches([target("topic", "/p")]); + const [action] = mocks.notify.mock.lastCall![0].actions; + expect(action.label).toBe("GitHub Settings"); + action.run(); + expect(mocks.execute).toHaveBeenCalledWith("file.settings", "vcs.github"); + }); + it("offers Update Selected in the context menu of a multi-selection", () => { const selected = [target("a", "/p"), target("b", "/p")]; const items = branchMenu(selected[0]!.branch, "main", () => {}, { selected }); diff --git a/src/features/vcs/branchOps.ts b/src/features/vcs/branchOps.ts index b47909ea45..c3f420b910 100644 --- a/src/features/vcs/branchOps.ts +++ b/src/features/vcs/branchOps.ts @@ -17,6 +17,7 @@ import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { notifications } from "@/workbench/contributions"; import { openWorktree } from "./openWorktree"; +import { githubHttpsFailureHelp } from "./githubHttpsFailure"; import { activeRepository } from "./activeRepository"; import { ask, confirmChecked } from "@/workbench/messages"; import { branchNamePrefixes, isFavoriteBranch, isProtectedBranch, pushRecent, shortRemoteName } from "./branches"; @@ -1446,6 +1447,11 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) { const results = await runBranchUpdates(new Map([...byRepo].map(([repo, names]) => [repo, [...names]]))); if (!results || useProject.getState().project !== project) return; const { lines, ...summary } = branchUpdateSummary(results, heads.length > 1); + const help = await githubHttpsFailureHelp( + results.flatMap((r) => (r.status === "failed" && r.message ? [r.message] : [])), + ); + if (useProject.getState().project !== project) return; + if (help) lines.push(help.message); const body = createElement(Fragment, null, ...lines.map((line) => createElement("div", { key: line }, line))); const worktrees = [...new Set(results.flatMap((r) => (r.status === "failed" && r.worktree ? [r.worktree] : [])))]; notifications().notify({ @@ -1454,10 +1460,13 @@ export async function updateBranches(targets: readonly BranchUpdateTarget[]) { userInitiated: true, ...summary, body, - actions: worktrees.map((path) => { - const name = repoName(path); - return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) }; - }), + actions: [ + ...worktrees.map((path) => { + const name = repoName(path); + return { label: tx`Open Worktree ${name}`, run: () => void openWorktree(path, true) }; + }), + ...(help ? [help.action] : []), + ], }); } if (current.length && useProject.getState().project === project) await runRemoteRound(current); diff --git a/src/features/vcs/githubHttpsFailure.ts b/src/features/vcs/githubHttpsFailure.ts new file mode 100644 index 0000000000..0273f02acf --- /dev/null +++ b/src/features/vcs/githubHttpsFailure.ts @@ -0,0 +1,37 @@ +import { executeAction } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; + +/** GitHub deliberately uses "Repository not found" for inaccessible private repositories. + * Require Git's actual failing HTTPS URL: the same error from another host or SSH is unrelated + * to gh's HTTPS credential helper. Never infer a credential mismatch from the error alone. + */ +function isGithubHttpsFailure(message: string): boolean { + return /^fatal: (?:repository 'https:\/\/github\.com\/[^'\r\n]+' not found|Authentication failed for 'https:\/\/github\.com\/[^'\r\n]+')\.?(?:\r?$)/im.test( + message, + ); +} + +/** Diagnose only explicit failed remote operations. The existing project account settings + * handle selection; do not switch gh's global account, edit remotes, or retry a Git write. + */ +export async function githubHttpsFailureHelp(messages: readonly string[]) { + if (!messages.some(isGithubHttpsFailure)) return null; + const project = useProject.getState().project; + const status = await call(commands.ghProjectAccountStatus()).catch(() => null); + if (!status?.ghInstalled || status.accounts.length < 2 || useProject.getState().project !== project) return null; + return { + message: status.effectiveAccount + ? tx`GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, ${status.effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.` + : tx( + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.", + ), + action: { + label: "GitHub Settings", + run: () => { + if (useProject.getState().project === project) void executeAction("file.settings", "vcs.github"); + }, + }, + }; +} diff --git a/src/features/vcs/ops.ts b/src/features/vcs/ops.ts index e719f22a3c..556b5e9a0a 100644 --- a/src/features/vcs/ops.ts +++ b/src/features/vcs/ops.ts @@ -24,6 +24,7 @@ import { flushChangelists } from "./changelists"; import { pushHistoryRepo, rememberPushTarget } from "./pushHistory"; import { describePush, formatPushOutcomes, partialPushReport, pushedCommits, type RepoPushOutcome } from "./pushReport"; import { cancelIncomingCheck } from "./incomingRequest"; +import { githubHttpsFailureHelp } from "./githubHttpsFailure"; import { beginGitWork, conflictedFiles, currentRepo, refreshNow, repoName, repoOf, useVcs } from "./store"; // --------------------------------------------------------------------------- @@ -551,6 +552,13 @@ export async function runRemoteRound( : first.op === "unshallow" ? tx("Could not fetch full Git history") : `${doneTitle} failed`; + const help = await githubHttpsFailureHelp(remaining.map(({ error }) => errorMessage(error))); + if (cancelRequested || useProject.getState().project !== project) + throw new IpcError({ kind: "cancelled", message: "cancelled" }); + const actions = [ + ...(partial || isFetch ? [gitConsoleNotificationAction()] : []), + ...(help ? [help.action] : []), + ]; notify({ level: "error", key: "vcs.remote", @@ -561,9 +569,9 @@ export async function runRemoteRound( ? tx(message) : message, ) - .concat(pruned) + .concat(pruned, help ? [help.message] : []) .join("\n"), - actions: partial || isFetch ? [gitConsoleNotificationAction()] : undefined, + actions: actions.length ? actions : undefined, }); } if (!reported && isUpdate(first) && updated.length) await notifyUpdated(updated, "vcs.remote.updated"); diff --git a/src/features/vcs/remoteUi.tsx b/src/features/vcs/remoteUi.tsx index b2e822ffe1..ede885a2ac 100644 --- a/src/features/vcs/remoteUi.tsx +++ b/src/features/vcs/remoteUi.tsx @@ -26,6 +26,7 @@ import { openDialog } from "./dialogs"; import { useBranches } from "./gitMenuDialogs"; import { saveVcsSetting } from "./settingsUi"; import { formatTime } from "./model"; +import { githubHttpsFailureHelp } from "./githubHttpsFailure"; import { allRepos, errorMessage, @@ -1493,12 +1494,13 @@ function pushReviewActions(review: readonly PushReviewTarget[]) { ]; } -function pushFailed( +async function pushFailed( failures: RemoteFailure[], total: number, rejected: boolean, pushed: readonly RepoPushOutcome[], -): false { +): Promise { + const project = useProject.getState().project; const isPartial = ({ error }: RemoteFailure) => !!partialPushReport(error); const names = (items: RemoteFailure[]) => items.flatMap(({ target }) => (target.repo ? [repoName(target.repo)] : [])).join(", "); @@ -1521,7 +1523,11 @@ function pushFailed( : tx(errorMessage(failures[0]!.error)), ); } - const actions = pushReviewActions(review); + const help = await githubHttpsFailureHelp(failures.map(({ error }) => errorMessage(error))); + if (useProject.getState().project !== project) return false; + if (help) lines.push(help.message); + const actions = [...(pushReviewActions(review) ?? []), ...(help ? [help.action] : [])]; + if (partiallyApplied.length) actions.push(gitConsoleNotificationAction()); notifications().notify({ group: "vcs", level: "error", @@ -1534,7 +1540,7 @@ function pushFailed( ? "Push rejected" : "Push failed", body: lines.join("\n"), - actions: partiallyApplied.length ? [...(actions ?? []), gitConsoleNotificationAction()] : actions, + actions: actions.length ? actions : undefined, }); return false; } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 97f6e3cc1c..832a1f27ab 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4830,5 +4830,8 @@ "Create Library": "Create Library", "Library name": "Library name", "Library name cannot be empty.": "Library name cannot be empty.", - "A library with this name already exists.": "A library with this name already exists." + "A library with this name already exists.": "A library with this name already exists.", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.", + "GitHub Settings": "GitHub Settings" } diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 87c93aea88..8b556b9f19 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -9539,5 +9539,8 @@ "Create Library": "建立庫", "Library name": "庫名稱", "Library name cannot be empty.": "庫名稱不可為空。", - "A library with this name already exists.": "已存在同名的庫。" + "A library with this name already exists.": "已存在同名的庫。", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,{effectiveAccount} 可能沒有存取權限。請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登入了多個帳號。如果 Git 透過 gh 取得 HTTPS 憑證,請檢查遠端 URL,或在 GitHub 設定中選擇有權限的帳號後重試。", + "GitHub Settings": "GitHub 設定" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9b2eeecd96..70feddf67a 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11527,5 +11527,8 @@ "Create Library": "创建库", "Library name": "库名称", "Library name cannot be empty.": "库名称不能为空。", - "A library with this name already exists.": "已存在同名的库。" + "A library with this name already exists.": "已存在同名的库。", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, {effectiveAccount} may not have access. Check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,{effectiveAccount} 可能没有访问权限。请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。", + "GitHub CLI has multiple signed-in accounts. If Git uses gh for HTTPS credentials, check the remote URL or choose an account with access in GitHub settings, then retry.": "GitHub CLI 登录了多个账号。如果 Git 通过 gh 获取 HTTPS 凭据,请检查远程 URL,或在 GitHub 设置中选择有权限的账号后重试。", + "GitHub Settings": "GitHub 设置" }