From a5e0c416634e270c2c82efbeb7784ed8e7f86696 Mon Sep 17 00:00:00 2001 From: Deng Liu Date: Thu, 26 Nov 2026 16:16:10 -0800 Subject: [PATCH] feat(github): add project-scoped GitHub CLI account selection (#6277) A project can pin a GitHub CLI account in vcs.github.account (.openidea/settings.toml, a login, never a token), chosen in Settings > Version Control > GitHub or from the Pull Requests tool window header. With an account chosen, its token is resolved through gh and set as GH_TOKEN in the project environment for the project root and its agent worktrees; a .envrc GH_TOKEN still wins, and the token is cleared when the project closes or loses trust. Copilot keeps billing to its own account through COPILOT_GITHUB_TOKEN. Automatic (the default) sets no GH_TOKEN and makes no GitHub calls on project open. When the settings page or the Pull Requests window asks for the status with several gh accounts signed in, the project's GitHub remote is probed to suggest a non-active account with access ("Use for this project"). New commands: gh_project_account_status, gh_set_project_account. The gh account listing is shared with the Copilot account selector. Co-authored-by: dengliu <5108773+dengliu@users.noreply.github.com> --- crates/ide-agent/src/acp/discover.rs | 2 +- crates/ide-agent/src/lib.rs | 5 + crates/ide-agent/src/native/copilot/mod.rs | 4 +- crates/ide-agent/src/provider.rs | 56 ++- crates/ide-core/src/project_env.rs | 135 ++++++- crates/ide-core/src/workflow_settings.rs | 12 + crates/ide-host/src/github_auth.rs | 340 ++++++++++++++++++ crates/ide-host/src/lib.rs | 2 + crates/ide-host/src/ops/project.rs | 53 +++ crates/ide-host/src/project.rs | 6 + crates/ide-host/src/trust.rs | 7 + docs/en/guide/github.mdx | 8 + docs/zh/guide/github.mdx | 3 + e2e/projectGithubAccount.spec.ts | 52 +++ src-tauri/src/commands/github.rs | 7 +- src-tauri/tests/commands.snap | 2 + src/bindings.ts | 30 ++ src/features/github/data/account.ts | 79 ++++ src/features/github/data/repository.ts | 7 +- .../github/diff/GithubSettingsPage.tsx | 83 ++++- .../github/diff/ReviewDiff.module.css | 65 +++- src/features/github/runtime.ts | 25 +- src/features/github/settingsPages.test.tsx | 38 +- src/features/github/settingsPages.ts | 2 +- .../toolwindow/PullRequestsToolWindow.tsx | 155 +++++++- .../github/toolwindow/ToolWindow.module.css | 28 ++ .../github/toolwindow/toolwindow.test.tsx | 46 ++- src/platform/locales/text/en.json | 8 +- src/platform/locales/text/zh.json | 8 +- 29 files changed, 1215 insertions(+), 53 deletions(-) create mode 100644 crates/ide-host/src/github_auth.rs create mode 100644 e2e/projectGithubAccount.spec.ts create mode 100644 src/features/github/data/account.ts diff --git a/crates/ide-agent/src/acp/discover.rs b/crates/ide-agent/src/acp/discover.rs index 348a16553..5e494be0e 100644 --- a/crates/ide-agent/src/acp/discover.rs +++ b/crates/ide-agent/src/acp/discover.rs @@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc, spec: &ProviderSpec, model: Option Err(err) if !prefer_stored && crate::provider::is_copilot_provider(&spec.id) - && crate::provider::has_unconfigured_copilot_ambient_token(&spec.env) + && crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root) && super::auth_required(0, &err) => { let retry = run_once(shared, spec, true, model).await; diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 2251125c3..e700e9cf2 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -832,6 +832,11 @@ impl AgentManager { *self.shared.git_executable.write() = Some(hook); } + /// Directory holding linked Git worktrees created for agent tasks of this project. + pub fn worktrees_dir(&self) -> &Path { + &self.shared.paths.worktrees_dir + } + /// The agents (custom ones re-read), whether each is installed, and what they offered last time. pub fn providers(&self) -> Vec { let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets()); diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 0ce661401..6d46e7b60 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool { pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result { tokio::time::timeout(DISCOVER_TIMEOUT, async move { let prefer_stored = crate::provider::prefer_stored_copilot_auth(); - let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env); + let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd); match discover_once(spec.clone(), cwd.clone(), prefer_stored).await { Err(err) if !prefer_stored @@ -199,7 +199,7 @@ pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> O 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 has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd); let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await; if !prefer_stored && has_ambient diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 1e2e0bda5..ea0061661 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -154,12 +154,26 @@ impl ProviderSpec { cwd: &Path, strip_ambient_tokens: bool, ) -> Result { - let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten(); + let is_copilot = is_copilot_provider(&self.id); + let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten(); + let explicit_copilot_token = + self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty()); let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some()); if let Some(account) = account { let token = github_token_for_account(&account)?; + // Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's + // shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`. resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str())); resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token)); + } else if is_copilot + && !strip_ambient_tokens + && !explicit_copilot_token + && ide_core::project_env::github_token(cwd).is_some() + && let Some(default_token) = default_github_token() + { + // A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model + // billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present. + resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token)); } Ok(resolved) } @@ -169,7 +183,7 @@ impl ProviderSpec { self.command = crate::native::newest_install(&self.command); } if is_copilot_provider(&self.id) { - self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens); + self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens); self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV); } let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env); @@ -386,7 +400,8 @@ fn parse_gh_auth_status_json(text: &str) -> Option> { 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")) { + // Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts. + if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") { continue; } if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) { @@ -406,7 +421,8 @@ fn parse_gh_auth_status_text(text: &str) -> Vec { 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() { + current = None; + if !login.is_empty() && !rest.contains("_TOKEN") { if let Some(idx) = accounts.iter().position(|a| a.login == login) { current = Some(idx); } else { @@ -423,6 +439,20 @@ fn parse_gh_auth_status_text(text: &str) -> Vec { accounts } +fn default_github_token() -> Option { + let program = find_gh_executable()?; + let mut command = std::process::Command::new(program); + ide_core::process::prepare(&mut command); + command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env()); + for name in AMBIENT_COPILOT_AUTH_VARS { + command.env_remove(name); + } + let output = command.output().ok().filter(|out| out.status.success())?; + let token = String::from_utf8(output.stdout).ok()?; + let token = token.trim(); + (!token.is_empty()).then(|| token.to_owned()) +} + pub(crate) fn prefer_stored_copilot_auth() -> bool { PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire) } @@ -431,18 +461,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() { PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release); } -pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool { +pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool { AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| { !spec_env.iter().any(|(k, v)| k == key && !v.is_empty()) - && ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty()) + && ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty()) }) } -fn ambient_copilot_env_value(key: &str) -> Option { - ide_core::process::shell_env() - .find(|(k, _)| *k == key) - .map(|(_, v)| v.to_string_lossy().into_owned()) - .or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned())) +fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option { + ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| { + ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned()) + }) } /// Builds child environment overrides for `copilot`: @@ -453,9 +482,10 @@ fn ambient_copilot_env_value(key: &str) -> Option { /// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`. pub(crate) fn sanitized_copilot_env( spec_env: &[(String, String)], + cwd: &Path, strip_ambient_tokens: bool, ) -> Vec<(String, String)> { - sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value) + sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd)) } pub(crate) fn sanitize_copilot_env_with( @@ -1695,6 +1725,8 @@ mod tests { let text = "\ github.com + ✓ Logged in to github.com account env_user (GH_TOKEN) + - Active account: true ✓ Logged in to github.com account alice (keyring) - Active account: false ✓ Logged in to github.com account alice-work (keyring) diff --git a/crates/ide-core/src/project_env.rs b/crates/ide-core/src/project_env.rs index 75d4b2951..2a0ce1aca 100644 --- a/crates/ide-core/src/project_env.rs +++ b/crates/ide-core/src/project_env.rs @@ -14,10 +14,33 @@ pub type Changes = Arc)>>; struct Entry { root: PathBuf, + direnv: Vec<(OsString, Option)>, + github_token: Option, changes: Changes, loading: bool, } +impl Entry { + fn new(root: PathBuf) -> Self { + Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false } + } + + fn rebuild(&mut self) { + let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some())); + if let Some(token) = &self.github_token { + combined.push(("GH_TOKEN".into(), Some(token.clone()))); + } + // `.envrc` entries override the project GitHub token when both define `GH_TOKEN`. + combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k)); + combined.extend(self.direnv.iter().cloned()); + self.changes = Arc::new(combined); + } + + fn is_idle_empty(&self) -> bool { + !self.loading && self.direnv.is_empty() && self.github_token.is_none() + } +} + static ENTRIES: Mutex> = Mutex::new(Vec::new()); static SETTLED: Condvar = Condvar::new(); @@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) { let mut entries = entries(); match entries.iter_mut().find(|e| e.root == root) { Some(entry) => entry.loading = true, - None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }), + None => { + let mut entry = Entry::new(root.to_path_buf()); + entry.loading = true; + entries.push(entry); + } } } -/// What children started in `root` (or below it) get on top of the IDE's own environment -/// (`None`: removed). Ends a [`begin_loading`]. +/// What children started in `root` (or below it) get from direnv on top of the IDE's own +/// environment (`None`: removed). Ends a [`begin_loading`]. pub fn set(root: &Path, changes: Vec<(OsString, Option)>) { let mut entries = entries(); - let changes = Arc::new(changes); - match entries.iter_mut().find(|e| e.root == root) { - Some(entry) => { - entry.changes = changes; + match entries.iter_mut().position(|e| e.root == root) { + Some(idx) => { + let entry = &mut entries[idx]; + entry.direnv = changes; entry.loading = false; + entry.rebuild(); + if entry.is_idle_empty() { + entries.remove(idx); + } } - None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }), + None if !changes.is_empty() => { + let mut entry = Entry::new(root.to_path_buf()); + entry.direnv = changes; + entry.rebuild(); + entries.push(entry); + } + None => {} } SETTLED.notify_all(); } /// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays. pub fn settle(root: &Path) { - if let Some(entry) = entries().iter_mut().find(|e| e.root == root) { - entry.loading = false; + let mut entries = entries(); + if let Some(idx) = entries.iter().position(|e| e.root == root) { + entries[idx].loading = false; + if entries[idx].is_idle_empty() { + entries.remove(idx); + } } SETTLED.notify_all(); } -/// `root` has no environment of its own any more (closed, or not trusted). +/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted). +/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`]. pub fn remove(root: &Path) { + let mut entries = entries(); + if let Some(idx) = entries.iter().position(|e| e.root == root) { + let entry = &mut entries[idx]; + entry.direnv.clear(); + entry.loading = false; + entry.rebuild(); + if entry.is_idle_empty() { + entries.remove(idx); + } + } + SETTLED.notify_all(); +} + +/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root` +/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed. +pub fn set_github_token(root: &Path, token: Option) -> bool { + let token = token.filter(|t| !t.is_empty()); + let mut entries = entries(); + match entries.iter().position(|e| e.root == root) { + Some(idx) => { + if entries[idx].github_token == token { + return false; + } + let entry = &mut entries[idx]; + entry.github_token = token; + entry.rebuild(); + if entry.is_idle_empty() { + entries.remove(idx); + } + true + } + None => { + let Some(token) = token else { return false }; + let mut entry = Entry::new(root.to_path_buf()); + entry.github_token = Some(token); + entry.rebuild(); + entries.push(entry); + true + } + } +} + +/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any. +pub fn github_token(dir: &Path) -> Option { + find(&entries(), dir).and_then(|e| e.github_token.clone()) +} + +/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted). +pub fn remove_all(root: &Path) { entries().retain(|e| e.root != root); SETTLED.notify_all(); } @@ -135,4 +226,26 @@ mod tests { assert_eq!(*for_dir(root), [change("NEW", Some("2"))]); remove(root); } + + #[test] + fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() { + let root = Path::new("/openidea-test-env/gh-project"); + let worktrees = Path::new("/openidea-test-env/gh-project.worktrees"); + assert!(set_github_token(root, Some("gho_work".into()))); + assert!(!set_github_token(root, Some("gho_work".into())), "idempotent"); + assert!(set_github_token(worktrees, Some("gho_work".into()))); + remove(root); // no `.envrc` in `root` + assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]); + assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]); + assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into())); + + // An explicit `.envrc` GH_TOKEN overrides the project GitHub account token. + set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]); + assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]); + + remove_all(root); + remove_all(worktrees); + assert!(for_dir(root).is_empty()); + assert!(for_dir(worktrees).is_empty()); + } } diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index c4c50b5e4..43752cc63 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -25,6 +25,17 @@ pub struct VcsSettings { pub issue_navigation: Vec, /// Directory Mappings: repository roots added to or excluded from the detected ones. pub mappings: VcsMappings, + /// Settings › Version Control › GitHub: per-project GitHub CLI account selection. + pub github: GithubSettings, +} + +/// Settings › Version Control › GitHub (`vcs.github`). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct GithubSettings { + /// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project. + /// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected). + pub account: String, } /// Directory Mappings on top of repository detection. Paths are relative to the project @@ -68,6 +79,7 @@ impl Default for VcsSettings { shelf: ShelfSettings::default(), issue_navigation: Vec::new(), mappings: VcsMappings::default(), + github: GithubSettings::default(), } } } diff --git a/crates/ide-host/src/github_auth.rs b/crates/ide-host/src/github_auth.rs new file mode 100644 index 000000000..43441d09e --- /dev/null +++ b/crates/ide-host/src/github_auth.rs @@ -0,0 +1,340 @@ +//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection. +//! +//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or +//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN` +//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls. +//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts, +//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account +//! ("Use for this project"). Only when an account is explicitly chosen does OpenIDEA +//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`). + +use crate::Project; +use ide_agent::GhAuthAccount; +use ide_core::cli_process::{CliTool, Decoding}; +use parking_lot::Mutex; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::LazyLock; +use std::time::{Duration, Instant}; + +const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"]; +const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy); +const LOCAL_TIMEOUT: Duration = Duration::from_secs(5); +const PROBE_TIMEOUT: Duration = Duration::from_secs(6); +const CACHE_TTL: Duration = Duration::from_secs(10 * 60); + +/// GitHub CLI accounts available on this machine and which one applies to the project. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct GhProjectAccountStatus { + pub gh_installed: bool, + pub accounts: Vec, + /// Value of `vcs.github.account` (`""` = Automatic). + pub configured_account: String, + /// Account login currently used (`configured_account` if signed in, else `gh`'s active account). + pub effective_account: Option, + /// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty. + pub suggested_account: Option, +} + +#[derive(Clone)] +struct CachedAutoAccount { + login: Option, + at: Instant, +} + +type AutoCacheMap = HashMap<(String, Vec), CachedAutoAccount>; +static AUTO_CACHE: LazyLock> = LazyLock::new(|| Mutex::new(HashMap::new())); + +pub(crate) fn is_valid_github_login(login: &str) -> bool { + let bytes = login.as_bytes(); + !bytes.is_empty() + && bytes.len() <= 39 + && bytes[0].is_ascii_alphanumeric() + && bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_') +} + +fn find_gh_executable() -> Option { + ide_core::tool_path::find_gh_executable() +} + +fn clean_gh_command(program: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new(program); + cmd.current_dir(std::env::temp_dir()) + .args(args) + .env("GH_PROMPT_DISABLED", "1") + .env("GH_NO_UPDATE_NOTIFIER", "1") + .env("NO_COLOR", "1") + .env("CLICOLOR", "0"); + // Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls + // `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`. + for key in AMBIENT_GH_VARS { + cmd.env_remove(key); + } + cmd +} + +fn gh_token_for_account(program: &Path, login: &str) -> Option { + if !is_valid_github_login(login) { + return None; + } + let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]); + let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?; + let token = out.stdout.trim(); + (!token.is_empty()).then(|| token.to_owned()) +} + +/// Access level of an account for a specific `owner/repo` on `github.com`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum RepoAccess { + None = 0, + Read = 1, + Push = 2, +} + +fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess { + let endpoint = format!("repos/{owner}/{name}"); + let mut cmd = + clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]); + cmd.env("GH_TOKEN", token); + let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else { + return RepoAccess::None; + }; + if !out.success { + return RepoAccess::None; + } + if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read } +} + +fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> { + let active_access = + candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None); + // Prefer higher RepoAccess; break ties in favor of the globally active account. + let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?; + if *best_access == RepoAccess::None { + // Nobody could reach the repo (offline or SSO required): keep the active account. + return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false)); + } + let auto_detected = !best.active && *best_access > active_access; + Some((best, auto_detected)) +} + +/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs. +pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> { + let url = url.trim(); + let path = if let Some(rest) = + url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/")) + { + rest + } else if let Some(rest) = url.strip_prefix("ssh://") { + rest.strip_prefix("git@github.com/").or_else(|| rest.strip_prefix("github.com/"))? + } else { + url.strip_prefix("git@github.com:")? + }; + let path = path.trim_matches('/'); + let (owner, rest) = path.split_once('/')?; + let repo = rest.split('/').next()?; + let repo = repo.strip_suffix(".git").unwrap_or(repo); + if owner.is_empty() || repo.is_empty() { + return None; + } + Some((owner.to_owned(), repo.to_owned())) +} + +fn primary_github_repo(project: &Project) -> Option<(String, String)> { + let repos = project.repos(); + let mut ordered = Vec::new(); + if let Some(primary) = repos.primary() { + ordered.push(primary); + } + for repo in repos.all() { + if ordered.first().is_none_or(|p| p.root() != repo.root()) { + ordered.push(repo); + } + } + for repo in ordered { + let Ok(mut remotes) = repo.remotes() else { continue }; + remotes.sort_by_key(|r| r.name != "origin"); + for remote in remotes { + let url = remote.resolved_url.as_deref().unwrap_or(&remote.url); + if let Some(coords) = parse_github_owner_repo(url) { + return Some(coords); + } + } + } + None +} + +fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> { + // Fast path: the repository owner matches one of the signed-in accounts directly. + if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) { + return Some((matched.login.clone(), !matched.active)); + } + let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase()); + let key_logins: Vec = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect(); + let cache_key = (key_repo, key_logins); + if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned() + && cached.at.elapsed() < CACHE_TTL + { + if let Some(login) = cached.login { + let is_active = accounts.iter().any(|a| a.login == login && a.active); + return Some((login, !is_active)); + } + return None; + } + + let tokens: Vec<(GhAuthAccount, Option)> = + accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect(); + let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| { + let handles: Vec<_> = tokens + .into_iter() + .map(|(acc, token)| { + s.spawn(move || { + let access = match token { + Some(tok) => probe_repo_access(program, &tok, owner, repo), + None => RepoAccess::None, + }; + (acc, access) + }) + }) + .collect(); + handles.into_iter().filter_map(|h| h.join().ok()).collect() + }); + let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto)); + AUTO_CACHE + .lock() + .insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() }); + picked +} + +/// Resolves global status when no project is open. +pub fn global_status(configured_account: String) -> GhProjectAccountStatus { + let configured_account = configured_account.trim().to_owned(); + let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts(); + let effective_account = if !configured_account.is_empty() { + accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone()) + } else { + accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone()) + }; + GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None } +} + +/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`] +/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so +/// processes use `gh`'s own behaviour. +pub fn apply_to_project(project: &Project) { + if project.light || !project.is_trusted() { + clear_project_env(project); + return; + } + let configured_account = project.settings.effective().vcs.github.account.trim().to_owned(); + if configured_account.is_empty() { + set_project_token(project, None); + return; + } + let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account)); + set_project_token(project, token); +} + +/// Applies the project's explicit account setting and returns the full account status, +/// probing the project's GitHub remote to suggest a matching non-active `gh` account when +/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in. +pub fn project_status(project: &Project) -> GhProjectAccountStatus { + let configured_account = project.settings.effective().vcs.github.account.trim().to_owned(); + if project.light || !project.is_trusted() { + clear_project_env(project); + return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() }; + } + apply_to_project(project); + let Some(program) = find_gh_executable() else { + return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() }; + }; + let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts(); + let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone()); + + let effective_account = if !configured_account.is_empty() { + accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone()) + } else { + active_login + }; + + let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 { + primary_github_repo(project) + .and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo)) + .and_then(|(login, non_active_match)| non_active_match.then_some(login)) + } else { + None + }; + + GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account } +} + +fn set_project_token(project: &Project, token: Option) { + let os_tok = token.map(std::ffi::OsString::from); + let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone()); + let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok); + if changed_root || changed_wt { + project.agents.notify_mcp_servers_changed(); + } +} + +pub fn clear_project_env(project: &Project) { + ide_core::project_env::remove_all(&project.root); + ide_core::project_env::remove_all(project.agents.worktrees_dir()); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() { + assert_eq!( + parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"), + Some(("l0ng-ai".into(), "openidea".into())) + ); + assert_eq!( + parse_github_owner_repo("git@github.com:acme-corp/payments.git"), + Some(("acme-corp".into(), "payments".into())) + ); + assert_eq!(parse_github_owner_repo("ssh://git@github.com/alice/demo/"), Some(("alice".into(), "demo".into()))); + assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None); + } + + #[test] + fn validates_github_logins_against_flag_injection() { + assert!(is_valid_github_login("alice")); + assert!(is_valid_github_login("alice-work")); + assert!(is_valid_github_login("l0ng-ai")); + assert!(!is_valid_github_login("")); + assert!(!is_valid_github_login("--hostname")); + assert!(!is_valid_github_login("bad space")); + } + + #[test] + fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() { + let personal = GhAuthAccount { login: "alice".into(), active: true }; + let work = GhAuthAccount { login: "alice-work".into(), active: false }; + + // Private org repo: personal gets 404 (None), work gets Push -> auto-detects work. + let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)]; + let (picked, auto) = pick_best_account(&private_org).unwrap(); + assert_eq!(picked.login, "alice-work"); + assert!(auto); + + // Public org repo: personal gets Read, work gets Push -> auto-detects work. + let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)]; + let (picked, auto) = pick_best_account(&public_org).unwrap(); + assert_eq!(picked.login, "alice-work"); + assert!(auto); + + // Third-party public repo: both get Read -> keeps active personal account without auto flag. + let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)]; + let (picked, auto) = pick_best_account(&oss).unwrap(); + assert_eq!(picked.login, "alice"); + assert!(!auto); + } +} diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 80f1a92cc..94bb4d34f 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -12,6 +12,7 @@ pub mod diagnostics_store; mod direnv; pub mod environment; mod formatter; +pub mod github_auth; mod java_runtime; mod kotlin_bridge; pub mod mcp; @@ -419,6 +420,7 @@ impl Host { self.environment.project_closed(); if self.windows_for_root(&project.root).is_empty() { self.environment.direnv_closed(&project.root); + crate::github_auth::clear_project_env(&project); } } if let Some(bridge) = &project.kotlin_bridge { diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 29f13b3a2..689653a40 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -448,6 +448,14 @@ pub fn set_settings( if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" { host.apply_git_executable(); } + if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") { + let affected = affected(); + host.runtime.spawn_blocking(move || { + for project in affected { + crate::github_auth::apply_to_project(&project); + } + }); + } // `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again. if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) { for project in affected() { @@ -524,11 +532,56 @@ pub fn set_settings( Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed }) } +/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project. +#[command(trust = outside_restricted)] +pub async fn gh_project_account_status( + host: &Arc, + window: &str, +) -> IdeResult { + host.require_trust_if_project(window)?; + let current = host.project(window).ok().filter(|p| !p.light); + let global_account = host.global_settings.effective().vcs.github.account; + host.blocking(move || match current { + Some(project) => Ok(crate::github_auth::project_status(&project)), + None => Ok(crate::github_auth::global_status(global_account)), + }) + .await +} + +/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open), +/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status. +#[command(trust = outside_restricted)] +pub async fn gh_set_project_account( + host: &Arc, + window: &str, + account: String, +) -> IdeResult { + host.require_trust_if_project(window)?; + let trimmed = account.trim().to_owned(); + if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) { + return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}"))); + } + let current = host.project(window).ok().filter(|p| !p.light); + let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global }; + let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?; + set_settings(host, window, scope, "vcs.github.account", &json)?; + let sink = host.window_sink(window); + sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() }); + let global_account = host.global_settings.effective().vcs.github.account; + host.blocking(move || match current { + Some(project) => Ok(crate::github_auth::project_status(&project)), + None => Ok(crate::github_auth::global_status(global_account)), + }) + .await +} + ide_command::domain!( project: cancel_request, cancel_task, close_project, + gh_project_account_status, + gh_set_project_account, open_project, project_current, project_roots, diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index 521b0aa21..23c4dc59e 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -762,6 +762,12 @@ impl Host { if let Some(cmd) = post_start { self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone()); } + if project.is_trusted() { + let p = project.clone(); + self.runtime.spawn_blocking(move || { + crate::github_auth::apply_to_project(&p); + }); + } crate::ops::sdk::container_python::ensure(self, &project); Ok(project) } diff --git a/crates/ide-host/src/trust.rs b/crates/ide-host/src/trust.rs index f37581abe..e954e9575 100644 --- a/crates/ide-host/src/trust.rs +++ b/crates/ide-host/src/trust.rs @@ -282,11 +282,18 @@ impl crate::Host { self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone()); } self.environment.direnv_opened(&project.root, &project.sink); + { + let p = project.clone(); + self.runtime.spawn_blocking(move || { + crate::github_auth::apply_to_project(&p); + }); + } project.lsp.set_execution_allowed(true); project.lsp.prewarm_java_configuration(); } else { self.environment.project_closed(); self.environment.direnv_closed(&project.root); + crate::github_auth::clear_project_env(&project); project.agents.shutdown(); project.flutter.stop(); project.devtools.stop(); diff --git a/docs/en/guide/github.mdx b/docs/en/guide/github.mdx index 2c1f9d99c..cf2156495 100644 --- a/docs/en/guide/github.mdx +++ b/docs/en/guide/github.mdx @@ -24,6 +24,14 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh The project needs a Git remote on `github.com`. With one GitHub remote, OpenIDEA connects to it automatically. With several, the tool window asks you to pick a **Repository**; the choice is remembered per project. To switch later, use **Change Repository or Account…** in the tool window's `⋮` menu. + + When multiple `github.com` accounts are signed into `gh`, **Automatic** uses `gh`'s own active account without + setting `GH_TOKEN`. In **Settings › Version Control › GitHub** and in the **Pull Requests** header, OpenIDEA can + suggest a matching account for the repository (**Use `` for this project**) or let you choose one + explicitly (saved in `.openidea/settings.toml`). Choosing an account passes its `GH_TOKEN` to processes started in + that project (terminals, agents, Git, Pull Requests, and run configurations) without changing your global + `gh auth switch` selection. + diff --git a/docs/zh/guide/github.mdx b/docs/zh/guide/github.mdx index 3378d5af8..6610beeba 100644 --- a/docs/zh/guide/github.mdx +++ b/docs/zh/guide/github.mdx @@ -21,6 +21,9 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub: 项目需要有一个指向 `github.com` 的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择 **仓库**,选择按项目记住。之后要切换,可在工具窗口的 `⋮` 菜单中选 **更改仓库或账户…**。 + + 当 `gh` 中登录了多个 `github.com` 账户时,**自动**模式沿用 `gh` 当前的活动账户,不会在项目环境中设置 `GH_TOKEN`。在 **设置 › 版本控制 › GitHub** 和 **拉取请求** 标题栏中,OpenIDEA 会根据仓库远程提示匹配的账户(**对此项目使用 ``**),也可以手动为项目指定账户(保存在 `.openidea/settings.toml`)。显式选择账户后,OpenIDEA 会将该账户的 `GH_TOKEN` 传递给此项目中启动的进程(终端、智能体、Git、拉取请求和运行配置),而不会改动全局的 `gh auth switch` 状态。 + diff --git a/e2e/projectGithubAccount.spec.ts b/e2e/projectGithubAccount.spec.ts new file mode 100644 index 000000000..1124d6f75 --- /dev/null +++ b/e2e/projectGithubAccount.spec.ts @@ -0,0 +1,52 @@ +import type { Page } from "@playwright/test"; +import type { GhProjectAccountStatus } from "../src/bindings"; +import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; + +async function openGithubSettings(page: Page) { + const settings = "/src/features/settings/model/staging.ts"; + await page.evaluate(async (path) => (await import(/* @vite-ignore */ path)).openSettings("vcs.github"), settings); + return page.getByRole("dialog", { name: "Settings", exact: true }); +} + +test("suggests and configures a project-scoped GitHub account in Settings › Version Control › GitHub", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(() => { + let configuredAccount = ""; + const makeStatus = (): GhProjectAccountStatus => ({ + ghInstalled: true, + accounts: [ + { login: "alice", active: true }, + { login: "alice-work", active: false }, + ], + configuredAccount, + effectiveAccount: configuredAccount || "alice", + suggestedAccount: configuredAccount ? null : "alice-work", + }); + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + gh_project_account_status: () => makeStatus(), + gh_set_project_account: ({ account }: { account: string }) => { + configuredAccount = account; + return makeStatus(); + }, + }); + }); + + const dialog = await openGithubSettings(page); + const select = dialog.getByRole("button", { name: "GitHub account" }); + await expect(select).toContainText("Automatic (alice)"); + await expect( + dialog.getByText("Uses GitHub CLI's active account without setting GH_TOKEN in the project environment."), + ).toBeVisible(); + + await dialog.getByRole("button", { name: "Use alice-work for this project" }).click(); + await expect(select).toContainText("alice-work"); + await expect( + dialog.getByText( + "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).", + ), + ).toBeVisible(); + expect(await ipcCalls(page, "gh_set_project_account")).toEqual([{ account: "alice-work" }]); +}); diff --git a/src-tauri/src/commands/github.rs b/src-tauri/src/commands/github.rs index 86bfe8b98..169f0814f 100644 --- a/src-tauri/src/commands/github.rs +++ b/src-tauri/src/commands/github.rs @@ -52,8 +52,13 @@ pub async fn gh_availability( state: State<'_, AppState>, repo: Option, ) -> IdeResult { + let project = state.project(window.label())?; let root = root(&window, &state, repo)?; - blocking(move || Ok(ide_github::availability(&root))).await + blocking(move || { + ide_host::github_auth::apply_to_project(&project); + Ok(ide_github::availability(&root)) + }) + .await } #[desktop_command(trust = trusted)] diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 546af6cc5..a81154f3a 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -318,6 +318,8 @@ gh_pr_prepare_diff trusted desktop bin gh_pr_review trusted desktop bindings async gh_pr_review_comments trusted desktop bindings async gh_pr_view trusted desktop bindings async +gh_project_account_status outside_restricted project_host bindings async +gh_set_project_account outside_restricted project_host bindings async git_credential_forget always desktop bindings sync git_credentials always desktop bindings sync gradle_dependencies trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 1b4b412ee..b76e9eb98 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -795,6 +795,13 @@ export const commands = { ghPrReview: (repo: string | null, number: number, event: ReviewEvent, body: string) => typedError(__TAURI_INVOKE("gh_pr_review", { repo, number, event, body })), ghPrReviewComments: (repo: string | null, number: number) => typedError(__TAURI_INVOKE("gh_pr_review_comments", { repo, number })), ghPrView: (repo: string | null, number: number) => typedError(__TAURI_INVOKE("gh_pr_view", { repo, number })), + /** Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project. */ + ghProjectAccountStatus: () => typedError(__TAURI_INVOKE("gh_project_account_status")), + /** + * Sets `vcs.github.account` for `window`'s project (or globally when no project is open), + * updates the project's `GH_TOKEN` environment immediately, and returns the updated status. + */ + ghSetProjectAccount: (account: string) => typedError(__TAURI_INVOKE("gh_set_project_account", { account })), /** Forgets the credential of `key` (a `git_credentials` entry). */ gitCredentialForget: (key: string) => __TAURI_INVOKE("git_credential_forget", { key }), /** Settings › Git › Saved credentials: `scheme://host` of every saved entry. */ @@ -7717,6 +7724,18 @@ login: string | null } | /** The project has no GitHub remote (or is not a git repository). */ { kind: "notGitHub"; message: string } | { kind: "error"; message: string }; +/** GitHub CLI accounts available on this machine and which one applies to the project. */ +export type GhProjectAccountStatus = { + ghInstalled: boolean, + accounts: GhAuthAccount[], + /** Value of `vcs.github.account` (`""` = Automatic). */ + configuredAccount: string, + /** Account login currently used (`configured_account` if signed in, else `gh`'s active account). */ + effectiveAccount: string | null, + /** Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty. */ + suggestedAccount: string | null, +}; + export type GhRepo = { /** `owner/name`. */ nameWithOwner: string, @@ -7847,6 +7866,15 @@ export type GitSigningEdit = { key: string | null, }; +/** Settings › Version Control › GitHub (`vcs.github`). */ +export type GithubSettings = { + /** + * GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project. + * Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected). + */ + account?: string, +}; + export type GoBuildTags = { /** Empty values inherit the selected toolchain's defaults. */ os?: string, @@ -14586,6 +14614,8 @@ export type VcsSettings = { issueNavigation?: IssueLink[], /** Directory Mappings: repository roots added to or excluded from the detected ones. */ mappings?: VcsMappings, + /** Settings › Version Control › GitHub: per-project GitHub CLI account selection. */ + github?: GithubSettings, }; /** The tool that creates a new Python environment in "Add Python Interpreter". */ diff --git a/src/features/github/data/account.ts b/src/features/github/data/account.ts new file mode 100644 index 000000000..f28f94089 --- /dev/null +++ b/src/features/github/data/account.ts @@ -0,0 +1,79 @@ +/** + * Per-project GitHub CLI (`gh`) account selection (`vcs.github.account` in `.openidea/settings.toml`). + * Kept free of editor/markdown imports so `GithubSettingsPage` stays within `settingsWindowBoot`. + */ +import { create } from "zustand"; +import type { GhProjectAccountStatus } from "@/bindings"; +import { tx } from "@/platform/i18n"; +import { call, commands, isTauri } from "@/platform/ipc"; +import type { SelectOption } from "@/ui"; + +interface GhProjectAccountState { + status: GhProjectAccountStatus | null; + loading: boolean; + saving: boolean; + /** Incremented whenever the user changes the project GitHub account so open views reconnect. */ + revision: number; +} + +export const useGhProjectAccount = create(() => ({ + status: null, + loading: false, + saving: false, + revision: 0, +})); + +export async function loadProjectGithubAccount(): Promise { + if (!isTauri()) return useGhProjectAccount.getState().status; + useGhProjectAccount.setState({ loading: true }); + try { + const status = await call(commands.ghProjectAccountStatus()); + useGhProjectAccount.setState({ status, loading: false }); + return status; + } catch { + useGhProjectAccount.setState({ loading: false }); + return null; + } +} + +export async function setProjectGithubAccount(account: string): Promise { + if (!isTauri()) { + useGhProjectAccount.setState((s) => ({ + status: s.status + ? { + ...s.status, + configuredAccount: account, + effectiveAccount: account || s.status.accounts.find((a) => a.active)?.login || null, + suggestedAccount: account ? null : s.status.suggestedAccount, + } + : null, + revision: s.revision + 1, + })); + return useGhProjectAccount.getState().status; + } + useGhProjectAccount.setState({ saving: true }); + try { + const status = await call(commands.ghSetProjectAccount(account)); + useGhProjectAccount.setState((s) => ({ status, saving: false, revision: s.revision + 1 })); + return status; + } catch { + useGhProjectAccount.setState({ saving: false }); + return null; + } +} + +export function projectAccountOptions(status: GhProjectAccountStatus | null): SelectOption[] { + const accounts = status?.accounts ?? []; + const configured = status?.configuredAccount ?? ""; + const activeLogin = + accounts.find((a) => a.active)?.login ?? (!configured ? (status?.effectiveAccount ?? null) : null); + const automaticLabel = activeLogin ? tx`Automatic (${activeLogin})` : tx("Automatic"); + + return [ + { value: "", label: automaticLabel, verbatim: true }, + ...accounts.map((a) => ({ value: a.login, label: a.login, verbatim: true })), + ...(configured && !accounts.some((a) => a.login === configured) + ? [{ value: configured, label: tx`${configured} (not signed in)`, verbatim: true }] + : []), + ]; +} diff --git a/src/features/github/data/repository.ts b/src/features/github/data/repository.ts index 5354088a0..9cf21b7ac 100644 --- a/src/features/github/data/repository.ts +++ b/src/features/github/data/repository.ts @@ -224,7 +224,12 @@ export async function connect( if (seq !== connectSeq) return false; if (!repository) throw new Error(`Repository ${nameWithOwner(coordinates)} not found`); const previous = useGhRepository.getState().connection; - if (!sameRepository(previous?.coordinates, coordinates) || previous?.root !== root) resetRepositoryData(); + if ( + !sameRepository(previous?.coordinates, coordinates) || + previous?.root !== root || + previous?.currentUser.login !== currentUser.login + ) + resetRepositoryData(); setCurrentRepository({ ...coordinates, id: repository.id, root }); useGhRepository.setState((s) => ({ connection: { coordinates, repository, currentUser, root, remotes }, diff --git a/src/features/github/diff/GithubSettingsPage.tsx b/src/features/github/diff/GithubSettingsPage.tsx index 522ae71f2..40dd83012 100644 --- a/src/features/github/diff/GithubSettingsPage.tsx +++ b/src/features/github/diff/GithubSettingsPage.tsx @@ -1,20 +1,87 @@ /** - * Settings › Version Control › GitHub (`GithubSettingsConfigurable`); accounts are gh's, so - * only the pull request option is here. Applies at once, like the Log page. + * Settings › Version Control › GitHub (`GithubSettingsConfigurable`): per-project GitHub CLI + * account selection (`vcs.github.account`) and pull request review options. Applies at once, + * like the Log page. */ -import { Checkbox } from "@/ui"; +import { useEffect, useId } from "react"; +import { tx } from "@/platform/i18n"; +import { Button, Checkbox, Select, T } from "@/ui"; +import { + loadProjectGithubAccount, + projectAccountOptions, + setProjectGithubAccount, + useGhProjectAccount, +} from "../data/account"; import { setReviewDiffSettings, useReviewDiffSettings } from "./settings"; import styles from "./ReviewDiff.module.css"; export function GithubSettingsPage() { const autoMarkViewed = useReviewDiffSettings((s) => s.autoMarkViewed); + const status = useGhProjectAccount((s) => s.status); + const saving = useGhProjectAccount((s) => s.saving); + const accountHeading = useId(); + const prHeading = useId(); + const selectId = useId(); + + useEffect(() => { + void loadProjectGithubAccount(); + }, []); + + const options = projectAccountOptions(status); + const value = status?.configuredAccount ?? ""; + const suggested = !value ? (status?.suggestedAccount ?? null) : null; + return (
- setReviewDiffSettings({ autoMarkViewed: v })} - label="Automatically mark opened files as viewed" - /> +
+

+ Account +

+
+ +
+
+
+ void setProjectGithubAccount(next)} + /> + {status.configuredAccount && ( +
+ + Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run + configurations). + +
+ )} +
+ ); +} + function Unavailable({ availability }: { availability: GhAvailability }) { const [installingGh, setInstallingGh] = useState(false); const [installError, setInstallError] = useState(null); @@ -101,6 +144,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) { } > Run gh auth login in a terminal, then retry. + ); case "notGitHub": @@ -115,7 +159,8 @@ function Unavailable({ availability }: { availability: GhAvailability }) { case "error": return ( - {availability.message} +
{availability.message}
+
); default: @@ -123,12 +168,14 @@ function Unavailable({ availability }: { availability: GhAvailability }) { } } -/** IntelliJ's repository selector: the repositories (owner always shown) and "View Pull Requests". */ +/** IntelliJ's repository selector: the repositories (owner always shown), project account, and "View Pull Requests". */ function RepositorySelector() { const remotes = useGhRepository((s) => s.remotes); const defaultRemote = useGhRepository((s) => s.defaultRemote); const connecting = useGhRepository((s) => s.connecting); const error = useGhRepository((s) => s.connectionError); + const status = useGhProjectAccount((s) => s.status); + const savingAccount = useGhProjectAccount((s) => s.saving); const [chosen, setChosen] = useState(null); const value = chosen ?? @@ -136,6 +183,36 @@ function RepositorySelector() { const target = remotes.find((r) => nameWithOwner(r) === value); return (
+ {status && status.accounts.length > 0 && ( + <> +
+ !!s.connection); const connecting = useGhRepository((s) => s.connecting); useEffect(() => { + if (!useGhProjectAccount.getState().status) void loadProjectGithubAccount(); if (!useGhRepository.getState().availability) void refreshConnection(); }, []); if (!availability) @@ -297,21 +375,82 @@ export function PullRequestsTabs() { ); } -/** Title actions: Create Pull Request… (+) and Select Opened Pull Request, while connected. */ +/** Title actions: account switcher (when multi-account), Create Pull Request… (+) and Select Opened Pull Request. */ export function PullRequestsHeaderActions() { - const connected = useGhRepository((s) => !!s.connection); - if (!connected) return null; + const connection = useGhRepository((s) => s.connection); + const status = useGhProjectAccount((s) => s.status); + if (!connection) return null; + const showAccount = (status?.accounts.length ?? 0) > 1 || !!status?.configuredAccount; + const activeLogin = connection.currentUser.login || status?.effectiveAccount || ""; + const suggested = !status?.configuredAccount ? (status?.suggestedAccount ?? null) : null; return ( <> + {showAccount && status && activeLogin && ( + + )} ); } -/** The "⋮" menu's own items: Change Repository or Account… (connected, several GitHub remotes). */ -export function headerMenu(s: Pick, "connection" | "remotes">): MenuItem[] { - return s.connection && s.remotes.length > 1 ? CHANGE_REPOSITORY : NONE; +/** The "⋮" menu's own items: suggested account (if any) and Change Repository or Account…. */ +export function headerMenu( + s: Pick, "connection" | "remotes">, + acct?: GhProjectAccountStatus | null, +): MenuItem[] { + if (!s.connection) return NONE; + const suggested = !acct?.configuredAccount ? (acct?.suggestedAccount ?? null) : null; + const multipleAccounts = (acct?.accounts.length ?? 0) > 1 || !!acct?.configuredAccount; + if (!suggested && s.remotes.length <= 1 && !multipleAccounts) return NONE; + return [ + ...(suggested + ? [ + { + label: tx`Use ${suggested} for this project`, + verbatim: true, + run: () => void setProjectGithubAccount(suggested), + }, + ] + : []), + ...CHANGE_REPOSITORY, + ]; } const NONE: MenuItem[] = []; diff --git a/src/features/github/toolwindow/ToolWindow.module.css b/src/features/github/toolwindow/ToolWindow.module.css index 1e8c6077d..5378c6ddb 100644 --- a/src/features/github/toolwindow/ToolWindow.module.css +++ b/src/features/github/toolwindow/ToolWindow.module.css @@ -36,6 +36,34 @@ .tabs { min-width: 0; } +.accountBadge { + flex: 0 1 auto; + height: 22px; + min-width: 48px; + max-width: 100px; + padding: 0 6px; + overflow: hidden; + border: 1px solid var(--border); + border-radius: 4px; + background: transparent; + color: var(--fg-secondary); + font-family: var(--font-ui); + font-size: var(--fs-small); + text-overflow: ellipsis; + white-space: nowrap; + cursor: pointer; +} +.accountBadge:hover { + background: var(--bg-hover); + color: var(--fg); +} +.accountInline { + display: flex; + flex-direction: column; + align-items: center; + gap: var(--space-1-5); + margin-top: 8px; +} /* 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 7c701db20..c35367329 100644 --- a/src/features/github/toolwindow/toolwindow.test.tsx +++ b/src/features/github/toolwindow/toolwindow.test.tsx @@ -7,9 +7,15 @@ import { provideToolWindowService, useContributions, type ToolWindowService } fr import { activate } from "../index"; import { setCurrentRepository } from "../api/client"; import type { GHRepository, GHUser } from "../api/types"; +import { useGhProjectAccount } from "../data/account"; import * as repositoryData from "../data/repository"; import { useGhRepository } from "../data/repository"; -import { PullRequestsTabs, PullRequestsToolWindow } from "./PullRequestsToolWindow"; +import { + PullRequestsHeaderActions, + PullRequestsTabs, + PullRequestsToolWindow, + headerMenu, +} from "./PullRequestsToolWindow"; import { closeTab, contextPullRequest, @@ -86,6 +92,7 @@ describe("tool window", () => { vi.restoreAllMocks(); setCurrentRepository(null); useGhRepository.setState({ connection: null, availability: null, remotes: [] }); + useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 }); resetTabs(); }); @@ -193,4 +200,41 @@ describe("tool window", () => { await act(async () => openPullRequestTab(4)); expect(screen.getByRole("tab", { name: /#4/ })).toBeTruthy(); }); + + it("suggests a matching GitHub account in the header menu and shows the active account badge", () => { + const connState = { + connection: { + coordinates: { owner: "org", name: "app" }, + repository, + currentUser: { ...me, login: "alice" }, + root: null, + remotes: [], + }, + remotes: [{ owner: "org", name: "app", remote: "origin", url: "" }], + }; + expect(headerMenu(connState, null)).toEqual([]); + const multiStatus = { + ghInstalled: true, + accounts: [ + { login: "alice", active: true }, + { login: "alice-work", active: false }, + ], + configuredAccount: "", + effectiveAccount: "alice", + suggestedAccount: "alice-work", + }; + expect(headerMenu(connState, multiStatus).map((i) => ("label" in i ? i.label : ""))).toEqual([ + "Use alice-work for this project", + "Change Repository or Account…", + ]); + + useGhRepository.setState({ + availability: { kind: "ready", repo: {} as never, login: "alice" }, + ...connState, + }); + useGhProjectAccount.setState({ status: multiStatus }); + render(); + const badge = screen.getByRole("button", { name: "@alice" }); + expect(badge).toHaveAttribute("title", "Use alice-work for this project"); + }); }); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7a5569fa8..d68f931bb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4199,5 +4199,11 @@ "Checking sign-in status…": "Checking sign-in status…", "Sign in above to view and choose models available for this account.": "Sign in above to view and choose models available for this account.", "Click Apply to load the models available for the selected account.": "Click Apply to load the models available for the selected account.", - "Loading models for this account…": "Loading models for this account…" + "Loading models for this account…": "Loading models for this account…", + "Account": "Account", + "Automatic ({activeLogin})": "Automatic ({activeLogin})", + "Use {suggested} for this project": "Use {suggested} for this project", + "GitHub account: @{activeLogin}": "GitHub account: @{activeLogin}", + "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.", + "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations)." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 73e62a1f9..5f25cb9ab 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10647,5 +10647,11 @@ "Checking sign-in status…": "正在检查登录状态…", "Sign in above to view and choose models available for this account.": "请在上方登录以查看并选择此账户可用的模型。", "Click Apply to load the models available for the selected account.": "点击“应用”以加载所选账户可用的模型。", - "Loading models for this account…": "正在加载此账户的模型…" + "Loading models for this account…": "正在加载此账户的模型…", + "Account": "账户", + "Automatic ({activeLogin})": "自动({activeLogin})", + "Use {suggested} for this project": "对此项目使用 {suggested}", + "GitHub account: @{activeLogin}": "GitHub 账户:@{activeLogin}", + "Uses GitHub CLI's active account without setting GH_TOKEN in the project environment.": "使用 GitHub CLI 当前活动账户,不在项目环境中设置 GH_TOKEN。", + "Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).": "将此账户的 GH_TOKEN 传递给此项目中启动的进程(终端、智能体、Git 和运行配置)。" }