diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index a6201d60fe..2251125c38 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -33,7 +33,7 @@ pub use catalogs::AgentCatalogs; pub use cli_update::{AgentCliOffer, AgentCliUpdateResult}; pub use external::ExternalSession; pub use model::*; -pub use provider::LoginLaunch; +pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch}; pub use skill_installer::{ InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview, SkillScanWarning, SkillScanWarningKind, @@ -69,6 +69,34 @@ pub fn login_launch_without_project( .ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))) } +/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts. +pub async fn copilot_auth_status_with( + custom_agents_dir: Option<&Path>, + secrets: Option<&dyn EnvSecrets>, + cwd: &Path, +) -> CopilotAuthStatus { + let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot"); + let cwd_buf = cwd.to_path_buf(); + let cli_fut = async move { + let spec = copilot_spec?; + native::copilot::probe_auth_status(spec, cwd_buf).await + }; + let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts); + let (cli, gh) = tokio::join!(cli_fut, gh_fut); + let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new())); + match cli { + Some(cli) => CopilotAuthStatus { + authenticated: cli.authenticated, + login: cli.login, + auth_type: cli.auth_type, + status_message: cli.status_message, + gh_installed, + gh_accounts, + }, + None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() }, + } +} + /// Receives the events of one project's tasks. pub type AgentSink = Arc; @@ -853,6 +881,20 @@ impl AgentManager { Ok(launch) } + /// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts. + pub async fn copilot_auth_status(&self) -> CopilotAuthStatus { + let status = copilot_auth_status_with( + self.shared.paths.custom_agents_dir.as_deref(), + self.shared.env_secrets(), + &self.shared.paths.project_root, + ) + .await; + if status.authenticated || !status.gh_accounts.is_empty() { + self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot"); + } + status + } + /// Overrides built-in `id`'s command with `command` (the driver and arguments stay /// the built-in's) through its agent file, or returns it to auto-detection with `None`. pub fn set_builtin_command(&self, id: &str, command: Option) -> IdeResult<()> { @@ -875,7 +917,9 @@ impl AgentManager { let Some(dir) = self.shared.paths.custom_agents_dir.clone() else { return Err(IdeError::unavailable("there is no custom agents directory")); }; - provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env) + provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?; + self.shared.paths.catalogs.evict_if_idle(&self.shared, id); + Ok(()) } /// Saves a new custom ACP agent through its agent file. diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 32baf23710..59477786a0 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -650,6 +650,26 @@ pub enum AgentCommandReadOnlyReason { CustomAgent, } +/// An authenticated `github.com` account stored in GitHub CLI (`gh`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GhAuthAccount { + pub login: String, + pub active: bool, +} + +/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct CopilotAuthStatus { + pub authenticated: bool, + pub login: Option, + pub auth_type: Option, + pub status_message: Option, + pub gh_installed: bool, + pub gh_accounts: Vec, +} + /// Output and completion of an interactive sign-in PTY started by the IDE. #[derive(Clone, Debug, Serialize, Deserialize, Type)] #[serde(tag = "type", rename_all = "camelCase")] diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 85ba37e002..0ce661401b 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> res } +#[derive(Clone, Debug, Default)] +pub(crate) struct CliAuthStatus { + pub authenticated: bool, + pub login: Option, + pub auth_type: Option, + pub status_message: Option, +} + +/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh` +/// account override so the UI can show what the "Default" account resolves to). +pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option { + spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV); + tokio::time::timeout(Duration::from_secs(8), async move { + let prefer_stored = crate::provider::prefer_stored_copilot_auth(); + let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env); + let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await; + if !prefer_stored + && has_ambient + && first.as_ref().is_none_or(|s| !s.authenticated) + && let Some(retry) = probe_auth_once(spec, cwd, true).await + { + if retry.authenticated { + crate::provider::mark_prefer_stored_copilot_auth(); + } + return Some(retry); + } + first + }) + .await + .ok() + .flatten() +} + +async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option { + let launch = tokio::task::spawn_blocking({ + let cwd = cwd.clone(); + move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient) + }) + .await + .ok()? + .ok()?; + let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd); + let args = headless_args(&launch.args); + let peer = Peer::spawn_framed( + &launch.command, + &args, + &cwd, + &launch.env, + Arc::new(ide_jsonrpc::NoopHandler), + Box::new(|_| {}), + Framing::ContentLength, + ) + .ok()?; + let res = async { + handshake(&peer).await.ok()?; + let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?; + let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false); + let str_field = |key: &str| { + auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned) + }; + Some(CliAuthStatus { + authenticated, + login: str_field("login"), + auth_type: str_field("authType"), + status_message: str_field("statusMessage"), + }) + } + .await; + peer.kill(); + res +} + #[cfg(test)] pub(super) fn attach( client: Arc, diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index e101b00657..1e2e0bda5b 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -2,7 +2,10 @@ //! `/agents/.toml` (written by hand, or by installing one from the ACP //! Registry, see `registry`). -use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets}; +use crate::{ + AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets, + GhAuthAccount, +}; use ide_core::{IdeError, IdeResult}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -268,16 +271,15 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option .map(str::to_owned) } +fn find_gh_executable() -> Option { + ide_core::tool_path::find_gh_executable() +} + fn github_token_for_account(account: &str) -> Result { - let path = ide_core::process::shell_env() - .find(|(name, _)| name == "PATH") - .map(|(_, value)| value) - .or_else(|| ide_core::process::host_var_os("PATH")); - let program = path - .as_deref() - .and_then(|path| ide_core::process::find_executable("gh", path)) + let program = find_gh_executable() .ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?; let mut command = std::process::Command::new(program); + ide_core::process::prepare(&mut command); command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env()); for name in AMBIENT_COPILOT_AUTH_VARS { command.env_remove(name); @@ -303,6 +305,124 @@ fn github_token_for_account(account: &str) -> Result { Ok(token.to_owned()) } +/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE, +/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run. +pub fn gh_login_launch() -> IdeResult { + let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?; + let mut env = BTreeMap::new(); + for key in AMBIENT_COPILOT_AUTH_VARS { + env.insert(key.to_owned(), String::new()); + } + Ok(LoginLaunch { + program, + args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()], + env, + }) +} + +/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`, +/// ignoring ambient token environment variables so keyring accounts remain visible. +pub fn gh_authenticated_accounts() -> (bool, Vec) { + let Some(program) = find_gh_executable() else { + return (false, Vec::new()); + }; + let run_gh = |args: &[&str]| -> Option { + let mut command = std::process::Command::new(&program); + ide_core::process::prepare(&mut command); + command + .args(args) + .envs(ide_core::process::shell_env()) + .env("GH_PROMPT_DISABLED", "1") + .env("GH_NO_UPDATE_NOTIFIER", "1") + .env("NO_COLOR", "1"); + for name in AMBIENT_COPILOT_AUTH_VARS { + command.env_remove(name); + } + command.output().ok() + }; + if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) { + let stdout = String::from_utf8_lossy(&output.stdout); + if let Some(accounts) = parse_gh_auth_status_json(&stdout) { + return (true, accounts); + } + let stderr = String::from_utf8_lossy(&output.stderr); + if !stderr.contains("unknown flag: --json") { + return (true, Vec::new()); + } + } + let fallback = run_gh(&["auth", "status", "--hostname", "github.com"]) + .map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))) + .map(|text| parse_gh_auth_status_text(&text)) + .unwrap_or_default(); + (true, fallback) +} + +fn parse_gh_auth_status_json(text: &str) -> Option> { + #[derive(Deserialize)] + #[serde(rename_all = "camelCase")] + struct Entry { + #[serde(default)] + state: Option, + #[serde(default)] + active: bool, + #[serde(default)] + login: String, + #[serde(default)] + token_source: Option, + } + #[derive(Deserialize)] + struct Response { + #[serde(default)] + hosts: BTreeMap>, + } + let parsed: Response = serde_json::from_str(text.trim()).ok()?; + let mut accounts: Vec = Vec::new(); + if let Some(entries) = parsed.hosts.get("github.com") { + for entry in entries { + let login = entry.login.trim(); + if login.is_empty() { + continue; + } + if entry.state.as_deref().is_some_and(|s| s != "success") { + continue; + } + if matches!(entry.token_source.as_deref(), Some("GITHUB_TOKEN" | "GH_TOKEN" | "COPILOT_GITHUB_TOKEN")) { + continue; + } + if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) { + existing.active |= entry.active; + } else { + accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active }); + } + } + } + Some(accounts) +} + +fn parse_gh_auth_status_text(text: &str) -> Vec { + let mut accounts: Vec = Vec::new(); + let mut current: Option = None; + for line in text.lines() { + let trimmed = line.trim(); + if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") { + let login = rest.split_whitespace().next().unwrap_or("").trim(); + if !login.is_empty() { + if let Some(idx) = accounts.iter().position(|a| a.login == login) { + current = Some(idx); + } else { + accounts.push(GhAuthAccount { login: login.to_owned(), active: false }); + current = Some(accounts.len() - 1); + } + } + } else if trimmed.starts_with("- Active account: true") + && let Some(idx) = current + { + accounts[idx].active = true; + } + } + accounts +} + pub(crate) fn prefer_stored_copilot_auth() -> bool { PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire) } @@ -1251,12 +1371,12 @@ mod tests { "copilot", BTreeMap::from([ ("REGISTRY_SETTING".into(), "kept".into()), - (COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()), + (COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()), ]), ) .unwrap(); let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap(); - assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft")); + assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work")); set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())])) .unwrap_err(); @@ -1265,7 +1385,7 @@ mod tests { #[test] fn launch_metadata_never_passes_the_github_account_control_to_copilot() { let mut spec = builtin_spec("copilot").unwrap(); - spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into())); + spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into())); let resolved = spec.resolve_for_launch(Path::new(".")); assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV)); } @@ -1550,6 +1670,45 @@ mod tests { ); } + #[test] + fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() { + let raw = r#"{ + "hosts": { + "github.com": [ + {"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"}, + {"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"}, + {"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"}, + {"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"} + ], + "ghe.example.com": [ + {"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"} + ] + } + }"#; + assert_eq!( + parse_gh_auth_status_json(raw), + Some(vec![ + GhAuthAccount { login: "alice".into(), active: true }, + GhAuthAccount { login: "alice-work".into(), active: false }, + ]) + ); + + let text = "\ +github.com + ✓ Logged in to github.com account alice (keyring) + - Active account: false + ✓ Logged in to github.com account alice-work (keyring) + - Active account: true +"; + assert_eq!( + parse_gh_auth_status_text(text), + vec![ + GhAuthAccount { login: "alice".into(), active: false }, + GhAuthAccount { login: "alice-work".into(), active: true }, + ] + ); + } + #[test] fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index a0865c51a4..26cad2a04e 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -8,9 +8,9 @@ use ide_agent::{ AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer, AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog, AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, - CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, McpImportSelection, - McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult, - RemoteSkillPreview, SkillsPolicy, + CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource, + McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, + RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy, }; use ide_command::command; use ide_core::error::ErrorKind; @@ -108,7 +108,21 @@ pub fn agent_set_env( host.project(window)?.agents.set_builtin_env(&id, env) } -pub(crate) fn spawn_login_pty( +/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`. +#[command(trust = outside_restricted)] +pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult { + host.require_trust_if_project(window)?; + match host.project(window) { + Ok(project) => Ok(project.agents.copilot_auth_status().await), + Err(_) => { + let custom_dir = host.config_dir.join("agents"); + let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir); + Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await) + } + } +} + +fn spawn_login_pty( host: &Host, window: &str, cwd: std::path::PathBuf, @@ -175,6 +189,25 @@ pub async fn agent_login_spawn( spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) } +/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token +/// variables cleared) and streams its output and exit code. +#[command(trust = outside_restricted)] +pub async fn agent_gh_login_spawn( + host: &Host, + window: &str, + cols: u16, + rows: u16, + on_event: Channel, +) -> IdeResult { + host.require_trust_if_project(window)?; + let cwd = host + .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?; + spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) +} + /// Saves a new custom ACP agent through its agent file. pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> { host.require_trust(window)?; @@ -1530,12 +1563,14 @@ ide_command::domain!( agent_cli_update, agent_cli_update_check, agent_commands, + agent_copilot_auth_status, agent_create, agent_delete, agent_entries, agent_external_sessions, agent_fork, agent_fork_session, + agent_gh_login_spawn, agent_grouped_changes, agent_hermes_profiles, agent_import_session, diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index fb46720d20..0f203c4a18 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -132,6 +132,8 @@ 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 are loaded for the authenticated account after sign-in or **Apply**. + **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**. ### External MCP servers diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index d284281878..32dd7223ba 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的 对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。 +对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。 + **设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。 ### 外部 MCP 服务器 diff --git a/e2e/agentCopilotAuth.spec.ts b/e2e/agentCopilotAuth.spec.ts new file mode 100644 index 0000000000..b9d3998422 --- /dev/null +++ b/e2e/agentCopilotAuth.spec.ts @@ -0,0 +1,164 @@ +import type { Page } from "@playwright/test"; +import type { AgentConfigOption, AgentProvider, CopilotAuthStatus } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +async function openAgents(page: Page) { + const settings = "/src/features/settings/model/staging.ts"; + await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("agents.list"), settings); + return page.getByRole("dialog", { name: "Settings", exact: true }); +} + +test("unifies Copilot sign-in, gates per-account models on auth, and supports in-IDE account switching", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(() => { + let savedAccount = ""; + let cliAuthenticated = false; + let ghAccounts: { login: string; active: boolean }[] = [{ login: "alice", active: true }]; + let loginChannel: unknown = null; + + const personalModel: 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 }, + ], + }; + const workModel: AgentConfigOption = { + id: "model", + name: "Model", + description: null, + category: "model", + current: "gemini-4-neon", + defaultValue: "gemini-4-neon", + via: "option", + values: [ + { value: "gemini-4-neon", name: "Gemini 4 Neon", description: null }, + { value: "gpt-5", name: "GPT-5", description: null }, + ], + }; + + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + agent_registry_list: () => ({ agents: [], warning: null }), + agent_providers: () => { + const env: Record = { COPILOT_TELEMETRY_OPTOUT: "1" }; + if (savedAccount) env.OPENIDEA_COPILOT_GITHUB_ACCOUNT = savedAccount; + 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: [workModel], + thoughtLevels: {}, + commands: [], + source: { kind: "registry", version: "1.0.116", update: null }, + }; + return [provider]; + }, + agent_copilot_auth_status: (): CopilotAuthStatus => ({ + authenticated: cliAuthenticated, + login: cliAuthenticated ? "alice" : null, + authType: cliAuthenticated ? "oauth" : null, + statusMessage: cliAuthenticated ? "alice" : null, + ghInstalled: true, + ghAccounts, + }), + agent_refresh_models: () => ({ + provider: "copilot", + config: [savedAccount === "alice-work" ? workModel : personalModel], + thoughtLevels: {}, + refreshing: false, + refreshedAtMs: Date.now(), + retryAtMs: null, + error: null, + }), + agent_set_env: ({ env }: { env: Record }) => { + savedAccount = env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? ""; + return null; + }, + agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => { + loginChannel = onEvent; + setTimeout(() => { + window.__ipc.send(loginChannel, { type: "output", data: "Opening GitHub in browser...\r\n" }); + cliAuthenticated = true; + window.__ipc.send(loginChannel, { type: "exited", code: 0 }); + }, 40); + return { id: 1, pid: 1001, title: "copilot" }; + }, + agent_gh_login_spawn: ({ onEvent }: { onEvent: unknown }) => { + loginChannel = onEvent; + setTimeout(() => { + window.__ipc.send(loginChannel, { type: "output", data: "Logged in as alice-work\r\n" }); + ghAccounts = [ + { login: "alice", active: true }, + { login: "alice-work", active: false }, + ]; + window.__ipc.send(loginChannel, { type: "exited", code: 0 }); + }, 40); + return { id: 2, pid: 1002, title: "gh" }; + }, + term_resize: () => null, + term_write: () => null, + term_kill: () => null, + }); + }); + + const dialog = await openAgents(page); + const signIn = dialog.getByRole("region", { name: "Sign In" }); + const newTasks = dialog.getByRole("region", { name: "New Tasks" }); + const launch = dialog.getByRole("region", { name: "Launch" }); + + // Unified Sign In section holds GitHub account; Launch has no duplicate account control. + const accountSelect = signIn.getByRole("button", { name: "GitHub account" }); + await expect(accountSelect).toContainText("Copilot CLI default (not signed in)"); + await expect(launch.getByRole("button", { name: "GitHub account" })).toHaveCount(0); + + // Unauthenticated state hides stale cached models. + await expect(newTasks.getByText("Sign in above to view and choose models available for this account.")).toBeVisible(); + await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0); + + // Sign In runs in-IDE PTY and unlocks personal account models. + await signIn.getByRole("button", { name: "Sign In…" }).click(); + await expect(page.getByRole("dialog", { name: "Sign In to GitHub Copilot" })).toHaveCount(0); + await expect(accountSelect).toContainText("Copilot CLI default (alice)"); + await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Claude Sonnet 4.5)"); + + // Add account runs gh auth login in-IDE, auto-selects alice-work, and gates models on Apply. + await signIn.getByRole("button", { name: "Add account…" }).click(); + await expect(page.getByRole("dialog", { name: "Sign In to GitHub CLI" })).toHaveCount(0); + await expect(accountSelect).toContainText("alice-work"); + await expect(newTasks.getByText("Click Apply to load the models available for the selected account.")).toBeVisible(); + await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0); + + // Applying loads the new account's subscription models. + await dialog.getByRole("button", { name: "Apply", exact: true }).click(); + await expect(newTasks.getByRole("button", { name: "Model" })).toContainText("Agent's default (Gemini 4 Neon)"); + expect(await ipcCalls(page, "agent_set_env")).toEqual([ + { + id: "copilot", + env: { + COPILOT_TELEMETRY_OPTOUT: "1", + OPENIDEA_COPILOT_GITHUB_ACCOUNT: "alice-work", + }, + }, + ]); +}); diff --git a/e2e/agentSignIn.spec.ts b/e2e/agentSignIn.spec.ts index 5790232a4d..924114ae1e 100644 --- a/e2e/agentSignIn.spec.ts +++ b/e2e/agentSignIn.spec.ts @@ -30,15 +30,15 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat agent_registry_list: () => ({ agents: [], warning: null }), agent_providers: () => { const provider: AgentProvider = { - id: "copilot", - name: "GitHub Copilot", - command: "copilot --headless --no-auto-update --stdio", - program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot", - args: ["--headless", "--no-auto-update", "--stdio"], - defaultProgram: "copilot", - defaultArgs: ["--headless", "--no-auto-update", "--stdio"], + id: "claude", + name: "Claude Code", + command: "claude", + program: "/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude", + args: [], + defaultProgram: "claude", + defaultArgs: [], loginHint: - "Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot' login` in a terminal.", + "Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/claude/claude'` in a terminal and sign in.", commandOverridden: false, commandEditable: false, commandReadOnlyReason: "registry", @@ -49,12 +49,12 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat config: signedIn ? [model] : [], thoughtLevels: {}, commands: [], - source: { kind: "registry", version: "1.0.116", update: null }, + source: { kind: "registry", version: "1.0.0", update: null }, }; return [provider]; }, agent_refresh_models: () => ({ - provider: "copilot", + provider: "claude", config: signedIn ? [model] : [], thoughtLevels: {}, refreshing: false, @@ -64,11 +64,11 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat }), agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => { setTimeout(() => { - window.__ipc.send(onEvent, { type: "output", data: "Opening GitHub in browser...\r\n" }); + window.__ipc.send(onEvent, { type: "output", data: "Opening Claude in browser...\r\n" }); signedIn = true; window.__ipc.send(onEvent, { type: "exited", code: 0 }); }, 40); - return { id: 1, pid: 1001, title: "copilot" }; + return { id: 1, pid: 1001, title: "claude" }; }, term_resize: () => null, term_write: () => null, @@ -82,7 +82,7 @@ test("signs in to an agent in an IDE terminal dialog and refreshes its model cat await expect(newTasks.getByRole("button", { name: "Model" })).toHaveCount(0); await signIn.getByRole("button", { name: "Sign In…" }).click(); - await expect(page.getByRole("dialog", { name: "Sign In to GitHub Copilot" })).toHaveCount(0); + await expect(page.getByRole("dialog", { name: "Sign In to Claude Code" })).toHaveCount(0); 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(["copilot"]); + expect((await ipcCalls(page, "agent_login_spawn")).map((c) => c.id)).toEqual(["claude"]); }); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 108d666533..546af6cc54 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -10,6 +10,7 @@ agent_cli_update trusted project_host bin agent_cli_update_check trusted project_host bindings async agent_commands always project_host bindings async agent_context_usage trusted project_host bindings async +agent_copilot_auth_status outside_restricted project_host bindings async agent_create trusted project_host bindings async agent_custom_import trusted desktop bindings sync agent_custom_remove trusted desktop bindings sync @@ -19,6 +20,7 @@ agent_entries always project_host bin agent_external_sessions trusted project_host bindings async agent_fork trusted project_host bindings async agent_fork_session trusted project_host bindings async +agent_gh_login_spawn outside_restricted project_host bindings async agent_grouped_changes trusted project_host bindings async agent_hermes_profiles trusted project_host bindings async agent_import_session trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index e22ae04f8e..1b4b412eef 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -44,6 +44,8 @@ export const commands = { agentCommands: (provider: string, task: string | null) => typedError(__TAURI_INVOKE("agent_commands", { provider, task })), /** Reads the running session's context categories without sending a prompt. */ agentContextUsage: (task: string) => typedError(__TAURI_INVOKE("agent_context_usage", { task })), + /** Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`. */ + agentCopilotAuthStatus: () => typedError(__TAURI_INVOKE("agent_copilot_auth_status")), agentCreate: (request: NewAgentTask) => typedError(__TAURI_INVOKE("agent_create", { request })), /** Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. */ agentCustomImport: (text: string) => typedError(__TAURI_INVOKE("agent_custom_import", { text })), @@ -69,6 +71,11 @@ export const commands = { * as the agent's own fork, under an id the host chooses. `cwd` must be where it was recorded. */ agentForkSession: (provider: string, sessionId: string, cwd: string) => typedError(__TAURI_INVOKE("agent_fork_session", { provider, sessionId, cwd })), + /** + * Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token + * variables cleared) and streams its output and exit code. + */ + agentGhLoginSpawn: (cols: number, rows: number, onEvent: Channel) => typedError(__TAURI_INVOKE("agent_gh_login_spawn", { cols, rows, onEvent })), /** The task's uncommitted changes and the commits made since it started. */ agentGroupedChanges: (task: string) => typedError(__TAURI_INVOKE("agent_grouped_changes", { task })), /** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */ @@ -4994,6 +5001,16 @@ export type ContributionInfo = { label: string, }; +/** GitHub Copilot's default sign-in status alongside the accounts available through `gh`. */ +export type CopilotAuthStatus = { + authenticated: boolean, + login: string | null, + authType: string | null, + statusMessage: string | null, + ghInstalled: boolean, + ghAccounts: GhAuthAccount[], +}; + export type CoveragePrepared = CoveragePrepared_Serialize | CoveragePrepared_Deserialize; export type CoveragePrepared_Deserialize = ({ status: "ready"; runner: string; @@ -7683,6 +7700,12 @@ export type GhApiRequest = { paginate: boolean, }; +/** An authenticated `github.com` account stored in GitHub CLI (`gh`). */ +export type GhAuthAccount = { + login: string, + active: boolean, +}; + /** Whether pull requests can be shown for the project, and why not. */ export type GhAvailability = { kind: "ready"; repo: GhRepo; /** The signed-in user. */ diff --git a/src/features/agents/AgentList.module.css b/src/features/agents/AgentList.module.css index 3b69a8a989..a228f67627 100644 --- a/src/features/agents/AgentList.module.css +++ b/src/features/agents/AgentList.module.css @@ -230,6 +230,14 @@ color: var(--fg); overflow-wrap: anywhere; } +.statusNote { + display: inline-flex; + align-items: center; + gap: var(--space-1-5); + margin: 4px 0; + color: var(--fg-subtle); + overflow-wrap: anywhere; +} .text code, .launch { font-family: var(--font-mono); @@ -306,6 +314,14 @@ flex: 1; min-width: 0; } +.accountField { + display: flex; + flex: 1; + flex-wrap: wrap; + align-items: center; + gap: var(--space-1-5); + min-width: 0; +} .select { display: flex; width: 280px; diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index d5fa53ad26..caa8692f12 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -5,12 +5,13 @@ * start with, and how it is launched. Launch edits are staged until Apply; installs run in * the background and keep running after the page closes. */ -import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from "react"; +import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from "react"; import type { AgentConfigOption, AgentModelCatalog, AgentProvider, AgentRegistry, + CopilotAuthStatus, CustomAgentInput, RegistryAgent, RequestId, @@ -878,6 +879,41 @@ function ProviderSettings({ }); const [error, setError] = useState(null); const [signInTarget, setSignInTarget] = useState(null); + const [copilotStatus, setCopilotStatus] = useState(null); + const [copilotStatusLoaded, setCopilotStatusLoaded] = useState(false); + const [authRevision, setAuthRevision] = useState(0); + const pendingAddAccountPrevLogins = useRef | null>(null); + const fetchCopilotStatus = backend.copilotAuthStatus; + const reloadCopilotStatus = useCallback(async (): Promise => { + if (agent.id !== "copilot" || !fetchCopilotStatus) return null; + try { + const next = await fetchCopilotStatus(); + setCopilotStatus(next); + setCopilotStatusLoaded(true); + return next; + } catch { + setCopilotStatusLoaded(true); + return null; + } + }, [agent.id, fetchCopilotStatus]); + useEffect(() => { + if (agent.id !== "copilot" || !fetchCopilotStatus) return; + let alive = true; + void fetchCopilotStatus() + .then((next) => { + if (alive) { + setCopilotStatus(next); + setCopilotStatusLoaded(true); + } + }) + .catch(() => { + if (alive) setCopilotStatusLoaded(true); + }); + return () => { + alive = false; + }; + }, [agent.id, fetchCopilotStatus]); + const activeCopilotStatus = agent.id === "copilot" && fetchCopilotStatus ? copilotStatus : null; // An edit can have been staged by a previous page instance. Its Apply callback // refreshes that instance; the mounted one follows the newly applied value too. useEffect(() => { @@ -892,65 +928,155 @@ function ProviderSettings({ const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent"; const canSignInInIde = agent.installed && (agent.canSignIn ?? false); const commandSpan = agent.loginHint ? (/`([^`]+)`/.exec(agent.loginHint)?.[1] ?? null) : null; + const defaultAccountLabel = + activeCopilotStatus?.authenticated && activeCopilotStatus.login + ? activeCopilotStatus.authType === "gh-cli" + ? tx`Copilot CLI default (${activeCopilotStatus.login} via GitHub CLI)` + : tx`Copilot CLI default (${activeCopilotStatus.login})` + : activeCopilotStatus && !activeCopilotStatus.authenticated + ? tx("Copilot CLI default (not signed in)") + : tx("Copilot CLI default"); + const ghAccounts = activeCopilotStatus?.ghAccounts ?? []; + const copilotAccountOptions = [ + { value: "", label: defaultAccountLabel, verbatim: true }, + ...ghAccounts.map((entry) => ({ + value: entry.login, + label: entry.login, + verbatim: true, + })), + ...(account.value && !ghAccounts.some((entry) => entry.login === account.value) + ? [ + { + value: account.value, + label: activeCopilotStatus ? tx`${account.value} (not signed in)` : account.value, + verbatim: true, + }, + ] + : []), + ]; + const copilotSelectedSignedIn = + !activeCopilotStatus || + (account.value === "" + ? activeCopilotStatus.authenticated + : activeCopilotStatus.ghInstalled && ghAccounts.some((entry) => entry.login === account.value)); + const authGate: DefaultsAuthGate = + agent.id !== "copilot" + ? "ready" + : fetchCopilotStatus && !activeCopilotStatus && !copilotStatusLoaded + ? "checking" + : !copilotSelectedSignedIn + ? "unauthenticated" + : account.value !== account.current + ? "pendingApply" + : "ready"; + const accountScope = + agent.id === "copilot" + ? `${account.current || `default:${activeCopilotStatus?.login ?? ""}`}:${authRevision}` + : "default"; return ( <> {value.trim() === current && agent.installed && agent.canCheckCliUpdate && ( )} - {(agent.loginHint || canSignInInIde) && ( + {agent.id === "copilot" ? (
-
- {canSignInInIde && ( - - )} - {agent.loginHint && ( -

- - {commandSpan && ( - void copyText(commandSpan)} - /> - )} -

- )} -
-
- )} -
- -
-
-
- {agent.id === "copilot" && ( +
GitHub account} htmlFor={`agent-github-account-${agent.id}`} hint={ - Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never - stores it. + GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch + and never stored. } > - account.set(e.target.value)} - /> +
+
+