Порівняти коміти

...
10 змінених файлів з 276 додано та 16 видалено

No files matched your search

+54
Переглянути файл
@@ -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,
}) => {
+108 -2
Переглянути файл
@@ -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<BranchInfo> = {};
/** What a pull brings in: the head moves to `c2`, with these changed files and commits. */
@@ -10,6 +10,7 @@ let reports: Record<string, PushReport | FetchReport> = {};
let partialReport: PushReport | null = null;
let remoteGate: Promise<void> | null = null;
let remoteRepos: Array<string | null> = [];
const ghAccountStatus = vi.fn();
vi.mock("@tauri-apps/api/core", async (importOriginal) => ({
...(await importOriginal<typeof import("@tauri-apps/api/core")>()),
@@ -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 '[email protected]: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();
+32 -1
Переглянути файл
@@ -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<typeof import("@/platform/actions")>()),
@@ -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<typeof import("@/platform/ipc")>();
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<typeof import("@/workbench/contributions")>()),
@@ -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 });
+13 -4
Переглянути файл
@@ -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);
+37
Переглянути файл
@@ -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");
},
},
};
}
+10 -2
Переглянути файл
@@ -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<Op extends RemoteOp>(
: 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<Op extends RemoteOp>(
? 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");
+10 -4
Переглянути файл
@@ -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<PushOp>[],
total: number,
rejected: boolean,
pushed: readonly RepoPushOutcome[],
): false {
): Promise<false> {
const project = useProject.getState().project;
const isPartial = ({ error }: RemoteFailure<PushOp>) => !!partialPushReport(error);
const names = (items: RemoteFailure<PushOp>[]) =>
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;
}
+4 -1
Переглянути файл
@@ -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"
}
+4 -1
Переглянути файл
@@ -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 設定"
}
+4 -1
Переглянути файл
@@ -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 设置"
}