diff --git a/crates/ide-host/src/environment.rs b/crates/ide-host/src/environment.rs index c3f650eaf..9dfa6f0ed 100644 --- a/crates/ide-host/src/environment.rs +++ b/crates/ide-host/src/environment.rs @@ -82,6 +82,11 @@ impl Environment { } } + /// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell. + pub fn is_remote(&self) -> bool { + self.project_env + } + /// A trusted project at `root` opened or became trusted: loads its direnv environment in /// the background, unless another window of it already did. Its language servers wait. pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) { diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index 1db21362e..07247d560 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -135,6 +135,39 @@ pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult, + host_has: impl Fn(&str) -> bool, +) { + if !is_remote { + return; + } + let has_non_empty = |env: &std::collections::BTreeMap, key: &str| { + env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key) + }; + // `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers, + // and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as + // `copilot login` choose OAuth device-code sign-in over a remote-only loopback server. + if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) { + env.insert("REMOTE_CONTAINERS".into(), "1".into()); + } + if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") { + env.insert("GH_BROWSER".into(), "true".into()); + } +} + +fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) { + let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) }; + prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| { + ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty()) + }); +} + fn spawn_login_pty( host: &Host, window: &str, @@ -180,7 +213,7 @@ pub async fn agent_login_spawn( on_event: Channel, ) -> IdeResult { host.require_trust_if_project(window)?; - let (cwd, launch) = match host.project(window) { + let (cwd, mut launch) = match host.project(window) { Ok(project) => { let root = project.root.clone(); let agents = project.agents.clone(); @@ -199,6 +232,7 @@ pub async fn agent_login_spawn( (cwd, launch) } }; + apply_remote_login_env(host, &cwd, false, &mut launch); spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) } @@ -217,7 +251,8 @@ pub async fn agent_gh_login_spawn( .project(window) .map(|p| p.root.clone()) .unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir)); - let launch = host.blocking(ide_agent::gh_login_launch).await?; + let mut launch = host.blocking(ide_agent::gh_login_launch).await?; + apply_remote_login_env(host, &cwd, true, &mut launch); spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) } @@ -1562,6 +1597,29 @@ mod tests { assert!(reloaded.approved(&root, "extra", &extra)); assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra)); } + + #[test] + fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() { + let mut desktop_env = std::collections::BTreeMap::new(); + prepare_login_launch_env(false, true, &mut desktop_env, |_| false); + assert!(desktop_env.is_empty()); + + let mut remote_agent_env = std::collections::BTreeMap::new(); + prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false); + assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1")); + assert!(!remote_agent_env.contains_key("GH_BROWSER")); + + let mut remote_gh_env = std::collections::BTreeMap::new(); + prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false); + assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1")); + assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true")); + + // Preserves existing SSH/remote indicators and explicit browser settings. + let mut ssh_env = std::collections::BTreeMap::new(); + prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER")); + assert!(!ssh_env.contains_key("REMOTE_CONTAINERS")); + assert!(!ssh_env.contains_key("GH_BROWSER")); + } } ide_command::domain!( diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index ac5419e7e..eeba42a81 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -132,7 +132,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone. -For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). **New Tasks** model options load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions. +For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). When an agent or `gh` prints an OAuth device verification code during in-IDE sign-in (including on remote hosts), the sign-in dialog surfaces the one-time code above the terminal with **Copy** and **Copy Code & Open Browser** so you can authorize in your local browser in one click. **New Tasks** model options load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions. **Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index cf5691f68..920cdeb2b 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -132,7 +132,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的 对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。 -对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。选择已验证的账号后,**新任务**会自动加载该账号对应的可用模型列表,点击**应用**或**确定**保存以供新会话使用。 +对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。在 IDE 内登录(包括连接远程主机时)过程中,若智能体或 `gh` 输出了 OAuth 设备验证码,登录对话框会在终端上方显示一次性验证码及 **复制**、**复制验证码并打开浏览器** 按钮,方便一键在本地浏览器完成授权。选择已验证的账号后,**新任务**会自动加载该账号对应的可用模型列表,点击**应用**或**确定**保存以供新会话使用。 **设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。 diff --git a/e2e/agentSignIn.spec.ts b/e2e/agentSignIn.spec.ts index 924114ae1..185d728fc 100644 --- a/e2e/agentSignIn.spec.ts +++ b/e2e/agentSignIn.spec.ts @@ -86,3 +86,112 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)"); expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]); }); + +test("surfaces a device-code banner during sign-in with one-click copy and browser launch", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(() => { + const model: AgentConfigOption = { + id: "model", + name: "Model", + description: null, + category: "model", + current: "claude-sonnet-4.5", + defaultValue: "claude-sonnet-4.5", + via: "option", + values: [ + { value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null }, + { value: "gpt-5", name: "GPT-5", description: null }, + ], + }; + let signedIn = false; + let loginChannel: unknown = null; + (window as unknown as { __finishDeviceLogin?: () => void }).__finishDeviceLogin = () => { + signedIn = true; + window.__ipc.send(loginChannel, { type: "exited", code: 0 }); + }; + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + agent_registry_list: () => ({ agents: [], warning: null }), + agent_providers: () => { + const provider: AgentProvider = { + id: "copilot", + name: "GitHub Copilot", + command: "copilot --headless --no-auto-update --stdio", + program: "/tools/copilot", + args: ["--headless", "--no-auto-update", "--stdio"], + defaultProgram: "copilot", + defaultArgs: ["--headless", "--no-auto-update", "--stdio"], + loginHint: "Run `copilot login` in a terminal.", + commandOverridden: false, + commandEditable: false, + commandReadOnlyReason: "registry", + installed: true, + canSignIn: true, + canCheckCliUpdate: false, + env: {}, + config: signedIn ? [model] : [], + thoughtLevels: {}, + commands: [], + source: { kind: "registry", version: "1.0.116", update: null }, + }; + return [provider]; + }, + agent_copilot_auth_status: () => ({ + authenticated: signedIn, + login: signedIn ? "alice" : null, + authType: signedIn ? "oauth" : null, + statusMessage: signedIn ? "alice" : null, + ghInstalled: true, + ghAccounts: [], + }), + agent_refresh_models: () => ({ + provider: "copilot", + config: signedIn ? [model] : [], + thoughtLevels: {}, + refreshing: false, + refreshedAtMs: signedIn ? Date.now() : null, + retryAtMs: null, + error: null, + }), + agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => { + loginChannel = onEvent; + setTimeout(() => { + window.__ipc.send(onEvent, { + type: "output", + data: "Waiting for authorization...\r\nEnter one-time code: \u001b[1mWDJB-MJHT\u001b[0m at https://github.com/login/device\r\n", + }); + }, 30); + return { id: 1, pid: 1001, title: "copilot" }; + }, + clipboard_write_text: () => null, + "plugin:opener|open_url": () => null, + term_resize: () => null, + term_write: () => null, + term_kill: () => null, + }); + }); + + const dialog = await openAgents(page); + await dialog.getByRole("region", { name: "Sign In" }).getByRole("button", { name: "Sign In…" }).click(); + + const signInDialog = page.getByRole("dialog", { name: "Sign In to GitHub Copilot" }); + const banner = signInDialog.getByRole("region", { name: "Device verification code" }); + await expect(banner).toBeVisible(); + await expect(banner.getByText("WDJB-MJHT")).toBeVisible(); + await expect(banner.getByText("github.com/login/device")).toBeVisible(); + + await banner.getByRole("button", { name: "Copy Code & Open Browser" }).click(); + await expect(banner.getByRole("button", { name: "Copied" })).toBeVisible(); + await expect.poll(() => ipcCalls(page, "clipboard_write_text")).toEqual([{ text: "WDJB-MJHT" }]); + await expect + .poll(() => ipcCalls(page, "plugin:opener|open_url")) + .toEqual([{ url: "https://github.com/login/device" }]); + + await page.evaluate(() => (window as unknown as { __finishDeviceLogin?: () => void }).__finishDeviceLogin?.()); + await expect(signInDialog).toHaveCount(0); + await expect(dialog.getByRole("region", { name: "New Tasks" }).getByRole("button", { name: "Model" })).toContainText( + "Agent's default (Claude Sonnet 4.5)", + ); +}); diff --git a/src/features/agents/AgentSignInDialog.module.css b/src/features/agents/AgentSignInDialog.module.css index 836f4515f..4763d1fe0 100644 --- a/src/features/agents/AgentSignInDialog.module.css +++ b/src/features/agents/AgentSignInDialog.module.css @@ -5,6 +5,66 @@ padding: 12px 16px 8px; } +.deviceBanner { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: var(--space-3); + padding: 8px 12px; + border: 1px solid var(--border-strong); + border-radius: var(--radius-small); + background: var(--bg-editor-banner, var(--bg-elev)); +} + +.deviceMeta { + display: flex; + flex-direction: column; + gap: var(--space-1); + min-width: 0; +} + +.deviceLabel { + color: var(--fg-subtle); + font-size: var(--fs-tiny); +} + +.deviceCodeRow { + display: flex; + align-items: baseline; + flex-wrap: wrap; + gap: var(--space-2); + min-width: 0; +} + +.deviceCode { + padding: 2px 6px; + border: 1px solid var(--border); + border-radius: var(--radius-small); + background: var(--bg-input); + color: var(--fg-strong); + font-family: var(--font-mono); + font-size: var(--fs-code); + font-weight: var(--fw-code-bold); + letter-spacing: 0.04em; +} + +.deviceUrl { + color: var(--fg-muted); + font-family: var(--font-mono); + font-size: var(--fs-small); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.deviceActions { + display: flex; + align-items: center; + gap: var(--space-1-5); + flex-shrink: 0; +} + .terminal { width: 100%; height: 300px; diff --git a/src/features/agents/AgentSignInDialog.tsx b/src/features/agents/AgentSignInDialog.tsx index d081bd8ba..25abc725d 100644 --- a/src/features/agents/AgentSignInDialog.tsx +++ b/src/features/agents/AgentSignInDialog.tsx @@ -3,13 +3,18 @@ * 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 clsx from "clsx"; import { useEffect, useRef, useState } from "react"; import type { AgentLoginEvent, TerminalId } from "@/bindings"; import { tx } from "@/platform/i18n"; import { commands } from "@/platform/ipc"; -import { Dialog, Spinner, T } from "@/ui"; +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"; export type SignInTarget = { kind: "agent"; id: string; name: string } | { kind: "gh" }; @@ -19,6 +24,16 @@ export interface SignInSpawner { ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise; } +function formatVerificationUrl(rawUrl: string): string { + try { + const parsed = new URL(rawUrl); + const path = parsed.pathname === "/" ? "" : parsed.pathname; + return `${parsed.host}${path}`; + } catch { + return rawUrl; + } +} + export function AgentSignInDialog({ target, spawner, @@ -33,14 +48,27 @@ export function AgentSignInDialog({ const hostRef = useRef(null); const ptyIdRef = useRef(null); const completedRef = useRef(false); + const outputBufferRef = useRef(""); + const devicePromptRef = useRef(null); + const sentEnterCodesRef = useRef>(new Set()); + const copyTimerRef = useRef | null>(null); const callbacksRef = useRef({ onClose, onCompleted, spawner }); useEffect(() => { callbacksRef.current = { onClose, onCompleted, spawner }; }); + useEffect( + () => () => { + if (copyTimerRef.current !== null) clearTimeout(copyTimerRef.current); + }, + [], + ); + const [attempt, setAttempt] = useState(0); const [exitCode, setExitCode] = useState(null); const [error, setError] = useState(null); + const [devicePrompt, setDevicePrompt] = useState(null); + const [copiedCode, setCopiedCode] = useState(null); const targetKind = target.kind; const agentId = target.kind === "agent" ? target.id : ""; @@ -53,8 +81,13 @@ export function AgentSignInDialog({ const pendingOutput: string[] = []; let pendingSize: { cols: number; rows: number } = { cols: 80, rows: 18 }; completedRef.current = false; + outputBufferRef.current = ""; + devicePromptRef.current = null; + sentEnterCodesRef.current.clear(); setExitCode(null); setError(null); + setDevicePrompt(null); + setCopiedCode(null); const killPty = () => { const id = ptyIdRef.current; @@ -69,6 +102,9 @@ export function AgentSignInDialog({ if (!factory) throw new Error(tx("The terminal is not available in this window.")); const instance = await factory(el, { onData: (data) => { + if (devicePromptRef.current) { + sentEnterCodesRef.current.add(devicePromptRef.current.code); + } const id = ptyIdRef.current; if (id !== null) void commands.termWrite(id, data).catch(() => {}); }, @@ -97,6 +133,17 @@ export function AgentSignInDialog({ if (event.type === "output") { if (term) term.write(event.data); else pendingOutput.push(event.data); + outputBufferRef.current = appendLoginOutput(outputBufferRef.current, event.data); + const nextPrompt = parseDeviceCodePrompt(outputBufferRef.current); + const prevPrompt = devicePromptRef.current; + if ( + prevPrompt?.code !== nextPrompt?.code || + prevPrompt?.url !== nextPrompt?.url || + prevPrompt?.needsEnterToPoll !== nextPrompt?.needsEnterToPoll + ) { + devicePromptRef.current = nextPrompt; + setDevicePrompt(nextPrompt); + } } else { ptyIdRef.current = null; const code = event.code ?? -1; @@ -142,6 +189,35 @@ export function AgentSignInDialog({ const running = exitCode === null && !error; const title = target.kind === "gh" ? tx("Sign In to GitHub CLI") : tx`Sign In to ${target.name}`; + const markCopied = (code: string) => { + setCopiedCode(code); + if (copyTimerRef.current !== null) clearTimeout(copyTimerRef.current); + copyTimerRef.current = setTimeout(() => { + copyTimerRef.current = null; + setCopiedCode((prev) => (prev === code ? null : prev)); + }, 2000); + }; + + const handleCopyCode = async () => { + if (!devicePrompt) return; + const { code } = devicePrompt; + await copyText(code); + markCopied(code); + }; + + const handleCopyAndOpen = async () => { + if (!devicePrompt) return; + const { code, url, needsEnterToPoll } = devicePrompt; + await copyText(code); + markCopied(code); + if (needsEnterToPoll && (isRemoteWindow() || isWebMode()) && !sentEnterCodesRef.current.has(code)) { + sentEnterCodesRef.current.add(code); + const id = ptyIdRef.current; + if (id !== null) void commands.termWrite(id, "\r").catch(() => {}); + } + await openExternalUrl(url); + }; + const finishAndClose = () => { const id = ptyIdRef.current; ptyIdRef.current = null; @@ -189,6 +265,33 @@ export function AgentSignInDialog({ } >
+ {running && devicePrompt && ( +
+
+ + One-time verification code + +
+ {devicePrompt.code} + + {formatVerificationUrl(devicePrompt.url)} + +
+
+
+ + +
+
+ )}
{error &&

{error}

}
diff --git a/src/features/agents/agentRegistry.test.tsx b/src/features/agents/agentRegistry.test.tsx index d1bb715a8..25758b515 100644 --- a/src/features/agents/agentRegistry.test.tsx +++ b/src/features/agents/agentRegistry.test.tsx @@ -10,7 +10,9 @@ import type { RegistryAgent, RequestId, } from "@/bindings"; -import { IpcError } from "@/platform/ipc"; +import { IpcError, commands as ipcCommands } from "@/platform/ipc"; +import * as openUrlMod from "@/platform/openUrl"; +import { disableRemote, enableRemote } from "@/platform/remote"; import { setLocale, tx } from "@/platform/i18n"; import { iconMarkup } from "@/ui/icons"; import { MessagesHost } from "@/workbench/messages"; @@ -877,6 +879,96 @@ describe("Built-in executable overrides", () => { } }); + it("surfaces a device-code banner in Sign In dialog, copies locally, opens browser, and advances remote gh login", async () => { + provideEmbeddedTerminal(async () => ({ + write: vi.fn(), + clear: vi.fn(), + focus: vi.fn(), + fit: vi.fn(), + dispose: vi.fn(), + })); + const openSpy = vi.spyOn(openUrlMod, "openExternalUrl").mockResolvedValue(); + const termWriteSpy = vi.spyOn(ipcCommands, "termWrite").mockResolvedValue({ status: "ok", data: null }); + const writeText = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + enableRemote({ + target: { kind: "ssh", configId: "devbox" } as never, + root: "/home/alice/repo", + host: "devbox", + os: "linux", + commands: ["agent_gh_login_spawn", "term_write", "term_resize", "term_kill"], + }); + let onLoginEvent: ((e: AgentLoginEvent) => void) | null = null; + try { + const commands = new FakeCommands(); + commands.ghLoginSpawn = vi.fn(async (_cols, _rows, cb) => { + onLoginEvent = cb; + return 202; + }); + commands.copilotAuthStatus = vi.fn<() => Promise>().mockResolvedValue({ + authenticated: false, + login: null, + authType: null, + statusMessage: null, + ghInstalled: true, + ghAccounts: [], + }); + commands.list = [ + { + ...claudeProvider("copilot"), + id: "copilot", + name: "GitHub Copilot", + command: "copilot --headless --no-auto-update --stdio", + defaultProgram: "copilot", + loginHint: "Run `copilot login` in a terminal.", + installed: true, + canSignIn: true, + commandReadOnlyReason: "registry", + }, + ]; + await openCommands(commands, vi.fn(), "GitHub Copilot"); + + fireEvent.click(await screen.findByRole("button", { name: "Add account…" })); + expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument(); + await waitFor(() => expect(commands.ghLoginSpawn).toHaveBeenCalled()); + + act(() => { + onLoginEvent?.({ + type: "output", + data: "! First copy your one-time code: \u001b[1mWDJB-MJHT\u001b[0m\r\nPress Enter to open https://github.com/login/device in your browser... ", + }); + }); + + const banner = await screen.findByRole("region", { name: "Device verification code" }); + expect(within(banner).getByText("WDJB-MJHT")).toBeInTheDocument(); + expect(within(banner).getByText("github.com/login/device")).toBeInTheDocument(); + + await act(async () => { + fireEvent.click(within(banner).getByRole("button", { name: "Copy Code & Open Browser" })); + }); + + expect(writeText).toHaveBeenCalledWith("WDJB-MJHT"); + expect(openSpy).toHaveBeenCalledWith("https://github.com/login/device"); + expect(termWriteSpy).toHaveBeenCalledWith(202, "\r"); + expect(within(banner).getByRole("button", { name: "Copied" })).toBeInTheDocument(); + + // Clicking again does not send a second Enter for the same code. + termWriteSpy.mockClear(); + await act(async () => { + fireEvent.click(within(banner).getByRole("button", { name: "Copy Code & Open Browser" })); + }); + expect(termWriteSpy).not.toHaveBeenCalled(); + } finally { + disableRemote(); + openSpy.mockRestore(); + termWriteSpy.mockRestore(); + provideEmbeddedTerminal(undefined); + } + }); + it("Cancel discards command edits without writing", async () => { const commands = new FakeCommands(); commands.list = [ diff --git a/src/features/agents/deviceCode.test.ts b/src/features/agents/deviceCode.test.ts new file mode 100644 index 000000000..036f501bb --- /dev/null +++ b/src/features/agents/deviceCode.test.ts @@ -0,0 +1,72 @@ +import { describe, expect, it } from "vitest"; +import { appendLoginOutput, parseDeviceCodePrompt } from "./deviceCode"; + +describe("parseDeviceCodePrompt", () => { + it("parses Copilot CLI Ink output with SGR styling, OSC-8 links, and cursor-forward escapes", () => { + const raw = + "\x1b[?25l⠋ Waiting for authorization...\r\n" + + "Enter\x1b[1Cone-time\x1b[1Ccode:\x1b[1C\x1b[1m\x1b[36mWDJB-MJHT\x1b[39m\x1b[22m\x1b[1Cat\x1b[1C" + + "\x1b]8;;https://github.com/login/device\x07\x1b[4mhttps://github.com/login/device\x1b[24m\x1b]8;;\x07\r\n" + + "Press any key to copy to clipboard and open browser..."; + expect(parseDeviceCodePrompt(raw)).toEqual({ + code: "WDJB-MJHT", + url: "https://github.com/login/device", + needsEnterToPoll: false, + }); + }); + + it("parses GitHub CLI device-code output across chunks and marks Press Enter to open", () => { + let buffer = ""; + buffer = appendLoginOutput(buffer, "! First copy your one-time code: 9F4K-2L8P\r\n"); + expect(parseDeviceCodePrompt(buffer)).toBeNull(); + + buffer = appendLoginOutput(buffer, "Press Enter to open https://github.com/login/device in your browser... "); + expect(parseDeviceCodePrompt(buffer)).toEqual({ + code: "9F4K-2L8P", + url: "https://github.com/login/device", + needsEnterToPoll: true, + }); + }); + + it("parses Codex, Microsoft devicelogin, and RFC 8628 verification_uri_complete prompts", () => { + expect(parseDeviceCodePrompt("│ Visit https://auth.openai.com/codex/device and enter code: ABCD-EFGH │")).toEqual({ + code: "ABCD-EFGH", + url: "https://auth.openai.com/codex/device", + needsEnterToPoll: false, + }); + + expect( + parseDeviceCodePrompt( + "To sign in, use a web browser to open https://microsoft.com/devicelogin and enter the code K9P4M2X7Q to authenticate.", + ), + ).toEqual({ + code: "K9P4M2X7Q", + url: "https://microsoft.com/devicelogin", + needsEnterToPoll: false, + }); + + expect( + parseDeviceCodePrompt("Open https://auth.example.com/activate?user_code=zx90-12ab to finish signing in."), + ).toEqual({ + code: "ZX90-12AB", + url: "https://auth.example.com/activate?user_code=zx90-12ab", + needsEnterToPoll: false, + }); + }); + + it("updates to the newest code when an expired device code is re-issued", () => { + const raw = + "Enter one-time code: AAAA-1111 at https://github.com/login/device\n" + + "Code expired. Enter one-time code: BBBB-2222 at https://github.com/login/device\n"; + expect(parseDeviceCodePrompt(raw)?.code).toBe("BBBB-2222"); + }); + + it("ignores regular browser OAuth callback URLs with UUIDs and copyright year ranges", () => { + expect( + parseDeviceCodePrompt( + "Copyright 2024-2026 Anthropic\n" + + "Browser didn't open? Visit https://claude.ai/oauth/authorize?client_id=9D1C-4567-ABCD-EF01&state=XY12-3456", + ), + ).toBeNull(); + }); +}); diff --git a/src/features/agents/deviceCode.ts b/src/features/agents/deviceCode.ts new file mode 100644 index 000000000..8703e1444 --- /dev/null +++ b/src/features/agents/deviceCode.ts @@ -0,0 +1,120 @@ +/** + * 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"; + +const MAX_BUFFER_CHARS = 16_384; +// oxlint-disable-next-line no-control-regex +const OSC_HYPERLINK_RE = /\x1b\]8;[^;\x07\x1b]*;([^\x07\x1b]*)(?:\x07|\x1b\\)/g; +// oxlint-disable-next-line no-control-regex +const OSC_OTHER_RE = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g; +// oxlint-disable-next-line no-control-regex +const SGR_RE = /\x1b\[[0-9;:]*m/g; +// oxlint-disable-next-line no-control-regex +const CSI_NON_SGR_RE = /\x1b\[[0-9;?]*[@-ln-zA-Z~]/g; +// oxlint-disable-next-line no-control-regex +const ESC_SINGLE_RE = /\x1b[@-_]/g; +// oxlint-disable-next-line no-control-regex +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 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; +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})?$/; +const PRESS_ENTER_TO_OPEN_RE = /\bPress Enter to open\b/i; + +export interface DeviceCodePrompt { + code: string; + url: string; + /** True when the CLI pauses at "Press Enter to open …" before starting its token poll (`gh auth login`). */ + needsEnterToPoll: boolean; +} + +export function appendLoginOutput(previous: string, chunk: string): string { + if (!chunk) return previous; + const next = previous + chunk; + return next.length > MAX_BUFFER_CHARS ? next.slice(next.length - MAX_BUFFER_CHARS) : next; +} + +function cleanTerminalOutput(raw: string): string { + return raw + .replace(OSC_HYPERLINK_RE, (_match, uri: string) => (uri ? ` ${uri} ` : "")) + .replace(OSC_OTHER_RE, "") + .replace(SGR_RE, "") + .replace(CSI_NON_SGR_RE, " ") + .replace(ESC_SINGLE_RE, " ") + .replace(/\r\n?/g, "\n") + .replace(CONTROL_OR_BOX_RE, " "); +} + +export function parseDeviceCodePrompt(rawOutput: string): DeviceCodePrompt | null { + if (!rawOutput) return null; + const cleaned = cleanTerminalOutput(rawOutput); + + let latestDeviceUrl: string | null = null; + let fallbackHttpsUrl: string | null = null; + 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, ""); + if (!isOpenable(candidate)) continue; + let parsed: URL; + try { + parsed = new URL(candidate); + } catch { + continue; + } + fallbackHttpsUrl = candidate; + const queryCode = parsed.searchParams.get("user_code")?.trim(); + if (queryCode && COMPLETE_URI_CODE_RE.test(queryCode) && !YEAR_RANGE_RE.test(queryCode)) { + completeUriPrompt = { url: candidate, code: queryCode.toUpperCase(), index: match.index ?? 0 }; + } + if (DEVICE_PATH_RE.test(parsed.pathname)) { + latestDeviceUrl = candidate; + } + } + + const textWithoutUrls = cleaned.replace(HTTPS_URL_RE, " "); + + let latestCode: { code: string; index: number } | null = null; + for (const match of textWithoutUrls.matchAll(LABELED_CODE_RE)) { + const code = match[1]; + if (code && !YEAR_RANGE_RE.test(code)) { + latestCode = { code, index: match.index ?? 0 }; + } + } + + const targetUrl = latestDeviceUrl ?? (EXPLICIT_CODE_CUE_RE.test(textWithoutUrls) ? fallbackHttpsUrl : null); + + if (!latestCode && latestDeviceUrl) { + for (const match of textWithoutUrls.matchAll(HYPHENATED_CODE_RE)) { + const code = match[1]; + if (code && !YEAR_RANGE_RE.test(code)) { + latestCode = { code, index: match.index ?? 0 }; + } + } + } + + if (completeUriPrompt && (!latestCode || completeUriPrompt.index >= latestCode.index)) { + const tail = cleaned.slice(completeUriPrompt.index); + return { + code: completeUriPrompt.code, + url: completeUriPrompt.url, + needsEnterToPoll: PRESS_ENTER_TO_OPEN_RE.test(tail), + }; + } + + if (!targetUrl || !latestCode) return null; + const tail = cleaned.slice(latestCode.index); + return { + code: latestCode.code, + url: targetUrl, + needsEnterToPoll: PRESS_ENTER_TO_OPEN_RE.test(tail), + }; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f6176f15d..81272a607 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4217,6 +4217,9 @@ "Sign In…": "Sign In…", "Copy command": "Copy command", "Sign In to {name}": "Sign In to {name}", + "Device verification code": "Device verification code", + "One-time verification code": "One-time verification code", + "Copy Code & Open Browser": "Copy Code & Open Browser", "Complete sign-in in your browser or the terminal above…": "Complete sign-in in your browser or the terminal above…", "Sign-in exited with code {exitCode}.": "Sign-in exited with code {exitCode}.", "Install GitHub CLI": "Install GitHub CLI", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 37e79fac3..be6c85255 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10678,6 +10678,9 @@ "Sign In…": "登录…", "Copy command": "复制命令", "Sign In to {name}": "登录 {name}", + "Device verification code": "设备验证码", + "One-time verification code": "一次性验证码", + "Copy Code & Open Browser": "复制验证码并打开浏览器", "Complete sign-in in your browser or the terminal above…": "请在浏览器或上方终端中完成登录…", "Sign-in exited with code {exitCode}.": "登录已退出,代码为 {exitCode}。", "Install GitHub CLI": "安装 GitHub CLI",