diff --git a/e2e/projectGithubAccount.spec.ts b/e2e/projectGithubAccount.spec.ts index 1124d6f759..280b447d10 100644 --- a/e2e/projectGithubAccount.spec.ts +++ b/e2e/projectGithubAccount.spec.ts @@ -50,3 +50,237 @@ test("suggests and configures a project-scoped GitHub account in Settings › Ve ).toBeVisible(); 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, +}) => { + await page.setViewportSize({ width: 1280, height: 840 }); + await stubDesktop(page); + await page.evaluate(() => { + let configuredAccount = ""; + let accounts = [{ login: "alice", active: true }]; + let loginChannel: unknown = null; + const makeStatus = (): GhProjectAccountStatus => ({ + ghInstalled: true, + accounts, + configuredAccount, + effectiveAccount: configuredAccount || accounts.find((a) => a.active)?.login || null, + suggestedAccount: null, + }); + (window as unknown as { __finishGhLogin?: () => void }).__finishGhLogin = () => { + accounts = [ + { login: "alice", active: true }, + { login: "alice-work", active: false }, + ]; + window.__ipc.send(loginChannel, { type: "exited", code: 0 }); + }; + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + gh_project_account_status: () => makeStatus(), + gh_set_project_account: ({ account }: { account: string }) => { + configuredAccount = account; + return makeStatus(); + }, + agent_gh_login_spawn: ({ onEvent }: { onEvent: unknown }) => { + loginChannel = onEvent; + setTimeout(() => { + window.__ipc.send(onEvent, { + type: "output", + data: + "! First copy your one-time code: AB12-CD34\r\n" + + "Press Enter to open https://github.com/login/device in your browser...\r\n", + }); + }, 40); + return { id: 101, pid: 5001, title: "gh" }; + }, + term_resize: () => null, + term_write: () => null, + term_kill: () => null, + }); + }); + + const dialog = await openGithubSettings(page); + await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("Automatic (alice)"); + const addBtn = dialog.getByRole("button", { name: "Add account…" }); + await expect(addBtn).toBeVisible(); + + const screenshotDir = process.env.CAPTURE_GH_SIGNIN_SCREENSHOTS; + if (screenshotDir) { + await page.waitForTimeout(150); + await dialog.screenshot({ path: `${screenshotDir}/after-settings-github.png`, animations: "disabled" }); + } + + await addBtn.click(); + const signInDialog = page.getByRole("dialog", { name: "Sign In to GitHub CLI" }); + await expect(signInDialog).toBeVisible(); + const deviceBanner = signInDialog.getByRole("region", { name: "Device verification code" }); + await expect(deviceBanner.getByText("AB12-CD34", { exact: true })).toBeVisible(); + await expect(deviceBanner.getByRole("button", { name: "Copy Code & Open Browser" })).toBeVisible(); + + if (screenshotDir) { + await page.waitForTimeout(150); + await page.screenshot({ path: `${screenshotDir}/after-settings-github-device-code.png`, animations: "disabled" }); + } + + await page.evaluate(() => (window as unknown as { __finishGhLogin?: () => void }).__finishGhLogin?.()); + await expect(signInDialog).toHaveCount(0); + await expect(dialog.getByRole("button", { name: "GitHub account" })).toContainText("alice-work"); +}); + +test("signs in via the in-IDE GitHub CLI dialog from Pull Requests and Clone Repository", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1280, height: 840 }); + await stubDesktop(page); + await page.evaluate(() => { + let signedIn = false; + let loginChannel: unknown = null; + (window as unknown as { __finishGhLogin?: () => void }).__finishGhLogin = () => { + signedIn = true; + window.__ipc.send(loginChannel, { type: "exited", code: 0 }); + }; + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + vcs_roots: () => [{ root: "/dev/acme-api", name: "acme-api", branch: "main" }], + vcs_remotes: () => [{ name: "origin", url: "https://github.com/acme/api.git", resolvedUrl: null }], + gh_project_account_status: (): GhProjectAccountStatus => ({ + ghInstalled: true, + accounts: signedIn ? [{ login: "alice", active: true }] : [], + configuredAccount: "", + effectiveAccount: signedIn ? "alice" : null, + suggestedAccount: null, + }), + gh_availability: () => + signedIn + ? { kind: "ready", login: "alice", repo: { nameWithOwner: "acme/api", url: "https://github.com/acme/api" } } + : { kind: "notLoggedIn", message: "not logged in" }, + gh_api: ({ request }: { request: { endpoint: string } }) => { + if (request.endpoint === "user") return JSON.stringify({ login: "alice", id: 1 }); + return JSON.stringify({ + data: { + repository: { + id: "R1", + owner: { __typename: "Organization", id: "O1", login: "acme" }, + nameWithOwner: "acme/api", + viewerPermission: "WRITE", + mergeCommitAllowed: true, + squashMergeAllowed: true, + rebaseMergeAllowed: true, + defaultBranchRef: { name: "main" }, + isFork: false, + url: "https://github.com/acme/api", + sshUrl: "git@github.com:acme/api.git", + }, + viewer: { __typename: "User", id: "U1", login: "alice", url: "https://github.com/alice", avatarUrl: "" }, + search: { + pageInfo: { startCursor: null, endCursor: null, hasNextPage: false, hasPreviousPage: false }, + nodes: [], + }, + }, + }); + }, + gh_account_repos: () => + signedIn + ? { + kind: "ready", + login: "alice", + repos: [ + { + nameWithOwner: "acme/api", + description: "Backend service", + private: true, + fork: false, + archived: false, + cloneUrl: "https://github.com/acme/api.git", + }, + ], + } + : { kind: "notLoggedIn", message: "not logged in" }, + agent_gh_login_spawn: ({ onEvent }: { onEvent: unknown }) => { + loginChannel = onEvent; + setTimeout(() => { + window.__ipc.send(onEvent, { + type: "output", + data: + "! First copy your one-time code: 9F8E-7D6C\r\n" + + "Press Enter to open https://github.com/login/device in your browser...\r\n", + }); + }, 40); + return { id: 102, pid: 5002, title: "gh" }; + }, + term_resize: () => null, + term_write: () => null, + term_kill: () => null, + }); + }); + + // 1. Open Clone Repository › GitHub while signed out. + await page.evaluate(async () => { + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("vcs.clone"); + }); + const cloneDialog = page.getByRole("dialog", { name: "Clone Repository" }); + await expect(cloneDialog).toBeVisible(); + await cloneDialog + .getByRole("complementary", { name: "Clone source" }) + .getByRole("button", { name: "GitHub" }) + .click(); + await expect(cloneDialog.getByText("Not logged in to GitHub")).toBeVisible(); + const cloneSignInBtn = cloneDialog.getByRole("button", { name: "Sign In…" }); + await expect(cloneSignInBtn).toBeVisible(); + + const screenshotDir = process.env.CAPTURE_GH_SIGNIN_SCREENSHOTS; + if (screenshotDir) { + await page.waitForTimeout(150); + await cloneDialog.screenshot({ path: `${screenshotDir}/after-clone-not-logged-in.png`, animations: "disabled" }); + } + + // Close Clone dialog and test Pull Requests tool window Sign In… flow. + await cloneDialog.getByRole("button", { name: "Cancel" }).click(); + await expect(cloneDialog).toHaveCount(0); + + await page.evaluate(async () => { + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("github.pullRequests"); + }); + await expect(page.getByText("Not logged in to GitHub")).toBeVisible(); + const prSignInBtn = page.getByRole("button", { name: "Sign In…" }); + await expect(prSignInBtn).toBeVisible(); + + if (screenshotDir) { + await page.waitForTimeout(150); + await page.screenshot({ path: `${screenshotDir}/after-pr-not-logged-in.png`, animations: "disabled" }); + } + + await prSignInBtn.click(); + const signInDialog = page.getByRole("dialog", { name: "Sign In to GitHub CLI" }); + await expect(signInDialog).toBeVisible(); + const deviceBanner = signInDialog.getByRole("region", { name: "Device verification code" }); + await expect(deviceBanner.getByText("9F8E-7D6C", { exact: true })).toBeVisible(); + await expect(deviceBanner.getByRole("button", { name: "Copy Code & Open Browser" })).toBeVisible(); + + await page.evaluate(() => (window as unknown as { __finishGhLogin?: () => void }).__finishGhLogin?.()); + await expect(signInDialog).toHaveCount(0); + await expect(page.getByRole("textbox", { name: "Search pull requests" })).toBeVisible(); + + // Reopen Clone Repository › GitHub now that gh is signed in. + await page.evaluate(async () => { + const actionsPath = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsPath); + await executeAction("vcs.clone"); + }); + await expect(cloneDialog).toBeVisible(); + await cloneDialog + .getByRole("complementary", { name: "Clone source" }) + .getByRole("button", { name: "GitHub" }) + .click(); + await expect(cloneDialog.getByRole("option", { name: /acme\/api/ })).toBeVisible(); + await expect(cloneDialog.getByRole("button", { name: "Add account…" })).toBeVisible(); + + if (screenshotDir) { + await page.waitForTimeout(150); + await cloneDialog.screenshot({ path: `${screenshotDir}/after-clone-signed-in.png`, animations: "disabled" }); + } +}); diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index e1524f1d2b..a84dbc815c 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -36,7 +36,7 @@ import { } from "@/ui"; import { useSettingsForm } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; -import { AgentSignInDialog, type SignInTarget } from "./AgentSignInDialog"; +import { CliSignInDialog, type SignInTarget } from "@/workbench/CliSignInDialog"; import { LocalCliUpdate } from "./LocalCliUpdate"; import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel"; import { providerIcon, slugifyId } from "./model"; @@ -1193,7 +1193,7 @@ function ProviderSettings({ )} {signInTarget && ( - setSignInTarget(null)} diff --git a/src/features/agents/session/messages.tsx b/src/features/agents/session/messages.tsx index ab0062ef4c..2d396ee6fa 100644 --- a/src/features/agents/session/messages.tsx +++ b/src/features/agents/session/messages.tsx @@ -8,7 +8,7 @@ import { notifications } from "@/workbench/contributions"; import clsx from "clsx"; import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react"; import { AgentReply, MessageActions, ReplyActions } from "../AgentReply"; -import { AgentSignInDialog } from "../AgentSignInDialog"; +import { CliSignInDialog } from "@/workbench/CliSignInDialog"; import { ImageStrip } from "../ImageStrip"; import { ReferencedText } from "../ReferenceChip"; import styles from "../Session.module.css"; @@ -261,7 +261,7 @@ function AgentErrorEntry({ task, message }: { task: AgentTask; message: string } )} {signingIn && ( - setSigningIn(false)} onCompleted={() => { diff --git a/src/features/github/clone/GitHubCloneSource.test.tsx b/src/features/github/clone/GitHubCloneSource.test.tsx index 9c1614343f..63189a833d 100644 --- a/src/features/github/clone/GitHubCloneSource.test.tsx +++ b/src/features/github/clone/GitHubCloneSource.test.tsx @@ -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()), + 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()), 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 => ({ @@ -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( {}} 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 }); diff --git a/src/features/github/clone/GitHubCloneSource.tsx b/src/features/github/clone/GitHubCloneSource.tsx index b1a22bfdbe..f1741b48cb 100644 --- a/src/features/github/clone/GitHubCloneSource.tsx +++ b/src/features/github/clone/GitHubCloneSource.tsx @@ -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(null); + const [signingIn, setSigningIn] = useState(false); useEffect(() => { let alive = true; @@ -76,6 +78,9 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource Retry ); + const signInDialog = signingIn ? ( + 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 ( - - Run gh auth login in a terminal, then retry. - + <> + + + {retry} + + } + > + Sign in with GitHub CLI to list and clone your repositories. + + {signInDialog} + ); if (state.kind === "error") return ( @@ -157,6 +175,9 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource disabled={disabled} data-autofocus /> +
@@ -197,6 +218,7 @@ export function GitHubCloneSource({ url, onUrl, onClone, disabled }: CloneSource )} />
+ {signInDialog} ); } diff --git a/src/features/github/data/account.ts b/src/features/github/data/account.ts index f28f940896..59c45ce787 100644 --- a/src/features/github/data/account.ts +++ b/src/features/github/data/account.ts @@ -62,6 +62,24 @@ export async function setProjectGithubAccount(account: string): Promise, +): Promise { + 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 ?? ""; diff --git a/src/features/github/diff/GithubSettingsPage.tsx b/src/features/github/diff/GithubSettingsPage.tsx index 40dd830129..1c4f5fee74 100644 --- a/src/features/github/diff/GithubSettingsPage.tsx +++ b/src/features/github/diff/GithubSettingsPage.tsx @@ -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(null); + const prevLoginsRef = useRef>(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 (
@@ -53,6 +83,32 @@ export function GithubSettingsPage() { onChange={(next) => void setProjectGithubAccount(next)} />
+ {status?.ghInstalled && ( + + )} + {ghMissing && ( + <> + + + + )} {suggested && ( )} - void setProjectGithubAccount(next)} + /> + )} + {onAddAccount && status.ghInstalled && ( + + )} + {status.configuredAccount && (
@@ -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(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={ <> - {retry} } > - Run gh auth login in a terminal, then retry. + Sign in with GitHub CLI to view and review pull requests. ); @@ -161,7 +191,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) { return (
{availability.message}
- +
); 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 (
- {status && status.accounts.length > 0 && ( + {status && (status.accounts.length > 0 || status.ghInstalled) && ( <>
- void setProjectGithubAccount(next)} + /> + )} + {status.ghInstalled && ( + + )} {!status.configuredAccount && status.suggestedAccount && (
); - if (availability.kind !== "ready") return ; + if (availability.kind !== "ready") + return ( + <> + + {signIn.dialog} + + ); if (connected) return ; if (connecting) return ( @@ -328,7 +372,12 @@ export function PullRequestsToolWindow() { {tx("Connecting to GitHub…")}
); - return ; + return ( + <> + + {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() { )} + {signIn.dialog} ); } diff --git a/src/features/github/toolwindow/ToolWindow.module.css b/src/features/github/toolwindow/ToolWindow.module.css index 5378c6ddb5..8cf3512186 100644 --- a/src/features/github/toolwindow/ToolWindow.module.css +++ b/src/features/github/toolwindow/ToolWindow.module.css @@ -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 { diff --git a/src/features/github/toolwindow/toolwindow.test.tsx b/src/features/github/toolwindow/toolwindow.test.tsx index c35367329d..0914a12251 100644 --- a/src/features/github/toolwindow/toolwindow.test.tsx +++ b/src/features/github/toolwindow/toolwindow.test.tsx @@ -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()), + 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(); + + 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(); + + 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)); + }); }); diff --git a/src/features/agents/deviceCode.test.ts b/src/platform/deviceCode.test.ts similarity index 89% rename from src/features/agents/deviceCode.test.ts rename to src/platform/deviceCode.test.ts index 036f501bb8..b49cd336fe 100644 --- a/src/features/agents/deviceCode.test.ts +++ b/src/platform/deviceCode.test.ts @@ -61,6 +61,14 @@ describe("parseDeviceCodePrompt", () => { expect(parseDeviceCodePrompt(raw)?.code).toBe("BBBB-2222"); }); + it("matches all-caps code labels and preserves balanced parentheses in URLs", () => { + expect(parseDeviceCodePrompt("ONE-TIME CODE: K9P4M2X7Q at (https://auth.example.com/device/v1(beta)).")).toEqual({ + code: "K9P4M2X7Q", + url: "https://auth.example.com/device/v1(beta)", + needsEnterToPoll: false, + }); + }); + it("ignores regular browser OAuth callback URLs with UUIDs and copyright year ranges", () => { expect( parseDeviceCodePrompt( diff --git a/src/features/agents/deviceCode.ts b/src/platform/deviceCode.ts similarity index 83% rename from src/features/agents/deviceCode.ts rename to src/platform/deviceCode.ts index 8703e14449..fb8d71f723 100644 --- a/src/features/agents/deviceCode.ts +++ b/src/platform/deviceCode.ts @@ -2,7 +2,7 @@ * Extracts OAuth 2.0 device-authorization URLs and one-time user codes (`ABCD-1234`, etc.) * from interactive sign-in PTY output (`copilot login`, `gh auth login`, `codex login`, …). */ -import { isOpenable } from "@/platform/openUrl"; +import { isOpenable } from "./openUrl"; const MAX_BUFFER_CHARS = 16_384; // oxlint-disable-next-line no-control-regex @@ -19,11 +19,31 @@ const ESC_SINGLE_RE = /\x1b[@-_]/g; const CONTROL_OR_BOX_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f│┃╭╮╯╰┌┐└┘├┤┬┴┼─━═║╔╗╚╝]/g; const HTTPS_URL_RE = /https:\/\/[A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]+/g; -const TRAILING_PUNCT_RE = /[.,;:!?)'"\]]+$/; +const TRAILING_SIMPLE_PUNCT_RE = /[.,;:!?'"]+$/; const DEVICE_PATH_RE = /(?:^|\/)(?:device|devicelogin|activate|device-login|user-code)(?:\/|$)/i; const EXPLICIT_CODE_CUE_RE = /(?:one-time|device|verification)\s+code/i; const LABELED_CODE_RE = - /(?:[Oo]ne-time|[Dd]evice|[Vv]erification|[Uu]ser|[Ee]nter(?:\s+[Tt]he)?)\s+[Cc]ode(?:\s+[Ii]s)?\s*[::]?\s*([A-Z0-9]{4,6}-[A-Z0-9]{3,6}|[A-Z0-9]{8,9})(?![A-Za-z0-9-])/g; + /(?:[Oo]ne-time|ONE-TIME|[Dd]evice|DEVICE|[Vv]erification|VERIFICATION|[Uu]ser|USER|(?:[Ee]nter|ENTER)(?:\s+(?:[Tt]he|THE))?)\s+(?:[Cc]ode|CODE)(?:\s+(?:[Ii]s|IS))?\s*[::]?\s*([A-Z0-9]{4,6}-[A-Z0-9]{3,6}|[A-Z0-9]{8,9})(?![A-Za-z0-9-])/g; + +function trimTrailingUrlPunct(raw: string): string { + let out = raw; + for (;;) { + const trimmed = out.replace(TRAILING_SIMPLE_PUNCT_RE, ""); + if (trimmed !== out) { + out = trimmed; + continue; + } + if (out.endsWith(")") && out.split(")").length > out.split("(").length) { + out = out.slice(0, -1); + continue; + } + if (out.endsWith("]") && out.split("]").length > out.split("[").length) { + out = out.slice(0, -1); + continue; + } + return out; + } +} const HYPHENATED_CODE_RE = /(?:^|[^A-Za-z0-9-])([A-Z0-9]{4,5}-[A-Z0-9]{4,5})(?![A-Za-z0-9-])/g; const YEAR_RANGE_RE = /^(?:19|20)\d{2}-(?:19|20)\d{2}$/; const COMPLETE_URI_CODE_RE = /^[A-Za-z0-9]{4,8}(?:-[A-Za-z0-9]{3,8})?$/; @@ -62,7 +82,7 @@ export function parseDeviceCodePrompt(rawOutput: string): DeviceCodePrompt | nul let completeUriPrompt: { url: string; code: string; index: number } | null = null; for (const match of cleaned.matchAll(HTTPS_URL_RE)) { - const candidate = match[0].replace(TRAILING_PUNCT_RE, ""); + const candidate = trimTrailingUrlPunct(match[0]); if (!isOpenable(candidate)) continue; let parsed: URL; try { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index b154fc678c..8a7aa84c05 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4453,6 +4453,8 @@ "SQLite cannot drop the index of a primary key or unique constraint.": "SQLite cannot drop the index of a primary key or unique constraint.", "Cannot list the manage.py commands": "Cannot list the manage.py commands", "Install django-types into this project's virtual environment to complete Django model fields and managers": "Install django-types into this project's virtual environment to complete Django model fields and managers", + "Sign in with GitHub CLI to list and clone your repositories.": "Sign in with GitHub CLI to list and clone your repositories.", + "Sign in with GitHub CLI to view and review pull requests.": "Sign in with GitHub CLI to view and review pull requests.", "Find in Documentation": "Find in Documentation", "Previous Match": "Previous Match", "Next Match": "Next Match" diff --git a/src/platform/locales/text/es.json b/src/platform/locales/text/es.json index 9531fc1bd1..89f6de3c4e 100644 --- a/src/platform/locales/text/es.json +++ b/src/platform/locales/text/es.json @@ -1883,7 +1883,6 @@ "Run configurations": "Configuraciones de ejecución", "Run configurations and tests": "Configuraciones de ejecución y pruebas", "Run external linter on save": "Ejecutar linter externo al guardar", - "Run gh auth login": "Ejecutar gh auth login", "Run sessions": "Sesiones de ejecución", "Run the selected configuration under a sampling profiler": "Ejecutar la configuración seleccionada bajo un generador de perfiles por muestreo", "Run the selected configuration with coverage": "Ejecutar la configuración seleccionada con cobertura", @@ -2494,7 +2493,6 @@ "if statement": "instrucción if", "impl block": "bloque impl", "import default": "import predeterminado", - "in a terminal, then retry.": "en una terminal y vuelve a intentarlo.", "insert rows into a table": "insertar filas en una tabla", "inside your project.": "dentro de tu proyecto.", "is already assigned to:": "ya está asignado a:", diff --git a/src/platform/locales/text/fr.json b/src/platform/locales/text/fr.json index 639a558a46..21a94559c5 100644 --- a/src/platform/locales/text/fr.json +++ b/src/platform/locales/text/fr.json @@ -1801,7 +1801,6 @@ "Run configurations": "Configurations d'exécution", "Run configurations and tests": "Configurations d'exécution et tests", "Run external linter on save": "Exécuter le linter externe à l'enregistrement", - "Run gh auth login": "Exécuter gh auth login", "Run sessions": "Sessions d'exécution", "Run the selected configuration under a sampling profiler": "Exécuter la configuration sélectionnée sous un profileur par échantillonnage", "Run the selected configuration with coverage": "Exécuter la configuration sélectionnée avec couverture", @@ -2397,7 +2396,6 @@ "if statement": "instruction if", "impl block": "bloc impl", "import default": "import par défaut", - "in a terminal, then retry.": "dans un terminal, puis réessayez.", "insert rows into a table": "insérer des lignes dans une table", "inside your project.": "dans votre projet.", "is already assigned to:": "est déjà attribué à :", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 59876bc340..a9a87b22bb 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -1934,7 +1934,6 @@ "Run configurations": "실행 구성", "Run configurations and tests": "실행 구성 및 테스트", "Run external linter on save": "저장 시 외부 린터 실행", - "Run gh auth login": "gh auth login 실행", "Run sessions": "실행 세션", "Run the selected configuration under a sampling profiler": "선택한 구성을 샘플링 프로파일러로 실행", "Run the selected configuration with coverage": "선택한 구성을 커버리지와 함께 실행", @@ -2544,7 +2543,6 @@ "if statement": "if 문", "impl block": "impl 블록", "import default": "기본 import", - "in a terminal, then retry.": "을(를) 터미널에서 실행한 후 다시 시도하세요.", "insert rows into a table": "테이블에 행 삽입", "inside your project.": "프로젝트 내부에 있습니다.", "is already assigned to:": "이(가) 이미 할당된 대상:", diff --git a/src/platform/locales/text/pl.json b/src/platform/locales/text/pl.json index 6383ed704a..74c0644795 100644 --- a/src/platform/locales/text/pl.json +++ b/src/platform/locales/text/pl.json @@ -1874,7 +1874,6 @@ "Run configurations": "Konfiguracje uruchamiania", "Run configurations and tests": "Konfiguracje uruchamiania i testy", "Run external linter on save": "Uruchamiaj zewnętrzny linter przy zapisie", - "Run gh auth login": "Uruchom gh auth login", "Run sessions": "Sesje uruchamiania", "Run the selected configuration under a sampling profiler": "Uruchom wybraną konfigurację w profilerze próbkowym", "Run the selected configuration with coverage": "Uruchom wybraną konfigurację z pokryciem kodu", @@ -2472,7 +2471,6 @@ "if statement": "instrukcja if", "impl block": "blok impl", "import default": "import domyślny", - "in a terminal, then retry.": "w terminalu, a następnie ponów próbę.", "insert rows into a table": "wstaw wiersze do tabeli", "inside your project.": "wewnątrz Twojego projektu.", "is already assigned to:": "jest już przypisany do:", diff --git a/src/platform/locales/text/pt.json b/src/platform/locales/text/pt.json index 6db90977f7..de0e32f061 100644 --- a/src/platform/locales/text/pt.json +++ b/src/platform/locales/text/pt.json @@ -1874,7 +1874,6 @@ "Run configurations": "Configurações de execução", "Run configurations and tests": "Configurações de execução e testes", "Run external linter on save": "Executar linter externo ao salvar", - "Run gh auth login": "Executar gh auth login", "Run sessions": "Sessões de execução", "Run the selected configuration under a sampling profiler": "Executar a configuração selecionada em um profiler por amostragem", "Run the selected configuration with coverage": "Executar a configuração selecionada com cobertura", @@ -2473,7 +2472,6 @@ "if statement": "instrução if", "impl block": "bloco impl", "import default": "import padrão", - "in a terminal, then retry.": "em um terminal e tente novamente.", "insert rows into a table": "inserir linhas em uma tabela", "inside your project.": "dentro do seu projeto.", "is already assigned to:": "já está atribuído a:", diff --git a/src/platform/locales/text/ru.json b/src/platform/locales/text/ru.json index e1f3c26152..661e314d4e 100644 --- a/src/platform/locales/text/ru.json +++ b/src/platform/locales/text/ru.json @@ -3132,7 +3132,6 @@ "Run configurations": "Конфигурации запуска", "Run configurations and tests": "Конфигурации запуска и тесты", "Run external linter on save": "Запускать внешний линтер при сохранении", - "Run gh auth login": "Выполнить gh auth login", "Run sessions": "Сеансы запуска", "Run the selected configuration under a sampling profiler": "Запустить выбранную конфигурацию под сэмплирующим профилировщиком", "Run the selected configuration with coverage": "Запустить выбранную конфигурацию с покрытием", @@ -3809,7 +3808,6 @@ "if statement": "инструкция if", "impl block": "блок impl", "import default": "импорт по умолчанию", - "in a terminal, then retry.": "в терминале, затем повторите попытку.", "insert rows into a table": "вставить строки в таблицу", "inside your project.": "внутри вашего проекта.", "is already assigned to:": "уже назначено для:", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 22bd246cc2..c77274b57a 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -4600,7 +4600,6 @@ "Run configurations": "Çalıştırma yapılandırmaları", "Run configurations and tests": "Çalıştırma yapılandırmaları ve testler", "Run external linter on save": "Kaydederken harici linter çalıştır", - "Run gh auth login": "'gh auth login' komutunu çalıştır", "Run sessions": "Çalıştırma oturumları", "Run the selected configuration under a sampling profiler": "Seçili yapılandırmayı örneklemeli profilleyiciyle çalıştır", "Run the selected configuration with coverage": "Seçili yapılandırmayı kapsamayla çalıştır", @@ -5182,7 +5181,6 @@ "if statement": "if ifadesi", "impl block": "impl bloğu", "import default": "varsayılan içe aktarma", - "in a terminal, then retry.": "terminalde çalıştırıp yeniden deneyin.", "insert rows into a table": "Tabloya satır ekle", "inside your project.": "projenizin içinde.", "is already assigned to:": "şuna zaten atanmış:", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index de1d95be0d..49f5a09d64 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -2752,7 +2752,6 @@ "Run configurations": "執行組態", "Run configurations and tests": "執行組態和測試", "Run external linter on save": "儲存時執行外部 Linter", - "Run gh auth login": "執行 gh auth login", "Run sessions": "執行工作階段", "Run the selected configuration under a sampling profiler": "在取樣效能分析器下執行所選組態", "Run the selected configuration with coverage": "使用覆蓋率執行所選組態", @@ -3415,7 +3414,6 @@ "if statement": "if 陳述式", "impl block": "impl 塊", "import default": "預設匯入", - "in a terminal, then retry.": "(在終端機中),然後重試。", "insert rows into a table": "向表中插入列", "inside your project.": "的資料夾。", "is already assigned to:": "已分配給:", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index d3d856fa80..f376554e10 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -3315,7 +3315,6 @@ "Run configurations": "运行配置", "Run configurations and tests": "运行配置和测试", "Run external linter on save": "保存时运行外部 Linter", - "Run gh auth login": "运行 gh auth login", "Run sessions": "运行会话", "Run the selected configuration under a sampling profiler": "在采样性能分析器下运行所选配置", "Run the selected configuration with coverage": "使用覆盖率运行所选配置", @@ -4007,7 +4006,6 @@ "if statement": "if 语句", "impl block": "impl 块", "import default": "默认导入", - "in a terminal, then retry.": "(在终端中),然后重试。", "insert rows into a table": "向表中插入行", "inside your project.": "的文件夹。", "is already assigned to:": "已分配给:", @@ -10986,6 +10984,8 @@ "Cannot list the manage.py commands": "无法列出 manage.py 命令", "Install django-types into this project's virtual environment to complete Django model fields and managers": "将 django-types 安装到此项目的虚拟环境,以补全 Django 模型字段和管理器", "No local changes in {path}": "{path} 中没有本地更改", + "Sign in with GitHub CLI to list and clone your repositories.": "登录 GitHub CLI 以列出并克隆你的仓库。", + "Sign in with GitHub CLI to view and review pull requests.": "登录 GitHub CLI 以查看和评审拉取请求。", "Find in Documentation": "在文档中查找", "Previous Match": "上一个匹配项", "Next Match": "下一个匹配项" diff --git a/src/features/agents/AgentSignInDialog.module.css b/src/workbench/CliSignInDialog.module.css similarity index 100% rename from src/features/agents/AgentSignInDialog.module.css rename to src/workbench/CliSignInDialog.module.css diff --git a/src/features/agents/AgentSignInDialog.tsx b/src/workbench/CliSignInDialog.tsx similarity index 91% rename from src/features/agents/AgentSignInDialog.tsx rename to src/workbench/CliSignInDialog.tsx index 5365dbe733..2f15a7609e 100644 --- a/src/features/agents/AgentSignInDialog.tsx +++ b/src/workbench/CliSignInDialog.tsx @@ -3,19 +3,19 @@ * and GitHub CLI (`gh auth login`), backed by an IDE-managed PTY (`agent_login_spawn` / * `agent_gh_login_spawn`) and a lazily loaded embedded terminal widget. */ +import { Channel } from "@tauri-apps/api/core"; import clsx from "clsx"; import { useEffect, useRef, useState } from "react"; import type { AgentLoginEvent, TerminalId } from "@/bindings"; +import { appendLoginOutput, parseDeviceCodePrompt, type DeviceCodePrompt } from "@/platform/deviceCode"; import { tx } from "@/platform/i18n"; -import { commands } from "@/platform/ipc"; +import { call, commands } from "@/platform/ipc"; import { openExternalUrl } from "@/platform/openUrl"; import { isRemoteWindow } from "@/platform/remote"; import { isWebMode } from "@/platform/webBridge"; import { Button, Dialog, Spinner, T, copyText, selectableText } from "@/ui"; import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributions"; -import styles from "./AgentSignInDialog.module.css"; -import { appendLoginOutput, parseDeviceCodePrompt, type DeviceCodePrompt } from "./deviceCode"; -import { tauriCommands } from "./registry"; +import styles from "./CliSignInDialog.module.css"; export type SignInTarget = { kind: "agent"; id: string; name: string } | { kind: "gh" }; @@ -24,6 +24,29 @@ export interface SignInSpawner { ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise; } +async function defaultLoginSpawn( + id: string, + cols: number, + rows: number, + onEvent: (e: AgentLoginEvent) => void, +): Promise { + const channel = new Channel(); + channel.onmessage = onEvent; + const info = await call(commands.agentLoginSpawn(id, cols, rows, channel)); + return info.id; +} + +async function defaultGhLoginSpawn( + cols: number, + rows: number, + onEvent: (e: AgentLoginEvent) => void, +): Promise { + const channel = new Channel(); + channel.onmessage = onEvent; + const info = await call(commands.agentGhLoginSpawn(cols, rows, channel)); + return info.id; +} + // oxlint-disable-next-line no-control-regex const OSC_COLOR_RESPONSE_RE = /\x1b\]1[012];[^\x07\x1b]*(?:\x07|\x1b\\)/g; // oxlint-disable-next-line no-control-regex @@ -53,7 +76,7 @@ function formatVerificationUrl(rawUrl: string): string { } } -export function AgentSignInDialog({ +export function CliSignInDialog({ target, spawner, onClose, @@ -210,13 +233,8 @@ export function AgentSignInDialog({ const custom = callbacksRef.current.spawner; const ptyId = targetKind === "gh" - ? await (custom?.ghLoginSpawn ?? tauriCommands.ghLoginSpawn!)(pendingSize.cols, pendingSize.rows, onEvent) - : await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)( - agentId, - pendingSize.cols, - pendingSize.rows, - onEvent, - ); + ? await (custom?.ghLoginSpawn ?? defaultGhLoginSpawn)(pendingSize.cols, pendingSize.rows, onEvent) + : await (custom?.loginSpawn ?? defaultLoginSpawn)(agentId, pendingSize.cols, pendingSize.rows, onEvent); if (disposed) { void commands.termKill(ptyId).catch(() => {}); return;