дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(github): add in-IDE GitHub account sign-in in Settings, Pull Requests, and Clone (#6642)
Settings › Version Control › GitHub only listed accounts already signed in with gh, Clone Repository › GitHub told signed-out users to run gh auth login in a terminal, and Pull Requests opened a raw terminal tab. The PTY sign-in dialog and OAuth device-code parser move from features/agents to src/workbench/CliSignInDialog.tsx and src/platform/deviceCode.ts, so agents and GitHub share them without a cross-feature import. GitHub settings get Sign In… / Add account… (selecting a newly added second account for the project) and Install GitHub CLI when gh is missing; the Pull Requests tool window signs in in-IDE and reconnects, with Add account… in its error state, repository selector and account menu; Clone › GitHub gets Sign In… and Add account…. The merge with main carries the dialog's terminal-reply filtering and FIFO input over to the moved file. Co-authored-by: dengliu <[email protected]>
Цей коміт міститься в:
1 джерело
90734775b9
коміт
4c5f4fa1e1
25 files changed
+784
-86
No files matched your search
@@ -1,19 +1,31 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage?: (e: unknown) => void;
|
||||
},
|
||||
}));
|
||||
|
||||
const ghAccountRepos = vi.fn();
|
||||
const toolsList = vi.fn();
|
||||
const agentGhLoginSpawn = vi.fn();
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/ipc")>()),
|
||||
isTauri: () => true,
|
||||
commands: {
|
||||
ghAccountRepos: () => ghAccountRepos(),
|
||||
toolsList: () => toolsList(),
|
||||
agentGhLoginSpawn: (cols: number, rows: number, ch: unknown) => agentGhLoginSpawn(cols, rows, ch),
|
||||
termResize: () => Promise.resolve({ status: "ok", data: null }),
|
||||
termKill: () => Promise.resolve({ status: "ok", data: null }),
|
||||
},
|
||||
}));
|
||||
|
||||
import type { GhAccountRepo } from "@/bindings";
|
||||
import type { AgentLoginEvent, GhAccountRepo } from "@/bindings";
|
||||
import { registerAction } from "@/platform/actions";
|
||||
import { provideEmbeddedTerminal } from "@/workbench/contributions";
|
||||
import { GitHubCloneSource, matchRepos } from "./GitHubCloneSource";
|
||||
|
||||
const repo = (nameWithOwner: string, extra: Partial<GhAccountRepo> = {}): GhAccountRepo => ({
|
||||
@@ -29,8 +41,10 @@ const repos = [repo("me/app", { private: true, description: "The app" }), repo("
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
provideEmbeddedTerminal(undefined);
|
||||
ghAccountRepos.mockReset();
|
||||
toolsList.mockReset();
|
||||
agentGhLoginSpawn.mockReset();
|
||||
});
|
||||
|
||||
describe("GitHub clone source", () => {
|
||||
@@ -71,6 +85,43 @@ describe("GitHub clone source", () => {
|
||||
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
|
||||
});
|
||||
|
||||
it("signs in via the in-IDE GitHub CLI dialog from notLoggedIn and reloads repositories", async () => {
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: () => {},
|
||||
clear: () => {},
|
||||
focus: () => {},
|
||||
fit: () => {},
|
||||
dispose: () => {},
|
||||
}));
|
||||
let sendEvent: ((e: AgentLoginEvent) => void) | null = null;
|
||||
agentGhLoginSpawn.mockImplementation(async (_cols, _rows, ch: { onmessage?: (e: AgentLoginEvent) => void }) => {
|
||||
sendEvent = (event) => ch.onmessage?.(event);
|
||||
return { status: "ok", data: { id: 31, pid: 444, title: "gh" } };
|
||||
});
|
||||
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "notLoggedIn", message: "x" } });
|
||||
render(<GitHubCloneSource url="" onUrl={() => {}} onClone={() => {}} disabled={false} />);
|
||||
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Sign In…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(agentGhLoginSpawn).toHaveBeenCalledTimes(1));
|
||||
|
||||
act(() => {
|
||||
sendEvent?.({
|
||||
type: "output",
|
||||
data: "! First copy your one-time code: 4FE2-9B7D\r\nOpen https://github.com/login/device\r\n",
|
||||
});
|
||||
});
|
||||
expect(await screen.findByText("4FE2-9B7D")).toBeInTheDocument();
|
||||
|
||||
ghAccountRepos.mockResolvedValueOnce({ status: "ok", data: { kind: "ready", login: "me", repos } });
|
||||
act(() => {
|
||||
sendEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(screen.getByRole("option", { name: /me\/app/ })).toBeInTheDocument());
|
||||
expect(screen.getByRole("button", { name: "Add account…" })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("installs GitHub CLI in-app when missing and reloads repositories", async () => {
|
||||
const install = vi.fn().mockResolvedValue(undefined);
|
||||
const dispose = registerAction({ id: "tools.install", title: "Install", run: install });
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
listNavigate,
|
||||
} from "@/ui";
|
||||
import type { CloneSourceProps } from "@/workbench/contributions";
|
||||
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
|
||||
import { openInBrowser } from "../data/local";
|
||||
import styles from "./GitHubCloneSource.module.css";
|
||||
import { useRowHeight } from "@/ui/density";
|
||||
@@ -40,6 +41,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [installingGh, setInstallingGh] = useState(false);
|
||||
const [installError, setInstallError] = useState<string | null>(null);
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -76,6 +78,9 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
<T>Retry</T>
|
||||
</Button>
|
||||
);
|
||||
const signInDialog = signingIn ? (
|
||||
<CliSignInDialog target={{ kind: "gh" }} onClose={() => setSigningIn(false)} onCompleted={reload} />
|
||||
) : null;
|
||||
|
||||
if (!state)
|
||||
return (
|
||||
@@ -114,9 +119,22 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
);
|
||||
if (state.kind === "notLoggedIn")
|
||||
return (
|
||||
<EmptyState title="Not logged in to GitHub" actions={retry}>
|
||||
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
|
||||
</EmptyState>
|
||||
<>
|
||||
<EmptyState
|
||||
title="Not logged in to GitHub"
|
||||
actions={
|
||||
<>
|
||||
<Button size="small" variant="primary" onClick={() => setSigningIn(true)}>
|
||||
<T>Sign In…</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Sign in with GitHub CLI to list and clone your repositories.</T>
|
||||
</EmptyState>
|
||||
{signInDialog}
|
||||
</>
|
||||
);
|
||||
if (state.kind === "error")
|
||||
return (
|
||||
@@ -157,6 +175,9 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
disabled={disabled}
|
||||
data-autofocus
|
||||
/>
|
||||
<Button size="small" disabled={disabled} onClick={() => setSigningIn(true)}>
|
||||
<T>Add account…</T>
|
||||
</Button>
|
||||
</div>
|
||||
<div className={styles.list}>
|
||||
<List<Row>
|
||||
@@ -197,6 +218,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{signInDialog}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -62,6 +62,24 @@ export async function setProjectGithubAccount(account: string): Promise<GhProjec
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads GitHub CLI accounts after an in-IDE `gh auth login`. When the user already
|
||||
* had at least one account and added a new one, selects it for the project immediately.
|
||||
*/
|
||||
export async function refreshAfterGithubSignIn(
|
||||
prevLogins: ReadonlySet<string>,
|
||||
): Promise<GhProjectAccountStatus | null> {
|
||||
const fresh = await loadProjectGithubAccount();
|
||||
if (!fresh) return null;
|
||||
if (prevLogins.size > 0) {
|
||||
const added = fresh.accounts.find((entry) => !prevLogins.has(entry.login));
|
||||
if (added) {
|
||||
return (await setProjectGithubAccount(added.login)) ?? fresh;
|
||||
}
|
||||
}
|
||||
return fresh;
|
||||
}
|
||||
|
||||
export function projectAccountOptions(status: GhProjectAccountStatus | null): SelectOption[] {
|
||||
const accounts = status?.accounts ?? [];
|
||||
const configured = status?.configuredAccount ?? "";
|
||||
|
||||
@@ -3,12 +3,17 @@
|
||||
* account selection (`vcs.github.account`) and pull request review options. Applies at once,
|
||||
* like the Log page.
|
||||
*/
|
||||
import { useEffect, useId } from "react";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Button, Checkbox, Select, T } from "@/ui";
|
||||
import { isCancelled } from "@/platform/ipc";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import { Button, Checkbox, Select, Spinner, T } from "@/ui";
|
||||
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
|
||||
import {
|
||||
loadProjectGithubAccount,
|
||||
projectAccountOptions,
|
||||
refreshAfterGithubSignIn,
|
||||
setProjectGithubAccount,
|
||||
useGhProjectAccount,
|
||||
} from "../data/account";
|
||||
@@ -19,6 +24,10 @@ export function GithubSettingsPage() {
|
||||
const autoMarkViewed = useReviewDiffSettings((s) => s.autoMarkViewed);
|
||||
const status = useGhProjectAccount((s) => s.status);
|
||||
const saving = useGhProjectAccount((s) => s.saving);
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const [installingGh, setInstallingGh] = useState(false);
|
||||
const [installError, setInstallError] = useState<string | null>(null);
|
||||
const prevLoginsRef = useRef<Set<string>>(new Set());
|
||||
const accountHeading = useId();
|
||||
const prHeading = useId();
|
||||
const selectId = useId();
|
||||
@@ -30,6 +39,27 @@ export function GithubSettingsPage() {
|
||||
const options = projectAccountOptions(status);
|
||||
const value = status?.configuredAccount ?? "";
|
||||
const suggested = !value ? (status?.suggestedAccount ?? null) : null;
|
||||
const ghMissing = status !== null && !status.ghInstalled;
|
||||
const hasAccounts = (status?.accounts.length ?? 0) > 0;
|
||||
|
||||
const startSignIn = () => {
|
||||
prevLoginsRef.current = new Set((status?.accounts ?? []).map((entry) => entry.login));
|
||||
setSigningIn(true);
|
||||
};
|
||||
|
||||
const installGh = () => {
|
||||
if (installingGh) return;
|
||||
setInstallingGh(true);
|
||||
setInstallError(null);
|
||||
void installGhTool()
|
||||
.promise.then((installed) => {
|
||||
if (installed) void loadProjectGithubAccount();
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
|
||||
})
|
||||
.finally(() => setInstallingGh(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
@@ -53,6 +83,32 @@ export function GithubSettingsPage() {
|
||||
onChange={(next) => void setProjectGithubAccount(next)}
|
||||
/>
|
||||
</div>
|
||||
{status?.ghInstalled && (
|
||||
<Button
|
||||
size="small"
|
||||
variant={hasAccounts ? "secondary" : "primary"}
|
||||
disabled={saving}
|
||||
onClick={startSignIn}
|
||||
>
|
||||
<T>{hasAccounts ? "Add account…" : "Sign In…"}</T>
|
||||
</Button>
|
||||
)}
|
||||
{ghMissing && (
|
||||
<>
|
||||
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
|
||||
{installingGh ? (
|
||||
<>
|
||||
<Spinner size={12} /> <T>Installing…</T>
|
||||
</>
|
||||
) : (
|
||||
<T>Install GitHub CLI</T>
|
||||
)}
|
||||
</Button>
|
||||
<Button size="small" onClick={() => void openExternalUrl(GH_MANUAL_INSTALL_URL)}>
|
||||
<T>Download manually…</T>
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{suggested && (
|
||||
<Button size="small" disabled={saving} onClick={() => void setProjectGithubAccount(suggested)}>
|
||||
{tx`Use ${suggested} for this project`}
|
||||
@@ -60,7 +116,9 @@ export function GithubSettingsPage() {
|
||||
)}
|
||||
</div>
|
||||
<p className={styles.accountHint}>
|
||||
{value ? (
|
||||
{ghMissing ? (
|
||||
<T>Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.</T>
|
||||
) : value ? (
|
||||
<T>
|
||||
Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and
|
||||
run configurations).
|
||||
@@ -69,6 +127,11 @@ export function GithubSettingsPage() {
|
||||
<T>Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.</T>
|
||||
)}
|
||||
</p>
|
||||
{installError && (
|
||||
<p className={styles.accountHint} role="alert">
|
||||
{installError}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -82,6 +145,13 @@ export function GithubSettingsPage() {
|
||||
label="Automatically mark opened files as viewed"
|
||||
/>
|
||||
</section>
|
||||
{signingIn && (
|
||||
<CliSignInDialog
|
||||
target={{ kind: "gh" }}
|
||||
onClose={() => setSigningIn(false)}
|
||||
onCompleted={() => void refreshAfterGithubSignIn(prevLoginsRef.current)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { useSettingsPages } from "@/workbench/contributions";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage?: (e: unknown) => void;
|
||||
},
|
||||
}));
|
||||
|
||||
import type { AgentLoginEvent, GhProjectAccountStatus } from "@/bindings";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { provideEmbeddedTerminal, useSettingsPages } from "@/workbench/contributions";
|
||||
import { useGhProjectAccount } from "./data/account";
|
||||
import { activateSettingsPages } from "./settingsPages";
|
||||
import { GithubSettingsPage } from "./diff/GithubSettingsPage";
|
||||
@@ -15,6 +25,8 @@ beforeEach(() => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
provideEmbeddedTerminal(undefined);
|
||||
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
|
||||
});
|
||||
|
||||
@@ -85,4 +97,94 @@ describe("GitHub settings pages", () => {
|
||||
),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("runs in-IDE GitHub CLI sign-in from Add account… and selects the newly added account", async () => {
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: () => {},
|
||||
clear: () => {},
|
||||
focus: () => {},
|
||||
fit: () => {},
|
||||
dispose: () => {},
|
||||
}));
|
||||
vi.spyOn(ipc, "isTauri").mockReturnValue(true);
|
||||
let accounts = [{ login: "alice", active: true }];
|
||||
let configuredAccount = "";
|
||||
const makeStatus = (): GhProjectAccountStatus => ({
|
||||
ghInstalled: true,
|
||||
accounts,
|
||||
configuredAccount,
|
||||
effectiveAccount: configuredAccount || accounts.find((a) => a.active)?.login || null,
|
||||
suggestedAccount: null,
|
||||
});
|
||||
vi.spyOn(ipc.commands, "ghProjectAccountStatus").mockImplementation(async () => ({
|
||||
status: "ok",
|
||||
data: makeStatus(),
|
||||
}));
|
||||
const setAccountSpy = vi.spyOn(ipc.commands, "ghSetProjectAccount").mockImplementation(async (account: string) => {
|
||||
configuredAccount = account;
|
||||
return { status: "ok", data: makeStatus() };
|
||||
});
|
||||
vi.spyOn(ipc.commands, "termResize").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
vi.spyOn(ipc.commands, "termKill").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
let sendEvent: ((e: AgentLoginEvent) => void) | null = null;
|
||||
const spawnSpy = vi.spyOn(ipc.commands, "agentGhLoginSpawn").mockImplementation(async (_cols, _rows, ch) => {
|
||||
sendEvent = (event) => ch.onmessage?.(event);
|
||||
return { status: "ok", data: { id: 11, pid: 222, title: "gh" } };
|
||||
});
|
||||
|
||||
render(<GithubSettingsPage />);
|
||||
const addBtn = await screen.findByRole("button", { name: "Add account…" });
|
||||
fireEvent.click(addBtn);
|
||||
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1));
|
||||
|
||||
act(() => {
|
||||
sendEvent?.({
|
||||
type: "output",
|
||||
data: "! First copy your one-time code: AB12-CD34\r\nPress Enter to open https://github.com/login/device in your browser...",
|
||||
});
|
||||
});
|
||||
expect(await screen.findByText("AB12-CD34")).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Copy Code & Open Browser" })).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
accounts = [
|
||||
{ login: "alice", active: true },
|
||||
{ login: "alice-work", active: false },
|
||||
];
|
||||
sendEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(setAccountSpy).toHaveBeenCalledWith("alice-work"));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeNull());
|
||||
expect(screen.getByRole("button", { name: "GitHub account" })).toHaveTextContent("alice-work");
|
||||
});
|
||||
|
||||
it("shows primary Sign In… when gh is installed without accounts, and Install GitHub CLI when missing", async () => {
|
||||
useGhProjectAccount.setState({
|
||||
status: {
|
||||
ghInstalled: true,
|
||||
accounts: [],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: null,
|
||||
suggestedAccount: null,
|
||||
},
|
||||
});
|
||||
const { rerender } = render(<GithubSettingsPage />);
|
||||
expect(screen.getByRole("button", { name: "Sign In…" })).toBeInTheDocument();
|
||||
|
||||
useGhProjectAccount.setState({
|
||||
status: {
|
||||
ghInstalled: false,
|
||||
accounts: [],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: null,
|
||||
suggestedAccount: null,
|
||||
},
|
||||
});
|
||||
rerender(<GithubSettingsPage />);
|
||||
expect(screen.getByRole("button", { name: "Install GitHub CLI" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: "Download manually…" })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -12,12 +12,14 @@ import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
|
||||
import { isCancelled } from "@/platform/ipc";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
|
||||
import { CreatePanel } from "../create/CreatePanel";
|
||||
import { DetailsPanel } from "../details/DetailsPanel";
|
||||
import { ListPanel } from "../list/ListPanel";
|
||||
import {
|
||||
loadProjectGithubAccount,
|
||||
projectAccountOptions,
|
||||
refreshAfterGithubSignIn,
|
||||
setProjectGithubAccount,
|
||||
useGhProjectAccount,
|
||||
} from "../data/account";
|
||||
@@ -37,10 +39,36 @@ import {
|
||||
import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
|
||||
import styles from "./ToolWindow.module.css";
|
||||
|
||||
function ProjectAccountInline() {
|
||||
function useGhSignIn() {
|
||||
const [open, setOpen] = useState(false);
|
||||
const prevLoginsRef = useRef<Set<string>>(new Set());
|
||||
const start = () => {
|
||||
prevLoginsRef.current = new Set((useGhProjectAccount.getState().status?.accounts ?? []).map((a) => a.login));
|
||||
setOpen(true);
|
||||
};
|
||||
const dialog = open ? (
|
||||
<CliSignInDialog
|
||||
target={{ kind: "gh" }}
|
||||
onClose={() => setOpen(false)}
|
||||
onCompleted={() => {
|
||||
const beforeRev = useGhProjectAccount.getState().revision;
|
||||
void refreshAfterGithubSignIn(prevLoginsRef.current).finally(() => {
|
||||
// `setProjectGithubAccount` already bumps `revision` (which triggers `refreshConnection` in runtime.ts);
|
||||
// refresh explicitly when the active account changed under `Automatic` without changing `revision`.
|
||||
if (useGhProjectAccount.getState().revision === beforeRev) {
|
||||
void refreshConnection();
|
||||
}
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : null;
|
||||
return { start, dialog };
|
||||
}
|
||||
|
||||
function ProjectAccountInline({ onAddAccount }: { onAddAccount?: () => void }) {
|
||||
const status = useGhProjectAccount((s) => s.status);
|
||||
const saving = useGhProjectAccount((s) => s.saving);
|
||||
if (!status || status.accounts.length === 0) return null;
|
||||
if (!status || (status.accounts.length === 0 && !(onAddAccount && status.ghInstalled))) return null;
|
||||
const suggested = !status.configuredAccount ? status.suggestedAccount : null;
|
||||
return (
|
||||
<div className={styles.accountInline}>
|
||||
@@ -54,13 +82,22 @@ function ProjectAccountInline() {
|
||||
{tx`Use ${suggested} for this project`}
|
||||
</Button>
|
||||
)}
|
||||
<Select
|
||||
aria-label="GitHub account"
|
||||
value={status.configuredAccount}
|
||||
disabled={saving}
|
||||
options={projectAccountOptions(status)}
|
||||
onChange={(next) => void setProjectGithubAccount(next)}
|
||||
/>
|
||||
<div className={styles.accountInlineRow}>
|
||||
{status.accounts.length > 0 && (
|
||||
<Select
|
||||
aria-label="GitHub account"
|
||||
value={status.configuredAccount}
|
||||
disabled={saving}
|
||||
options={projectAccountOptions(status)}
|
||||
onChange={(next) => void setProjectGithubAccount(next)}
|
||||
/>
|
||||
)}
|
||||
{onAddAccount && status.ghInstalled && (
|
||||
<Button size="small" disabled={saving} onClick={onAddAccount}>
|
||||
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{status.configuredAccount && (
|
||||
<div className={styles.hint}>
|
||||
<T>
|
||||
@@ -73,7 +110,7 @@ function ProjectAccountInline() {
|
||||
);
|
||||
}
|
||||
|
||||
function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
function Unavailable({ availability, onSignIn }: { availability: GhAvailability; onSignIn: () => void }) {
|
||||
const [installingGh, setInstallingGh] = useState(false);
|
||||
const [installError, setInstallError] = useState<string | null>(null);
|
||||
const installGh = () => {
|
||||
@@ -82,7 +119,10 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
setInstallError(null);
|
||||
void installGhTool()
|
||||
.promise.then((installed) => {
|
||||
if (installed) void refreshConnection();
|
||||
if (installed) {
|
||||
void loadProjectGithubAccount();
|
||||
void refreshConnection();
|
||||
}
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
|
||||
@@ -127,24 +167,14 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
title="Not logged in to GitHub"
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
size="small"
|
||||
variant="primary"
|
||||
onClick={() =>
|
||||
void executeAction("terminal.runCommand", {
|
||||
program: "gh",
|
||||
args: ["auth", "login"],
|
||||
name: "gh auth login",
|
||||
})
|
||||
}
|
||||
>
|
||||
<T>Run gh auth login</T>
|
||||
<Button size="small" variant="primary" onClick={onSignIn}>
|
||||
<T>Sign In…</T>
|
||||
</Button>
|
||||
{retry}
|
||||
</>
|
||||
}
|
||||
>
|
||||
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
|
||||
<T>Sign in with GitHub CLI to view and review pull requests.</T>
|
||||
<ProjectAccountInline />
|
||||
</EmptyState>
|
||||
);
|
||||
@@ -161,7 +191,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
return (
|
||||
<EmptyState title="Could not reach GitHub" actions={retry}>
|
||||
<div>{availability.message}</div>
|
||||
<ProjectAccountInline />
|
||||
<ProjectAccountInline onAddAccount={onSignIn} />
|
||||
</EmptyState>
|
||||
);
|
||||
default:
|
||||
@@ -170,7 +200,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
|
||||
}
|
||||
|
||||
/** IntelliJ's repository selector: the repositories (owner always shown), project account, and "View Pull Requests". */
|
||||
function RepositorySelector() {
|
||||
function RepositorySelector({ onSignIn }: { onSignIn: () => void }) {
|
||||
const remotes = useGhRepository((s) => s.remotes);
|
||||
const defaultRemote = useGhRepository((s) => s.defaultRemote);
|
||||
const connecting = useGhRepository((s) => s.connecting);
|
||||
@@ -186,16 +216,23 @@ function RepositorySelector() {
|
||||
const hosts = new Set(remotes.map((r) => r.host ?? "github.com")).size > 1;
|
||||
return (
|
||||
<div className={styles.selector}>
|
||||
{status && status.accounts.length > 0 && (
|
||||
{status && (status.accounts.length > 0 || status.ghInstalled) && (
|
||||
<>
|
||||
<div className={styles.selectorRow}>
|
||||
<Select
|
||||
aria-label="GitHub account"
|
||||
value={status.configuredAccount}
|
||||
disabled={savingAccount}
|
||||
options={projectAccountOptions(status)}
|
||||
onChange={(next) => void setProjectGithubAccount(next)}
|
||||
/>
|
||||
{status.accounts.length > 0 && (
|
||||
<Select
|
||||
aria-label="GitHub account"
|
||||
value={status.configuredAccount}
|
||||
disabled={savingAccount}
|
||||
options={projectAccountOptions(status)}
|
||||
onChange={(next) => void setProjectGithubAccount(next)}
|
||||
/>
|
||||
)}
|
||||
{status.ghInstalled && (
|
||||
<Button size="small" disabled={savingAccount} onClick={onSignIn}>
|
||||
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
|
||||
</Button>
|
||||
)}
|
||||
{!status.configuredAccount && status.suggestedAccount && (
|
||||
<Button
|
||||
size="small"
|
||||
@@ -310,6 +347,7 @@ export function PullRequestsToolWindow() {
|
||||
const checking = useGhRepository((s) => s.checking);
|
||||
const connected = useGhRepository((s) => !!s.connection);
|
||||
const connecting = useGhRepository((s) => s.connecting);
|
||||
const signIn = useGhSignIn();
|
||||
useEffect(() => {
|
||||
if (!useGhProjectAccount.getState().status) void loadProjectGithubAccount();
|
||||
if (!useGhRepository.getState().availability) void refreshConnection();
|
||||
@@ -320,7 +358,13 @@ export function PullRequestsToolWindow() {
|
||||
{checking && <Spinner size={14} />} {tx("Connecting to GitHub…")}
|
||||
</div>
|
||||
);
|
||||
if (availability.kind !== "ready") return <Unavailable availability={availability} />;
|
||||
if (availability.kind !== "ready")
|
||||
return (
|
||||
<>
|
||||
<Unavailable availability={availability} onSignIn={signIn.start} />
|
||||
{signIn.dialog}
|
||||
</>
|
||||
);
|
||||
if (connected) return <Connected />;
|
||||
if (connecting)
|
||||
return (
|
||||
@@ -328,7 +372,12 @@ export function PullRequestsToolWindow() {
|
||||
<Spinner size={14} /> {tx("Connecting to GitHub…")}
|
||||
</div>
|
||||
);
|
||||
return <RepositorySelector />;
|
||||
return (
|
||||
<>
|
||||
<RepositorySelector onSignIn={signIn.start} />
|
||||
{signIn.dialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** The tab's context menu: Close Tab / Close Other Tabs for `#N` and New Pull Request tabs. */
|
||||
@@ -382,6 +431,7 @@ export function PullRequestsTabs() {
|
||||
export function PullRequestsHeaderActions() {
|
||||
const connection = useGhRepository((s) => s.connection);
|
||||
const status = useGhProjectAccount((s) => s.status);
|
||||
const signIn = useGhSignIn();
|
||||
if (!connection) return null;
|
||||
const showAccount = (status?.accounts.length ?? 0) > 1 || !!status?.configuredAccount;
|
||||
const activeLogin = connection.currentUser.login || status?.effectiveAccount || "";
|
||||
@@ -420,6 +470,15 @@ export function PullRequestsHeaderActions() {
|
||||
checked: configured === a.login,
|
||||
run: () => void setProjectGithubAccount(a.login),
|
||||
})),
|
||||
...(status.ghInstalled
|
||||
? [
|
||||
{ kind: "separator" as const },
|
||||
{
|
||||
label: "Add account…",
|
||||
run: signIn.start,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
showContextMenu(e, items);
|
||||
}}
|
||||
@@ -429,6 +488,7 @@ export function PullRequestsHeaderActions() {
|
||||
)}
|
||||
<IconButton icon="plus" size="small" iconSize={16} action="github.createPullRequest" />
|
||||
<IconButton icon="locate" size="small" iconSize={16} action="github.selectOpenedPullRequest" />
|
||||
{signIn.dialog}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -64,6 +64,13 @@
|
||||
gap: var(--space-1-5);
|
||||
margin-top: 8px;
|
||||
}
|
||||
.accountInlineRow {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
/* Repository selector (several GitHub remotes) */
|
||||
.selector {
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", async (original) => ({
|
||||
...(await original<typeof import("@tauri-apps/api/core")>()),
|
||||
Channel: class {
|
||||
onmessage?: (e: unknown) => void;
|
||||
},
|
||||
}));
|
||||
|
||||
import type { AgentLoginEvent } from "@/bindings";
|
||||
import { getAction, registerAction } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import * as ipc from "@/platform/ipc";
|
||||
import { provideToolWindowService, useContributions, type ToolWindowService } from "@/workbench/contributions";
|
||||
import {
|
||||
provideEmbeddedTerminal,
|
||||
provideToolWindowService,
|
||||
useContributions,
|
||||
type ToolWindowService,
|
||||
} from "@/workbench/contributions";
|
||||
import { activate } from "../index";
|
||||
import { setCurrentRepository } from "../api/client";
|
||||
import type { GHRepository, GHUser } from "../api/types";
|
||||
@@ -90,6 +104,7 @@ describe("tool window", () => {
|
||||
afterEach(() => {
|
||||
dispose();
|
||||
vi.restoreAllMocks();
|
||||
provideEmbeddedTerminal(undefined);
|
||||
setCurrentRepository(null);
|
||||
useGhRepository.setState({ connection: null, availability: null, remotes: [] });
|
||||
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
|
||||
@@ -237,4 +252,91 @@ describe("tool window", () => {
|
||||
const badge = screen.getByRole("button", { name: "@alice" });
|
||||
expect(badge).toHaveAttribute("title", "Use alice-work for this project");
|
||||
});
|
||||
|
||||
it("opens the in-IDE GitHub CLI sign-in dialog from notLoggedIn and refreshes connection on completion", async () => {
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: () => {},
|
||||
clear: () => {},
|
||||
focus: () => {},
|
||||
fit: () => {},
|
||||
dispose: () => {},
|
||||
}));
|
||||
vi.spyOn(ipc.commands, "termResize").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
vi.spyOn(ipc.commands, "termKill").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
let sendEvent: ((e: AgentLoginEvent) => void) | null = null;
|
||||
const spawnSpy = vi.spyOn(ipc.commands, "agentGhLoginSpawn").mockImplementation(async (_cols, _rows, ch) => {
|
||||
sendEvent = (event) => ch.onmessage?.(event);
|
||||
return { status: "ok", data: { id: 21, pid: 333, title: "gh" } };
|
||||
});
|
||||
const refresh = vi.spyOn(repositoryData, "refreshConnection").mockResolvedValue(undefined);
|
||||
|
||||
useGhRepository.setState({ availability: { kind: "notLoggedIn", message: "not logged in" } });
|
||||
useGhProjectAccount.setState({
|
||||
status: {
|
||||
ghInstalled: true,
|
||||
accounts: [],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: null,
|
||||
suggestedAccount: null,
|
||||
},
|
||||
});
|
||||
render(<PullRequestsToolWindow />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Sign In…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1));
|
||||
|
||||
act(() => {
|
||||
sendEvent?.({
|
||||
type: "output",
|
||||
data: "! First copy your one-time code: 9F8E-7D6C\r\nOpen https://github.com/login/device\r\n",
|
||||
});
|
||||
});
|
||||
expect(await screen.findByText("9F8E-7D6C")).toBeInTheDocument();
|
||||
|
||||
act(() => {
|
||||
sendEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
|
||||
await waitFor(() => expect(refresh).toHaveBeenCalledTimes(1));
|
||||
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeNull());
|
||||
});
|
||||
|
||||
it("offers Add account… in the repository selector and connected header account menu", async () => {
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: () => {},
|
||||
clear: () => {},
|
||||
focus: () => {},
|
||||
fit: () => {},
|
||||
dispose: () => {},
|
||||
}));
|
||||
vi.spyOn(ipc.commands, "termResize").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
vi.spyOn(ipc.commands, "termKill").mockResolvedValue({ status: "ok", data: null } as never);
|
||||
const spawnSpy = vi.spyOn(ipc.commands, "agentGhLoginSpawn").mockResolvedValue({
|
||||
status: "ok",
|
||||
data: { id: 22, pid: 334, title: "gh" },
|
||||
});
|
||||
|
||||
useGhProjectAccount.setState({
|
||||
status: {
|
||||
ghInstalled: true,
|
||||
accounts: [{ login: "alice", active: true }],
|
||||
configuredAccount: "",
|
||||
effectiveAccount: "alice",
|
||||
suggestedAccount: null,
|
||||
},
|
||||
});
|
||||
useGhRepository.setState({
|
||||
availability: { kind: "ready", repo: {} as never, login: "alice" },
|
||||
remotes: [
|
||||
{ owner: "alice", name: "app", remote: "origin", url: "" },
|
||||
{ owner: "org", name: "app", remote: "upstream", url: "" },
|
||||
],
|
||||
});
|
||||
render(<PullRequestsToolWindow />);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Add account…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
|
||||
await waitFor(() => expect(spawnSpy).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Заблокувати користувача