Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai aa2facac51 refactor(github): reuse the gh account listing from ide-agent
The project account status parsed gh auth status a second time with its own
account type. It now uses ide_agent::gh_authenticated_accounts and GhAuthAccount;
that parser also drops any environment-sourced entry (*_TOKEN or env), in the
JSON and the text output.
2026-11-27 08:15:50 +08:00
Deng Liu 7ec2539252 feat(github): add project-scoped GitHub CLI account selection and auto-detection 2026-11-26 15:56:46 -08:00
audichuang 77071238a0 fix(gradle): keep absolute owner for synced builds outside the project (#6260)
After a Gradle sync, an included build outside the project root (includeBuild('../svc')) was missing from Find in Files > Module: with_gradle_roots stamped plain Gradle as its owner, which the UI reads as the project root. Such builds now keep their absolute owner (<dir>/Gradle), which projectModules, the Module scope and changeModules already treat as an absolute module.

An ancestor of the opened folder (opening composite/app while Gradle reports composite) and a filesystem or drive root keep plain Gradle, so they can't claim every in-project file. Reported project dirs are canonicalized like the opened root, and moduleOf also recognises drive-letter module paths.

Co-authored-by: audichuang <[email protected]>
2026-11-27 07:56:28 +08:00
Deng Liuтаdengliu 64097d3c20 feat(agents): unify Copilot GitHub account selector and gate models on auth (#6269)
Copilot's Sign In notice and the free-text Launch > GitHub account field become one Sign In section: a GitHub account selector listing Copilot CLI's own default login (with its status from auth.getStatus) and the github.com accounts signed in to GitHub CLI (gh auth status, ignoring ambient token variables), plus Sign In... and an in-IDE Add account... that runs gh auth login in the sign-in dialog and selects the new account.

New Tasks model controls wait until the selected account is signed in and applied, and load that account's model catalog instead of showing a cached one from another account or subscription; changing the account evicts the idle Copilot catalog probe.

New commands: agent_copilot_auth_status, agent_gh_login_spawn.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:34:47 +08:00
Deng Liuтаdengliu cf0e57e5df fix(agents): advance history batching past long folded process runs (#6278)
A session's history paints from the end in batches of ENTRY_BATCH, and the first painted entry moves back over a leading run of tool calls so a folded process row is never split. Since all consecutive tool calls fold into one run, a run longer than a batch made the next batch end inside the same run, so start never moved: the background batches and loading earlier messages at the top both stalled, and earlier turns never appeared (also after a hidden tab trimmed its history).

The next batch now steps past what is actually painted. A conversation scrolled away from the end also keeps loading while its rows don't fill the viewport or it sits near the top.

Co-authored-by: dengliu <[email protected]>
2026-11-27 07:20:55 +08:00
l0ng-ai 703cf23296 fix(workspace): don't let refactoring undo overwrite an external write under an unsaved buffer (#6281)
Fingerprints hash an unsaved buffer in place of its file, so a file another
program wrote after a refactoring went unnoticed while its buffer had unsaved
changes, and undo (or redo) wrote the snapshot over it.

Each document now counts the disk conflicts it has seen (external writes while
the buffer had unsaved changes). The undo record keeps the counts as of the
refactoring; undo and redo first check unsaved buffers' files for a write the
watcher hasn't reported yet, then refuse when a count moved. The IDE's own
saves don't count, so saving and undoing typing before undoing the refactoring
still works, and a conflict from before the refactoring doesn't block it.

Fixes #6264
2026-11-27 07:16:02 +08:00
52 змінених файлів з 2819 додано та 209 видалено

No files matched your search

+1 -1
Переглянути файл
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, 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;
+51 -2
Переглянути файл
@@ -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<dyn Fn(AgentEvent) + Send + Sync>;
@@ -804,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<AgentProvider> {
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
@@ -853,6 +886,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<String>) -> IdeResult<()> {
@@ -875,7 +922,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.
+20
Переглянути файл
@@ -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<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
pub gh_installed: bool,
pub gh_accounts: Vec<GhAuthAccount>,
}
/// 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")]
+73 -1
Переглянути файл
@@ -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<Discovered, DiscoverError> {
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
@@ -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<String>,
pub auth_type: Option<String>,
pub status_message: Option<String>,
}
/// 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<CliAuthStatus> {
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, &cwd);
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<CliAuthStatus> {
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<dyn Handler>,
+212 -21
Переглянути файл
@@ -2,7 +2,10 @@
//! `<config>/agents/<id>.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;
@@ -151,12 +154,26 @@ impl ProviderSpec {
cwd: &Path,
strip_ambient_tokens: bool,
) -> Result<Self, String> {
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)
}
@@ -166,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);
@@ -268,16 +285,15 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
.map(str::to_owned)
}
fn find_gh_executable() -> Option<PathBuf> {
ide_core::tool_path::find_gh_executable()
}
fn github_token_for_account(account: &str) -> Result<String, String> {
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 +319,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
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<LoginLaunch> {
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<GhAuthAccount>) {
let Some(program) = find_gh_executable() else {
return (false, Vec::new());
};
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
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<Vec<GhAuthAccount>> {
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Entry {
#[serde(default)]
state: Option<String>,
#[serde(default)]
active: bool,
#[serde(default)]
login: String,
#[serde(default)]
token_source: Option<String>,
}
#[derive(Deserialize)]
struct Response {
#[serde(default)]
hosts: BTreeMap<String, Vec<Entry>>,
}
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
let mut accounts: Vec<GhAuthAccount> = 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;
}
// 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) {
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<GhAuthAccount> {
let mut accounts: Vec<GhAuthAccount> = Vec::new();
let mut current: Option<usize> = 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();
current = None;
if !login.is_empty() && !rest.contains("_TOKEN") {
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
}
fn default_github_token() -> Option<String> {
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)
}
@@ -311,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<String> {
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<String> {
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`:
@@ -333,9 +482,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
/// 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(
@@ -1251,12 +1401,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 +1415,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 +1700,47 @@ 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 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)
- 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();
+124 -11
Переглянути файл
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
struct Entry {
root: PathBuf,
direnv: Vec<(OsString, Option<OsString>)>,
github_token: Option<OsString>,
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<Vec<Entry>> = 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<OsString>)>) {
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<OsString>) -> 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<OsString> {
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());
}
}
+12
Переглянути файл
@@ -25,6 +25,17 @@ pub struct VcsSettings {
pub issue_navigation: Vec<IssueLink>,
/// 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(),
}
}
}
+340
Переглянути файл
@@ -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 <login> 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<GhAuthAccount>,
/// 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<String>,
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
pub suggested_account: Option<String>,
}
#[derive(Clone)]
struct CachedAutoAccount {
login: Option<String>,
at: Instant,
}
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = 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<PathBuf> {
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<String> {
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("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
} else {
url.strip_prefix("[email protected]:")?
};
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<String> = 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<String>)> =
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<String>) {
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("[email protected]:acme-corp/payments.git"),
Some(("acme-corp".into(), "payments".into()))
);
assert_eq!(parse_github_owner_repo("ssh://[email protected]/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);
}
}
+2
Переглянути файл
@@ -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 {
+39 -4
Переглянути файл
@@ -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<CopilotAuthStatus> {
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<AgentLoginEvent>,
) -> IdeResult<ide_terminal::TerminalInfo> {
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,
+53
Переглянути файл
@@ -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<Host>,
window: &str,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
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<Host>,
window: &str,
account: String,
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
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,
+115 -6
Переглянути файл
@@ -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)
}
@@ -2015,7 +2021,9 @@ fn independent_eclipse_projects(root: &Path) -> Vec<PathBuf> {
/// The detected roots with the last Gradle sync's source sets first: Gradle evaluated what
/// static detection guesses. Folders outside the project keep their absolute path, which
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`);
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
/// module lists still address them as absolute paths.
fn with_gradle_roots(
root: &Path,
build_cache: &Path,
@@ -2039,12 +2047,22 @@ fn with_gradle_roots(
};
if !out.iter().any(|f| f.path == path) {
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
// the UI reads the folder as project-relative.
// UI still finds the module after a sync. Projects outside the root keep their
// absolute owner (without `normalize`, which strips a leading `/`), except an ancestor
// of the root (opened from a subproject) or a filesystem/drive root, which stay
// `Gradle` so they cannot shadow in-project modules or collapse to a bare drive `D:`.
let project = dunce::canonicalize(&project).unwrap_or(project);
let detected_from = match project.strip_prefix(root) {
Ok(rel) if !rel.as_os_str().is_empty() => {
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
}
Err(_) if !root.starts_with(&project) && project.parent().is_some() => {
let raw = project.to_string_lossy().replace('\\', "/");
let owner = raw.trim_end_matches('/');
let drive_root =
owner.len() == 2 && owner.as_bytes()[0].is_ascii_alphabetic() && owner.as_bytes()[1] == b':';
if owner.is_empty() || drive_root { "Gradle".into() } else { format!("{owner}/Gradle") }
}
_ => "Gradle".into(),
};
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
@@ -2492,18 +2510,109 @@ mod gradle_roots_tests {
std::fs::write(root.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let owner = format!("{}/Gradle", svc.to_string_lossy().replace('\\', "/"));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
// A project outside the root is not a module the UI could address.
// A project outside the root keeps its absolute owner so module lists still address it.
assert_eq!(
got,
[
("src/it/java".into(), RootKind::Test, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
("web".into(), RootKind::Source, None),
]
);
}
#[test]
fn gradle_sync_roots_keep_plain_gradle_for_ancestors_and_fs_roots() {
let tmp = tempfile::tempdir().unwrap();
let composite = dunce::canonicalize(tmp.path()).unwrap();
let app = composite.join("app");
let lib = app.join("lib");
let cache = composite.join("cache");
let ext_posix = composite.join("ext-posix/src/main/java");
let ext_win = composite.join("ext-win/src/main/java");
for d in [
composite.join("src/main/java"),
app.join("src/main/java"),
lib.join("src/main/java"),
ext_posix.clone(),
ext_win.clone(),
cache.clone(),
] {
std::fs::create_dir_all(d).unwrap();
}
let s = |p: PathBuf| p.to_string_lossy().into_owned();
// Opened at `composite/app` while Gradle discovers parent `composite/settings.gradle`
// (so `composite` is an ancestor of `root`), plus external roots owned by `/` or `D:/`.
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
{ "path": ":", "dir": s(composite.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(composite.join("src/main/java"))], "res": [] } ] },
{ "path": ":app", "dir": s(app.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
{ "path": ":app:lib", "dir": s(lib.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
{ "path": ":posix-root", "dir": "/", "sourceSets": [
{ "name": "main", "test": false, "src": [s(ext_posix.clone())], "res": [] } ] },
{ "path": ":win-drive", "dir": "D:/", "sourceSets": [
{ "name": "main", "test": false, "src": [s(ext_win.clone())], "res": [] } ] },
]});
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
std::fs::write(app.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
assert_eq!(
got,
[
(abs(composite.join("src/main/java")), Some("Gradle")),
("src/main/java".into(), Some("Gradle")),
("lib/src/main/java".into(), Some("lib/Gradle")),
(abs(ext_posix), Some("Gradle")),
(abs(ext_win), Some("Gradle")),
]
);
}
#[cfg(unix)]
#[test]
fn gradle_sync_roots_canonicalize_symlinked_project_dirs() {
let tmp = tempfile::tempdir().unwrap();
let ws = dunce::canonicalize(tmp.path()).unwrap();
let real = ws.join("real");
let link = ws.join("link");
let app = real.join("app");
let lib = app.join("lib");
let cache = ws.join("cache");
for d in [real.join("src/main/java"), app.join("src/main/java"), lib.join("src/main/java"), cache.clone()] {
std::fs::create_dir_all(d).unwrap();
}
std::os::unix::fs::symlink(&real, &link).unwrap();
let s = |p: PathBuf| p.to_string_lossy().into_owned();
// Opened at canonical `real/app`, while Gradle reports projects through the symlink `link`.
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
{ "path": ":", "dir": s(link.clone()), "sourceSets": [
{ "name": "main", "test": false, "src": [s(real.join("src/main/java"))], "res": [] } ] },
{ "path": ":app", "dir": s(link.join("app")), "sourceSets": [
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
{ "path": ":app:lib", "dir": s(link.join("app/lib")), "sourceSets": [
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
]});
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
std::fs::write(app.join("build.gradle"), "").unwrap();
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
assert_eq!(
got,
[
(abs(real.join("src/main/java")), Some("Gradle")),
("src/main/java".into(), Some("Gradle")),
("lib/src/main/java".into(), Some("lib/Gradle")),
]
);
}
}
#[cfg(test)]
+7
Переглянути файл
@@ -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();
+31 -20
Переглянути файл
@@ -174,6 +174,9 @@ struct DocState {
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
/// alone until the user saves explicitly or the buffer is reloaded.
disk_conflict: bool,
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
external_writes: u64,
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
@@ -540,6 +543,7 @@ impl Documents {
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: None,
@@ -616,6 +620,7 @@ impl Documents {
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: Some(uri.to_owned()),
@@ -676,6 +681,7 @@ impl Documents {
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
external_writes: 0,
clean_text: None,
closed: false,
uri: Some(key.to_string_lossy().into_owned()),
@@ -948,20 +954,7 @@ impl Documents {
/// on disk after this buffer was edited, which only an explicit save may overwrite.
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
// The watcher event for an external write may not have arrived yet: check the stamp now.
if st.dirty
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& st.changed_on_disk(&meta)
{
st.disk_mtime = ide_vfs::mtime_ms(&meta);
st.disk_len = meta.len();
st.disk_conflict = true;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
}
self.check_disk_conflict(doc, st);
if st.dirty && st.disk_conflict {
return Ok(false);
}
@@ -969,6 +962,29 @@ impl Documents {
})
}
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
/// yet, so check the stamp now.
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
if st.dirty
&& !st.disk_conflict
&& st.uri.is_none()
&& let Ok(meta) = std::fs::metadata(&st.path)
&& st.changed_on_disk(&meta)
{
self.disk_conflict(doc, st, &meta);
}
}
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
st.disk_mtime = ide_vfs::mtime_ms(meta);
st.disk_len = meta.len();
st.disk_conflict = true;
st.external_writes += 1;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
}
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
{
if !st.dirty || st.uri.is_some() {
@@ -1443,12 +1459,7 @@ impl Documents {
if !st.changed_on_disk(&meta) {
return Ok(());
}
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
// The text read before no longer matches the file: undoing back to it is not clean.
st.clean_text = None;
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
self.disk_conflict(id, st, &meta);
return Ok(());
}
let loaded = if force_clean {
+42 -1
Переглянути файл
@@ -100,6 +100,8 @@ struct Record {
paths: Vec<SavedPath>,
documents: Vec<(DocId, DocState)>,
after: Vec<WorkspaceEditPrecondition>,
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
writes: Vec<(DocId, u64)>,
}
fn stale(path: &Path) -> IdeError {
@@ -369,6 +371,35 @@ impl Documents {
.collect()
}
/// How many external writes each open document under `roots` has seen, with its path. An
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
let mut writes = Vec::new();
for id in self.open_documents() {
self.with_doc(id, |state| {
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
self.check_disk_conflict(id, state);
writes.push((id, state.external_writes, state.path.clone()));
}
Ok(())
})?;
}
Ok(writes)
}
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
for (id, writes, path) in self.external_writes(roots)? {
// A document opened since then starts at zero.
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
if writes != before {
return Err(stale(&path));
}
}
Ok(())
}
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
for (before, after) in expected.iter().zip(current) {
@@ -469,6 +500,10 @@ impl Documents {
Ok(after) => after,
Err(error) => return Err(self.recover(record, error)),
};
record.writes = match self.external_writes(&roots) {
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
Err(error) => return Err(self.recover(record, error)),
};
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
return Err(self.recover(record, error.into()));
}
@@ -568,6 +603,7 @@ impl Documents {
paths,
documents,
after: Vec::new(),
writes: Vec::new(),
})
}
@@ -869,8 +905,9 @@ impl Documents {
if record.undone != redo {
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
}
self.validate_preconditions(&record.after)?;
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
self.validate_external_writes(record, &roots)?;
self.validate_preconditions(&record.after)?;
let mut current = self.backup(&roots)?;
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
let _active = ActiveEdit::new(&self.workspace_edit_active);
@@ -881,6 +918,10 @@ impl Documents {
Ok(after) => after,
Err(error) => return Err(self.recover(current, error)),
};
current.writes = match self.external_writes(&roots) {
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
Err(error) => return Err(self.recover(current, error)),
};
current.undone = !redo;
current.created = record.created;
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
+74
Переглянути файл
@@ -426,6 +426,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
}
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
std::fs::write(path, "old\n").unwrap();
let (docs, events) = recorded_documents();
let info = docs.open(path).unwrap();
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
.unwrap();
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
(docs, events, info.id)
}
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
let snapshot = docs.snapshot(id).unwrap();
let to = snapshot.text.encode_utf16().count() as u32;
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
.unwrap();
}
#[test]
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
// Not reported by a watcher: undo itself notices the write.
std::fs::write(&path, "external\n").unwrap();
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
}
#[test]
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
type_text(&docs, id, "typed later\n");
docs.save(id).unwrap();
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
type_text(&docs, id, "new\n");
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
}
#[test]
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
std::fs::write(&path, "old\n").unwrap();
let (docs, events) = recorded_documents();
let info = docs.open(&path).unwrap();
type_text(&docs, info.id, "own\n");
std::fs::write(&path, "external\n").unwrap();
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
docs.undo_workspace_edit(undo_id(&events)).unwrap();
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
}
#[test]
fn redo_keeps_an_external_write_made_after_the_undo() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("a.txt");
let (docs, events, id) = refactored_unsaved(&path);
let undo = undo_id(&events);
docs.undo_workspace_edit(undo).unwrap();
std::fs::write(&path, "external\n").unwrap();
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
}
#[test]
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
let tmp = tempfile::tempdir().unwrap();
+2
Переглянути файл
@@ -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
+8
Переглянути файл
@@ -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 `<login>` 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.
</Step>
</Steps>
+2
Переглянути файл
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
### 外部 MCP 服务器
+3
Переглянути файл
@@ -21,6 +21,9 @@ OpenIDEA 通过 [GitHub CLI](https://cli.github.com)(`gh`)对接 GitHub:
<Step title="打开带 GitHub 远程的项目">
项目需要有一个指向 `github.com` 的 Git 远程。只有一个 GitHub 远程时自动连接;有多个时,工具窗口会让你选择
**仓库**,选择按项目记住。之后要切换,可在工具窗口的 `⋮` 菜单中选 **更改仓库或账户…**。
当 `gh` 中登录了多个 `github.com` 账户时,**自动**模式沿用 `gh` 当前的活动账户,不会在项目环境中设置 `GH_TOKEN`。在 **设置 › 版本控制 › GitHub** 和 **拉取请求** 标题栏中,OpenIDEA 会根据仓库远程提示匹配的账户(**对此项目使用 `<login>`**),也可以手动为项目指定账户(保存在 `.openidea/settings.toml`)。显式选择账户后,OpenIDEA 会将该账户的 `GH_TOKEN` 传递给此项目中启动的进程(终端、智能体、Git、拉取请求和运行配置),而不会改动全局的 `gh auth switch` 状态。
</Step>
</Steps>
+164
Переглянути файл
@@ -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<string, string> = { 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<string, string> }) => {
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",
},
},
]);
});
+45
Переглянути файл
@@ -209,3 +209,48 @@ test("opens a folded process run with the keyboard and jumps back to the latest
await expect(jump).toBeHidden();
await expect.poll(() => stream.evaluate((el) => el.scrollHeight - el.clientHeight - el.scrollTop)).toBeLessThan(40);
});
test("paints earlier turns past folded process runs longer than ENTRY_BATCH", async ({ page }) => {
const longRun = (prefix: string, count: number): AgentEntry[] =>
Array.from({ length: count }, (_, i): AgentEntry => ({
type: "tool",
id: `${prefix}-${i}`,
kind: i % 3 === 0 ? "edit" : i % 2 === 0 ? "execute" : "read",
title: `tool ${prefix}-${i}`,
status: "completed",
locations: [],
output: null,
diffs: [],
}));
const longProcessEntries: AgentEntry[] = [
{ type: "user", text: "Earliest request before long runs", attachments: [], steered: false },
{ type: "agent", text: "Initial reply" },
{ type: "user", text: "Split PR into three focused PRs", attachments: [], steered: false },
...longRun("batch-a", 75),
{ type: "agent", text: "Interim status update" },
...longRun("batch-b", 75),
];
await page.goto("/");
await page.getByRole("tree", { name: "Project" }).waitFor();
await page.evaluate(
async ({ task, entries }) => {
const path = "/src/features/agents/store.ts";
const store = await import(path);
store.useAgents.setState({
loaded: true,
error: null,
providers: [],
tasks: new Map([[task.id, { ...task, status: "running" }]]),
entries: new Map([[task.id, entries]]),
unread: new Set(),
docked: null,
});
store.openTaskInEditorLocation(task.id);
},
{ task, entries: longProcessEntries },
);
const stream = page.locator("[class*='_stream_']:visible");
await expect(stream.getByText("Earliest request before long runs")).toBeVisible();
await expect(stream.getByText("Split PR into three focused PRs")).toBeVisible();
await expect(stream.getByText("Interim status update")).toBeVisible();
});
+14 -14
Переглянути файл
@@ -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"]);
});
+52
Переглянути файл
@@ -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" }]);
});
+6 -1
Переглянути файл
@@ -52,8 +52,13 @@ pub async fn gh_availability(
state: State<'_, AppState>,
repo: Option<PathBuf>,
) -> IdeResult<GhAvailability> {
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)]
+4
Переглянути файл
@@ -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
@@ -316,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
+53
Переглянути файл
@@ -44,6 +44,8 @@ export const commands = {
agentCommands: (provider: string, task: string | null) => typedError<AgentCommand[], IdeError>(__TAURI_INVOKE("agent_commands", { provider, task })),
/** Reads the running session's context categories without sending a prompt. */
agentContextUsage: (task: string) => typedError<AgentContextUsage, IdeError>(__TAURI_INVOKE("agent_context_usage", { task })),
/** Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`. */
agentCopilotAuthStatus: () => typedError<CopilotAuthStatus, IdeError>(__TAURI_INVOKE("agent_copilot_auth_status")),
agentCreate: (request: NewAgentTask) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_create", { request })),
/** Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. */
agentCustomImport: (text: string) => typedError<AcpImportOutcome[], IdeError>(__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<AgentTask_Serialize, IdeError>(__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<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__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<AgentChanges, IdeError>(__TAURI_INVOKE("agent_grouped_changes", { task })),
/** Hermes Agent profiles on this machine (`default` first); empty without Hermes. */
@@ -788,6 +795,13 @@ export const commands = {
ghPrReview: (repo: string | null, number: number, event: ReviewEvent, body: string) => typedError<null, IdeError>(__TAURI_INVOKE("gh_pr_review", { repo, number, event, body })),
ghPrReviewComments: (repo: string | null, number: number) => typedError<PrReviewComment[], IdeError>(__TAURI_INVOKE("gh_pr_review_comments", { repo, number })),
ghPrView: (repo: string | null, number: number) => typedError<PullRequestDetails, IdeError>(__TAURI_INVOKE("gh_pr_view", { repo, number })),
/** Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project. */
ghProjectAccountStatus: () => typedError<GhProjectAccountStatus, IdeError>(__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<GhProjectAccountStatus, IdeError>(__TAURI_INVOKE("gh_set_project_account", { account })),
/** Forgets the credential of `key` (a `git_credentials` entry). */
gitCredentialForget: (key: string) => __TAURI_INVOKE<void>("git_credential_forget", { key }),
/** Settings › Git › Saved credentials: `scheme://host` of every saved entry. */
@@ -4994,6 +5008,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 +7707,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. */
@@ -7694,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,
@@ -7824,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,
@@ -14563,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". */
+16
Переглянути файл
@@ -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;
+300 -56
Переглянути файл
@@ -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<string | null>(null);
const [signInTarget, setSignInTarget] = useState<SignInTarget | null>(null);
const [copilotStatus, setCopilotStatus] = useState<CopilotAuthStatus | null>(null);
const [copilotStatusLoaded, setCopilotStatusLoaded] = useState(false);
const [authRevision, setAuthRevision] = useState(0);
const pendingAddAccountPrevLogins = useRef<Set<string> | null>(null);
const fetchCopilotStatus = backend.copilotAuthStatus;
const reloadCopilotStatus = useCallback(async (): Promise<CopilotAuthStatus | null> => {
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 && (
<LocalCliUpdate key={agent.program} agent={agent} backend={backend} />
)}
{(agent.loginHint || canSignInInIde) && (
{agent.id === "copilot" ? (
<Section title="Sign In">
<div className={styles.signInRow}>
{canSignInInIde && (
<Button
size="small"
variant="primary"
onClick={() => setSignInTarget({ kind: "agent", id: agent.id, name: agent.name })}
>
<T>Sign In…</T>
</Button>
)}
{agent.loginHint && (
<p className={styles.signInHint}>
<LoginHint text={agent.loginHint} />
{commandSpan && (
<IconButton
size="small"
icon="copy"
title="Copy command"
onClick={() => void copyText(commandSpan)}
/>
)}
</p>
)}
</div>
</Section>
)}
<Section title="New Tasks">
<AgentDefaults agent={agent} backend={backend} />
</Section>
<Section title="Launch">
<div className={styles.form}>
{agent.id === "copilot" && (
<div className={styles.form}>
<Row
label={<T>GitHub account</T>}
htmlFor={`agent-github-account-${agent.id}`}
hint={
<T>
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.
</T>
}
>
<Input
id={`agent-github-account-${agent.id}`}
mono
value={account.value}
disabled={account.saving}
placeholder="github-username"
onChange={(e) => account.set(e.target.value)}
/>
<div className={styles.accountField}>
<div className={styles.select}>
<Select
id={`agent-github-account-${agent.id}`}
value={account.value}
disabled={account.saving}
options={copilotAccountOptions}
onChange={(nextValue) => account.set(nextValue)}
/>
</div>
{account.value === "" && canSignInInIde && (
<Button
size="small"
variant={activeCopilotStatus && !activeCopilotStatus.authenticated ? "primary" : "secondary"}
onClick={() => {
pendingAddAccountPrevLogins.current = null;
setSignInTarget({ kind: "agent", id: agent.id, name: agent.name });
}}
>
<T>Sign In…</T>
</Button>
)}
{activeCopilotStatus?.ghInstalled && (
<Button
size="small"
onClick={() => {
pendingAddAccountPrevLogins.current = new Set(ghAccounts.map((entry) => entry.login));
setSignInTarget({ kind: "gh" });
}}
>
<T>Add account…</T>
</Button>
)}
</div>
</Row>
{activeCopilotStatus && !activeCopilotStatus.ghInstalled && (
<p className={styles.rowHint}>
<T>Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.</T>{" "}
<ExternalLink url="https://cli.github.com/" label="Download GitHub CLI…" />
</p>
)}
</div>
{!agent.installed && agent.loginHint && (
<p className={styles.signInHint}>
<LoginHint text={agent.loginHint} />
</p>
)}
</Section>
) : (
(agent.loginHint || canSignInInIde) && (
<Section title="Sign In">
<div className={styles.signInRow}>
{canSignInInIde && (
<Button
size="small"
variant="primary"
onClick={() => {
pendingAddAccountPrevLogins.current = null;
setSignInTarget({ kind: "agent", id: agent.id, name: agent.name });
}}
>
<T>Sign In…</T>
</Button>
)}
{agent.loginHint && (
<p className={styles.signInHint}>
<LoginHint text={agent.loginHint} />
{commandSpan && (
<IconButton
size="small"
icon="copy"
title="Copy command"
onClick={() => void copyText(commandSpan)}
/>
)}
</p>
)}
</div>
</Section>
)
)}
<Section title="New Tasks">
<AgentDefaults agent={agent} backend={backend} authGate={authGate} accountScope={accountScope} />
</Section>
<Section title="Launch">
<div className={styles.form}>
<Row label={<T>Command</T>}>
<code className={styles.launch} title={launch}>
{launch}
@@ -1055,19 +1181,35 @@ function ProviderSettings({
spawner={backend}
onClose={() => setSignInTarget(null)}
onCompleted={() => {
if (signInTarget.kind === "gh") {
const prev = pendingAddAccountPrevLogins.current;
pendingAddAccountPrevLogins.current = null;
void reloadCopilotStatus().then((fresh) => {
if (!prev || !fresh) return;
const added = fresh.ghAccounts.find((entry) => !prev.has(entry.login));
if (added) account.set(added.login);
});
return;
}
void refresh().catch((e: unknown) => setError(errorText(e)));
onChanged?.();
if (agent.id === "copilot") void reloadCopilotStatus();
if (backend.refreshModels) {
void backend
.refreshModels(agent.id, null, true)
.then((cat) =>
.then((cat) => {
useAgents.setState((s) => {
const modelCatalogs = new Map(s.modelCatalogs);
modelCatalogs.set(agent.id, cat);
return { modelCatalogs };
}),
)
.catch(() => {});
});
setAuthRevision((n) => n + 1);
})
.catch(() => {
setAuthRevision((n) => n + 1);
});
} else {
setAuthRevision((n) => n + 1);
}
}}
/>
@@ -1154,23 +1296,90 @@ export function defaultOptions(
}
const MODEL_SETTINGS_POLL_MS = 600;
type DefaultsAuthGate = "checking" | "unauthenticated" | "pendingApply" | "ready";
function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: CommandsBackend }) {
const isCatalogAuthError = (message: string | null | undefined): boolean =>
!!message && /sign in required|authentication|not authenticated|unauthorized|not logged in/i.test(message);
function AgentDefaults({
agent,
backend,
authGate,
accountScope,
}: {
agent: AgentProvider;
backend: CommandsBackend;
authGate: DefaultsAuthGate;
accountScope: string;
}) {
const form = useSettingsForm();
const all = (form.useValue("agents.defaults") ?? {}) as Record<string, Record<string, string>>;
const newTaskApprovals = (form.useValue("agents.newTaskApprovals") as "bypass" | "ask" | undefined) ?? "bypass";
const chosen = all[agent.id] ?? {};
const refreshModels = backend.refreshModels;
const needsAccountCatalog = agent.id === "copilot" && agent.installed && !!refreshModels;
const scopeKey = `${agent.id}:${accountScope}`;
const storeCatalog = useAgents((s) => s.modelCatalogs.get(agent.id));
const [fetchedCatalog, setFetchedCatalog] = useState<AgentModelCatalog | null>(null);
const catalog = fetchedCatalog?.provider === agent.id ? fetchedCatalog : storeCatalog;
const [accountCatalog, setAccountCatalog] = useState<{ scopeKey: string; catalog: AgentModelCatalog } | null>(null);
const [fetchedCatalog, setFetchedCatalog] = useState<{ scopeKey: string; catalog: AgentModelCatalog } | null>(null);
useEffect(() => {
if (!needsAccountCatalog || authGate !== "ready" || !refreshModels) return;
let live = true;
let timer: ReturnType<typeof setTimeout> | null = null;
const poll = async () => {
try {
const next = await refreshModels(agent.id, null);
if (!live) return;
setAccountCatalog({ scopeKey, catalog: next });
if (next.refreshing) {
timer = setTimeout(() => void poll(), MODEL_SETTINGS_POLL_MS);
}
} catch (e) {
if (!live) return;
setAccountCatalog({
scopeKey,
catalog: {
provider: agent.id,
config: [],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: null,
retryAtMs: null,
error: errorText(e),
},
});
}
};
void poll();
return () => {
live = false;
if (timer) clearTimeout(timer);
};
}, [agent.id, authGate, needsAccountCatalog, refreshModels, scopeKey]);
const scopedAccountCatalog = accountCatalog?.scopeKey === scopeKey ? accountCatalog.catalog : null;
const scopedFetchedCatalog = fetchedCatalog?.scopeKey === scopeKey ? fetchedCatalog.catalog : null;
const catalog = scopedFetchedCatalog ?? scopedAccountCatalog ?? (needsAccountCatalog ? undefined : storeCatalog);
const effectiveAgent = useMemo<AgentProvider>(() => {
if (needsAccountCatalog) {
if (!catalog || catalog.refreshedAtMs == null) {
return { ...agent, config: [], thoughtLevels: {} };
}
return {
...agent,
config: catalog.config,
thoughtLevels: catalog.thoughtLevels ?? {},
};
}
if (!catalog) return agent;
return {
...agent,
config: catalog.config.length ? catalog.config : agent.config,
thoughtLevels: { ...agent.thoughtLevels, ...catalog.thoughtLevels },
};
}, [agent, catalog]);
}, [agent, catalog, needsAccountCatalog]);
const options = defaultOptions(effectiveAgent, chosen, newTaskApprovals);
const modelOption = options.find((o) => o.category === "model");
const selectedModel = (modelOption && chosen[modelOption.id]) || modelOption?.current || null;
@@ -1178,9 +1387,10 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
!!selectedModel &&
!!modelOption?.values.some((v) => v.value === selectedModel) &&
!Object.hasOwn(effectiveAgent.thoughtLevels ?? {}, selectedModel);
const refreshModels = backend.refreshModels;
const fetchKey =
agent.installed && refreshModels && selectedModel && unknownModelSettings ? `${agent.id}:${selectedModel}` : null;
authGate === "ready" && agent.installed && refreshModels && selectedModel && unknownModelSettings
? `${scopeKey}:${selectedModel}`
: null;
const [settledKey, setSettledKey] = useState<string | null>(null);
const loadingModel = fetchKey !== null && settledKey !== fetchKey;
@@ -1192,7 +1402,7 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
try {
const next = await refreshModels(agent.id, selectedModel);
if (!live) return;
setFetchedCatalog(next);
setFetchedCatalog({ scopeKey, catalog: next });
if (next.refreshing && !Object.hasOwn(next.thoughtLevels ?? {}, selectedModel)) {
timer = setTimeout(() => void poll(), MODEL_SETTINGS_POLL_MS);
} else {
@@ -1207,8 +1417,42 @@ function AgentDefaults({ agent, backend }: { agent: AgentProvider; backend: Comm
live = false;
if (timer) clearTimeout(timer);
};
}, [agent.id, fetchKey, refreshModels, selectedModel]);
}, [agent.id, fetchKey, refreshModels, scopeKey, selectedModel]);
if (authGate === "checking") {
return (
<p className={styles.statusNote}>
<Spinner size={12} /> <T>Checking sign-in status…</T>
</p>
);
}
if (authGate === "unauthenticated" || isCatalogAuthError(catalog?.error)) {
return (
<p className={styles.text}>
<T>Sign in above to view and choose models available for this account.</T>
</p>
);
}
if (authGate === "pendingApply") {
return (
<p className={styles.text}>
<T>Click Apply to load the models available for the selected account.</T>
</p>
);
}
if (
needsAccountCatalog &&
(!scopedAccountCatalog || (scopedAccountCatalog.refreshing && scopedAccountCatalog.refreshedAtMs == null))
) {
return (
<p className={styles.statusNote}>
<Spinner size={12} /> <T>Loading models for this account…</T>
</p>
);
}
if (needsAccountCatalog && scopedAccountCatalog?.refreshedAtMs == null && scopedAccountCatalog?.error) {
return <p className={styles.error}>{scopedAccountCatalog.error}</p>;
}
if (!options.length)
return (
<p className={styles.text}>
+18 -12
Переглянути файл
@@ -1,6 +1,7 @@
/**
* Interactive sign-in dialog for coding agents (`copilot login`, `codex login`, `claude`, …),
* backed by an IDE-managed PTY (`agent_login_spawn`) and a lazily loaded embedded terminal widget.
* Interactive sign-in dialog for coding agents (`copilot login`, `codex login`, `claude`, …)
* and GitHub CLI (`gh auth login`), backed by an IDE-managed PTY (`agent_login_spawn` /
* `agent_gh_login_spawn`) and a lazily loaded embedded terminal widget.
*/
import { useEffect, useRef, useState } from "react";
import type { AgentLoginEvent, TerminalId } from "@/bindings";
@@ -11,10 +12,11 @@ import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributio
import styles from "./AgentSignInDialog.module.css";
import { tauriCommands } from "./registry";
export type SignInTarget = { kind: "agent"; id: string; name: string };
export type SignInTarget = { kind: "agent"; id: string; name: string } | { kind: "gh" };
export interface SignInSpawner {
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
}
export function AgentSignInDialog({
@@ -40,7 +42,8 @@ export function AgentSignInDialog({
const [exitCode, setExitCode] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const agentId = target.id;
const targetKind = target.kind;
const agentId = target.kind === "agent" ? target.id : "";
useEffect(() => {
const el = hostRef.current;
@@ -108,12 +111,15 @@ export function AgentSignInDialog({
try {
const custom = callbacksRef.current.spawner;
const ptyId = await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
agentId,
pendingSize.cols,
pendingSize.rows,
onEvent,
);
const ptyId =
targetKind === "gh"
? await (custom?.ghLoginSpawn ?? tauriCommands.ghLoginSpawn!)(pendingSize.cols, pendingSize.rows, onEvent)
: await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
agentId,
pendingSize.cols,
pendingSize.rows,
onEvent,
);
if (disposed) {
void commands.termKill(ptyId).catch(() => {});
return;
@@ -131,10 +137,10 @@ export function AgentSignInDialog({
killPty();
term?.dispose();
};
}, [agentId, attempt]);
}, [agentId, attempt, targetKind]);
const running = exitCode === null && !error;
const title = tx`Sign In to ${target.name}`;
const title = target.kind === "gh" ? tx("Sign In to GitHub CLI") : tx`Sign In to ${target.name}`;
const finishAndClose = () => {
const id = ptyIdRef.current;
+161 -5
Переглянути файл
@@ -5,6 +5,7 @@ import type {
AgentLoginEvent,
AgentProvider,
AgentRegistry,
CopilotAuthStatus,
InstallEvent,
RegistryAgent,
RequestId,
@@ -420,7 +421,9 @@ class FakeCommands implements CommandsBackend {
list: AgentProvider[] = [];
saved: [string, string | null][] = [];
providers = vi.fn(async () => this.list);
copilotAuthStatus?: () => Promise<CopilotAuthStatus>;
loginSpawn?: CommandsBackend["loginSpawn"];
ghLoginSpawn?: CommandsBackend["ghLoginSpawn"];
refreshModels?: CommandsBackend["refreshModels"];
chooseExecutable = vi.fn(async () => "/chosen/agent");
saveCustom = vi.fn(async () => {});
@@ -611,8 +614,19 @@ describe("Built-in executable overrides", () => {
expect(commands.savedEnv.at(-1)).toEqual(["claude", {}]);
});
it("writes a Copilot GitHub account without storing a token or exposing the control variable", async () => {
it("writes a Copilot GitHub account from the dropdown without storing a token or exposing the control variable", async () => {
const commands = new FakeCommands();
commands.copilotAuthStatus = vi.fn(async () => ({
authenticated: true,
login: "alice",
authType: "gh-cli",
statusMessage: "alice (via gh)",
ghInstalled: true,
ghAccounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
}));
commands.list = [
{
...claudeProvider("copilot"),
@@ -625,9 +639,16 @@ describe("Built-in executable overrides", () => {
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
const account = screen.getByRole("textbox", { name: "GitHub account" });
const signInSection = screen.getByRole("region", { name: "Sign In" });
const launchSection = screen.getByRole("region", { name: "Launch" });
const account = await within(signInSection).findByRole("button", { name: "GitHub account" });
expect(within(launchSection).queryByRole("button", { name: "GitHub account" })).toBeNull();
await waitFor(() => expect(account).toHaveTextContent("Copilot CLI default (alice via GitHub CLI)"));
expect(screen.queryByRole("textbox", { name: "Environment variables" })).toBeNull();
fireEvent.change(account, { target: { value: "dengliu_microsoft" } });
fireEvent.click(account);
fireEvent.click(await screen.findByRole("option", { name: "alice-work" }));
expect(account).toHaveTextContent("alice-work");
expect(screen.getByText("Click Apply to load the models available for the selected account.")).toBeInTheDocument();
await act(async () => fireEvent.click(apply()));
@@ -636,14 +657,102 @@ describe("Built-in executable overrides", () => {
"copilot",
{
COPILOT_TELEMETRY_OPTOUT: "1",
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "dengliu_microsoft",
OPENIDEA_COPILOT_GITHUB_ACCOUNT: "alice-work",
},
],
]);
expect(JSON.stringify(commands.savedEnv)).not.toMatch(/gho_|ghp_|token/i);
});
it("runs in-IDE Sign In PTY dialog and refreshes the agent's model catalog on exit", async () => {
it("hides stale Copilot models until authenticated and reloads per-account models after Apply", async () => {
const staleModel: AgentProvider["config"][number] = {
id: "model",
name: "Model",
description: null,
category: "model",
current: "gemini-4-neon",
values: [
{ value: "gemini-4-neon", name: "Gemini 4 Neon", description: null },
{ value: "gpt-5", name: "GPT-5", description: null },
],
via: "option",
};
const personalModel: AgentProvider["config"][number] = {
id: "model",
name: "Model",
description: null,
category: "model",
current: "claude-sonnet-4.5",
values: [
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
{ value: "gpt-5", name: "GPT-5", description: null },
],
via: "option",
};
const commands = new FakeCommands();
commands.copilotAuthStatus = vi.fn(async () => ({
authenticated: false,
login: null,
authType: null,
statusMessage: null,
ghInstalled: true,
ghAccounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
}));
commands.refreshModels = vi.fn(async () => {
const currentAccount = commands.list[0]?.env.OPENIDEA_COPILOT_GITHUB_ACCOUNT ?? "";
return {
provider: "copilot",
config: [currentAccount === "alice-work" ? staleModel : personalModel],
thoughtLevels: {},
refreshing: false,
refreshedAtMs: Date.now(),
retryAtMs: null,
error: null,
};
});
commands.list = [
{
...claudeProvider("copilot"),
id: "copilot",
name: "GitHub Copilot",
command: "copilot --headless --no-auto-update --stdio",
defaultProgram: "copilot",
installed: true,
canSignIn: true,
commandReadOnlyReason: "registry",
config: [staleModel],
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
// Signed-out default account never leaks cached models from a previous session/account.
await screen.findByText("Sign in above to view and choose models available for this account.");
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
// Selecting `alice` stages the switch and asks for Apply before showing models.
const account = screen.getByRole("button", { name: "GitHub account" });
fireEvent.click(account);
fireEvent.click(await screen.findByRole("option", { name: "alice" }));
expect(screen.getByText("Click Apply to load the models available for the selected account.")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
// Applying loads `alice`'s subscription models.
await act(async () => fireEvent.click(apply()));
const modelButton = await screen.findByRole("button", { name: "Model" });
expect(modelButton).toHaveTextContent("Agent's default (Claude Sonnet 4.5)");
// Switching to `alice-work` and applying loads its own subscription models.
fireEvent.click(screen.getByRole("button", { name: "GitHub account" }));
fireEvent.click(await screen.findByRole("option", { name: "alice-work" }));
expect(screen.queryByRole("button", { name: "Model" })).toBeNull();
await act(async () => fireEvent.click(apply()));
expect(await screen.findByRole("button", { name: "Model" })).toHaveTextContent("Agent's default (Gemini 4 Neon)");
});
it("runs in-IDE Sign In and Add account PTY dialogs and selects the newly added gh account", async () => {
const written: string[] = [];
provideEmbeddedTerminal(async () => ({
write: (d) => written.push(d),
@@ -659,6 +768,10 @@ describe("Built-in executable overrides", () => {
onLoginEvent = cb;
return 101;
});
commands.ghLoginSpawn = vi.fn(async (_cols, _rows, cb) => {
onLoginEvent = cb;
return 102;
});
const refreshModels = vi.fn().mockResolvedValue({
provider: "copilot",
config: [],
@@ -669,6 +782,35 @@ describe("Built-in executable overrides", () => {
error: null,
});
commands.refreshModels = refreshModels;
commands.copilotAuthStatus = vi
.fn<() => Promise<CopilotAuthStatus>>()
.mockResolvedValueOnce({
authenticated: false,
login: null,
authType: null,
statusMessage: null,
ghInstalled: true,
ghAccounts: [{ login: "alice", active: true }],
})
.mockResolvedValueOnce({
authenticated: true,
login: "alice",
authType: "oauth",
statusMessage: "alice",
ghInstalled: true,
ghAccounts: [{ login: "alice", active: true }],
})
.mockResolvedValueOnce({
authenticated: true,
login: "alice",
authType: "oauth",
statusMessage: "alice",
ghInstalled: true,
ghAccounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
});
commands.list = [
{
...claudeProvider("copilot"),
@@ -683,6 +825,8 @@ describe("Built-in executable overrides", () => {
},
];
await openCommands(commands, vi.fn(), "GitHub Copilot");
// 1) Agent Sign In dialog (`copilot login`)
fireEvent.click(await screen.findByRole("button", { name: "Sign In…" }));
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeInTheDocument();
await waitFor(() =>
@@ -700,6 +844,18 @@ describe("Built-in executable overrides", () => {
expect(written).toContain("Opening browser…\r\n");
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeNull());
expect(refreshModels).toHaveBeenCalledWith("copilot", null, true);
// 2) Add GitHub CLI account (`gh auth login`) auto-selects newly added account
fireEvent.click(await screen.findByRole("button", { name: "Add account…" }));
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeInTheDocument();
await waitFor(() => expect(commands.ghLoginSpawn).toHaveBeenCalled());
act(() => {
onLoginEvent?.({ type: "exited", code: 0 });
});
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Sign In to GitHub CLI" })).toBeNull());
await waitFor(() =>
expect(screen.getByRole("button", { name: "GitHub account" })).toHaveTextContent("alice-work"),
);
} finally {
provideEmbeddedTerminal(undefined);
}
+85
Переглянути файл
@@ -255,4 +255,89 @@ describe("a kept-alive session tab that stays hidden", { timeout: 30_000 }, () =
// The one request in the trimmed part of the history is found.
expect(await screen.findByText("1/1", {}, { timeout: 10_000 })).toBeInTheDocument();
});
it("paints earlier messages past folded process runs longer than ENTRY_BATCH on open and after hiding", async () => {
const toolCalls = (prefix: string, count: number): AgentEntry[] =>
Array.from({ length: count }, (_, k): AgentEntry => ({
type: "tool",
id: `${prefix}-${k}`,
title: `Read src/file${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
}));
const longRuns: AgentEntry[] = [
...history(5),
{ type: "user", text: "Split the PR", attachments: [], sentMs: null },
...toolCalls("first-run", 75),
{ type: "agent", text: "Interim update" },
...toolCalls("second-run", 75),
];
useAgents.setState({
tasks: new Map([[task("A").id, { ...task("A"), status: "running" }]]),
entries: new Map([["A", longRuns]]),
});
const view = render(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
vi.useRealTimers();
view.rerender(session(true));
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Split the PR")).toBeInTheDocument();
});
it("loads earlier messages past a long process run when scrolled to the top with stick disabled", async () => {
const longRun: AgentEntry[] = [
...history(3),
{ type: "user", text: "Prompt before long run", attachments: [], sentMs: null },
...Array.from({ length: 75 }, (_, k): AgentEntry => ({
type: "tool",
id: `top-run-${k}`,
title: `Read src/mod${k}.ts`,
kind: "read",
status: "completed",
locations: [],
output: null,
diffs: [],
})),
{ type: "agent", text: "Tail reply" },
];
useAgents.setState({ entries: new Map([["A", longRun]]) });
// Suppress background auto-follow after initial render by scrolling away before history finishes.
const view = render(session(true));
await settle("Tail reply");
vi.useFakeTimers();
view.rerender(session(false));
await act(async () => {
await vi.advanceTimersByTimeAsync(LONG_HIDDEN_MS);
});
expect(screen.queryByText("Request 0")).toBeNull();
// User switches back while holding pointer down, then scrolls to the top (`stick: false`).
fireEvent.pointerDown(stream());
view.rerender(session(true));
const el = stream();
layOut(el);
fireEvent.wheel(el, { deltaY: -120 });
el.scrollTop = 0;
fireEvent.scroll(el);
fireEvent.pointerUp(window);
await act(async () => {
await vi.advanceTimersByTimeAsync(2_000);
});
vi.useRealTimers();
expect(await screen.findByText("Request 0", {}, { timeout: 3_000 })).toBeInTheDocument();
expect(screen.getByText("Prompt before long run")).toBeInTheDocument();
});
});
+10
Переглянути файл
@@ -11,6 +11,7 @@ import type {
AgentModelCatalog,
AgentProvider,
AgentRegistry,
CopilotAuthStatus,
CustomAgentInput,
InstallEvent,
RegistryAgent,
@@ -34,7 +35,9 @@ export interface CommandsBackend {
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
cancel(request: RequestId): void;
providers(): Promise<AgentProvider[]>;
copilotAuthStatus?(): Promise<CopilotAuthStatus>;
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
ghLoginSpawn?(cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
refreshModels?(id: string, model: string | null, force?: boolean): Promise<AgentModelCatalog>;
set(id: string, command: string | null): Promise<void>;
setAdditionalArgs(id: string, args: string[]): Promise<void>;
@@ -64,12 +67,19 @@ export const tauriCommands: CommandsBackend = {
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
cancel: tauriRegistry.cancel,
providers: () => call(commands.agentProviders()),
copilotAuthStatus: () => call(commands.agentCopilotAuthStatus()),
loginSpawn: async (id, cols, rows, onEvent) => {
const channel = new Channel<AgentLoginEvent>();
channel.onmessage = onEvent;
const info = await call(commands.agentLoginSpawn(id, cols, rows, channel));
return info.id;
},
ghLoginSpawn: async (cols, rows, onEvent) => {
const channel = new Channel<AgentLoginEvent>();
channel.onmessage = onEvent;
const info = await call(commands.agentGhLoginSpawn(cols, rows, channel));
return info.id;
},
refreshModels: (id, model, force = false) => call(commands.agentRefreshModels(id, force, model)),
chooseExecutable: async (title, current, location) => {
if (location !== "desktop") return choosePath({ title, defaultPath: current, directory: false });
+52 -15
Переглянути файл
@@ -212,6 +212,24 @@ function clampMultiClick(target: EventTarget) {
if (row) clampSelectionToRow(document.getSelection(), row);
}
/** First entry index painted for a `shown` tail cap, keeping a leading process run intact. */
function historyStart(entries: readonly AgentEntry[], shown: number): number {
let start = Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
return start;
}
/**
* Next `shown` cap after one batch. Keeping a process run intact can already paint more than
* `shown` entries, so step past what is actually painted (`entries.length - start`) rather than
* `shown`; otherwise a process run longer than `ENTRY_BATCH` leaves `start` unchanged and stalls.
*/
function nextShownBatch(entries: readonly AgentEntry[] | null, shown: number): number {
if (!entries) return shown + ENTRY_BATCH;
return Math.max(shown, entries.length - historyStart(entries, shown)) + ENTRY_BATCH;
}
export function Stream({
loadError,
task,
@@ -239,9 +257,11 @@ export function Stream({
// Opened at the end, the last entries come first and the earlier ones follow in batches:
// reopening a long conversation paints at once. A kept offset needs them all.
const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH));
let start = finding || !entries ? 0 : Math.max(0, entries.length - shown);
// Keep a process run intact so prepending never replaces the anchored row.
while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--;
const start = finding || !entries ? 0 : historyStart(entries, shown);
const latest = useRef({ entries, start, visible });
useLayoutEffect(() => {
latest.current = { entries, start, visible };
});
const dragging = useRef(false);
// When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find):
// that leaves the end. WebKit also moves the offset back on its own while rows lay out,
@@ -280,11 +300,12 @@ export function Stream({
const anchor = useRef<{ el: Element; top: number } | null>(null);
const loadEarlier = useCallback(() => {
const el = ref.current;
if (!visible || !el || start <= 0 || dragging.current || anchor.current) return;
const { start: currentStart, visible: isVisible } = latest.current;
if (!isVisible || !el || currentStart <= 0 || dragging.current || anchor.current) return;
const first = el.firstElementChild;
if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top };
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
}, []);
const loadTimer = useRef<number | null>(null);
/** Load the next batch once the user stops scrolling near the top. */
const loadWhenStill = useCallback(() => {
@@ -298,12 +319,19 @@ export function Stream({
const down = (event: PointerEvent) => {
if (!ref.current?.contains(event.target as Node)) return;
dragging.current = true;
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
const up = () => {
if (!dragging.current) return;
dragging.current = false;
if (ref.current && (position.current.stick || ref.current.scrollTop < 120)) loadWhenStill();
if (
ref.current &&
(position.current.stick || ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)
)
loadWhenStill();
};
window.addEventListener("pointerdown", down, true);
window.addEventListener("pointerup", up, true);
@@ -314,16 +342,24 @@ export function Stream({
window.removeEventListener("pointerup", up, true);
window.removeEventListener("pointercancel", up, true);
window.removeEventListener("blur", up);
if (loadTimer.current !== null) window.clearTimeout(loadTimer.current);
if (loadTimer.current !== null) {
window.clearTimeout(loadTimer.current);
loadTimer.current = null;
}
};
}, [loadWhenStill]);
useEffect(() => {
// Following the end, paint the rest in the background. A user who scrolled away
// gets them only after stopping near the top (`loadWhenStill`), so the scrollbar
// is not resized mid-drag. A hidden tab paints nothing more.
if (visible && start > 0 && position.current.stick && !dragging.current)
startTransition(() => setShown((n) => n + ENTRY_BATCH));
}, [start, visible]);
// gets them only after stopping near the top (`loadWhenStill`), or when folded rows
// do not yet fill the viewport, so the scrollbar is not resized mid-drag. A hidden
// tab paints nothing more.
if (!visible || start <= 0 || dragging.current) return;
if (position.current.stick) {
startTransition(() => setShown((n) => nextShownBatch(latest.current.entries, n)));
} else if (ref.current && (ref.current.scrollHeight <= ref.current.clientHeight || ref.current.scrollTop < 120)) {
loadWhenStill();
}
}, [loadWhenStill, start, visible]);
useEffect(() => {
// A conversation read to its end gives back the history painted above its recent entries
// once it stays behind other tabs: a few kept-alive tabs would otherwise hold every turn
@@ -418,6 +454,7 @@ export function Stream({
const observer = new ResizeObserver(() => {
trimSlack();
if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight;
else if (!position.current.stick && el.scrollHeight <= el.clientHeight && !dragging.current) loadWhenStill();
updateJumpVisibility(el);
});
observer.observe(el);
@@ -425,7 +462,7 @@ export function Stream({
observer.disconnect();
if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop });
};
}, [key, positions, trimSlack, updateJumpVisibility]);
}, [key, loadWhenStill, positions, trimSlack, updateJumpVisibility]);
/**
* The wheel scrolls the innermost container under the pointer, and only that one: a run of
* calls from its headers, a tool output from its text, the conversation elsewhere. A container
+79
Переглянути файл
@@ -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<GhProjectAccountState>(() => ({
status: null,
loading: false,
saving: false,
revision: 0,
}));
export async function loadProjectGithubAccount(): Promise<GhProjectAccountStatus | null> {
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<GhProjectAccountStatus | null> {
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 }]
: []),
];
}
+6 -1
Переглянути файл
@@ -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 },
+75 -8
Переглянути файл
@@ -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 (
<div className={styles.page}>
<Checkbox
checked={autoMarkViewed}
onChange={(v) => setReviewDiffSettings({ autoMarkViewed: v })}
label="Automatically mark opened files as viewed"
/>
<section className={styles.section} aria-labelledby={accountHeading}>
<h2 id={accountHeading} className={styles.heading}>
<T>Account</T>
</h2>
<div className={styles.accountRow}>
<label htmlFor={selectId} className={styles.accountLabel}>
<T>GitHub account</T>:
</label>
<div className={styles.accountControl}>
<div className={styles.accountField}>
<div className={styles.accountSelect}>
<Select
id={selectId}
aria-label="GitHub account"
value={value}
disabled={saving}
options={options}
onChange={(next) => void setProjectGithubAccount(next)}
/>
</div>
{suggested && (
<Button size="small" disabled={saving} onClick={() => void setProjectGithubAccount(suggested)}>
{tx`Use ${suggested} for this project`}
</Button>
)}
</div>
<p className={styles.accountHint}>
{value ? (
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
) : (
<T>Uses GitHub CLI&apos;s active account without setting GH_TOKEN in the project environment.</T>
)}
</p>
</div>
</div>
</section>
<section className={styles.section} aria-labelledby={prHeading}>
<h2 id={prHeading} className={styles.heading}>
<T>Pull Requests</T>
</h2>
<Checkbox
checked={autoMarkViewed}
onChange={(v) => setReviewDiffSettings({ autoMarkViewed: v })}
label="Automatically mark opened files as viewed"
/>
</section>
</div>
);
}
+64 -1
Переглянути файл
@@ -29,6 +29,69 @@
.page {
display: flex;
flex-direction: column;
gap: var(--space-2);
gap: var(--space-4);
padding: 4px 0;
}
.section {
display: flex;
flex-direction: column;
gap: var(--space-2);
}
.heading {
margin: 0;
padding-bottom: 4px;
border-bottom: 1px solid var(--border);
color: var(--fg-strong);
font-size: var(--fs-ui);
font-weight: 600;
}
.accountRow {
display: grid;
grid-template-columns: max-content minmax(0, 1fr);
align-items: start;
column-gap: var(--space-3);
row-gap: var(--space-1);
}
.accountLabel {
line-height: var(--h-field);
color: var(--fg);
white-space: nowrap;
}
.accountControl {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-width: 0;
}
.accountField {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.accountSelect {
display: flex;
width: 280px;
max-width: 100%;
min-width: 0;
}
.accountSelect > button {
flex: 1;
min-width: 0;
}
.accountHint {
margin: 0;
max-width: 480px;
color: var(--fg-subtle);
font-size: var(--fs-small);
}
+22 -3
Переглянути файл
@@ -8,7 +8,8 @@ import { getContext, setContext } from "@/platform/context";
import { useProject } from "@/platform/project";
import { maybeEditorService, type EditorInput } from "@/workbench/contributions";
import { activateReviewDiff, toggleReviewDiffViewed } from "./diff";
import { reloadList } from "./data/list";
import { loadProjectGithubAccount, useGhProjectAccount } from "./data/account";
import { reloadList, useGhPrList } from "./data/list";
import { checkoutPullRequest, clearDiffCache, copyUrl, openInBrowser, openInWorktree } from "./data/local";
import { deleteMergedBranch } from "./data/operations";
import { cachedDetails, loadPullRequestData, reloadPullRequest } from "./data/pullRequest";
@@ -99,9 +100,10 @@ export const timeline = {
export function activate(): () => void {
const sync = () => {
const s = useGhRepository.getState();
const acct = useGhProjectAccount.getState().status;
setContext("githubConnected", !!s.connection);
setContext("githubTimelineActive", activeTimelinePullRequest() !== null);
useGithubShell.setState({ headerMenu: headerMenu(s) });
useGithubShell.setState({ headerMenu: headerMenu(s, acct) });
};
sync();
const disposers = [
@@ -112,10 +114,27 @@ export function activate(): () => void {
if (a?.owner !== b?.owner || a?.name !== b?.name) {
resetTabs();
clearDiffCache();
} else if (
s.connection &&
prev.connection &&
s.connection.currentUser.login !== prev.connection.currentUser.login &&
useGhPrList.getState().loaded
) {
void reloadList();
}
}),
useGhProjectAccount.subscribe((s, prev) => {
sync();
if (s.revision !== prev.revision) {
void refreshConnection();
}
}),
useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) resetConnection();
if (s.project?.root !== prev.project?.root) {
useGhProjectAccount.setState({ status: null, loading: false, saving: false });
resetConnection();
if (s.project) void loadProjectGithubAccount();
}
}),
activateReviewDiff(),
activateReviewMode(),
+37 -1
Переглянути файл
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { useSettingsPages } from "@/workbench/contributions";
import { useGhProjectAccount } from "./data/account";
import { activateSettingsPages } from "./settingsPages";
import { GithubSettingsPage } from "./diff/GithubSettingsPage";
import { setReviewDiffSettings, useReviewDiffSettings } from "./diff/settings";
@@ -10,6 +11,11 @@ const KEY = "openidea.github.reviewDiff.v1";
beforeEach(() => {
localStorage.removeItem(KEY);
window.dispatchEvent(new StorageEvent("storage", { key: KEY }));
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
});
afterEach(() => {
useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 });
});
describe("GitHub settings pages", () => {
@@ -49,4 +55,34 @@ describe("GitHub settings pages", () => {
window.dispatchEvent(new StorageEvent("storage", { key: KEY }));
expect(useReviewDiffSettings.getState().autoMarkViewed).toBe(false);
});
it("suggests a matching non-active GitHub account and shows the GH_TOKEN scope note once chosen", () => {
useGhProjectAccount.setState({
status: {
ghInstalled: true,
accounts: [
{ login: "alice", active: true },
{ login: "alice-work", active: false },
],
configuredAccount: "",
effectiveAccount: "alice",
suggestedAccount: "alice-work",
},
});
render(<GithubSettingsPage />);
const select = screen.getByRole("button", { name: "GitHub account" });
expect(select).toHaveTextContent("Automatic (alice)");
expect(
screen.getByText("Uses GitHub CLI's active account without setting GH_TOKEN in the project environment."),
).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Use alice-work for this project" }));
expect(screen.getByRole("button", { name: "GitHub account" })).toHaveTextContent("alice-work");
expect(useGhProjectAccount.getState().status?.configuredAccount).toBe("alice-work");
expect(
screen.getByText(
"Passes this account's GH_TOKEN to processes started in this project (terminals, agents, Git, and run configurations).",
),
).toBeInTheDocument();
});
});
+1 -1
Переглянути файл
@@ -6,7 +6,7 @@ export function activateSettingsPages(): () => void {
id: "vcs.github",
title: "GitHub",
order: 9,
keywords: ["pull request", "viewed", "review"],
keywords: ["pull request", "viewed", "review", "account", "gh", "token"],
component: lazyComponent(() => import("./diff/GithubSettingsPage").then((m) => m.GithubSettingsPage)),
});
}
+147 -8
Переглянути файл
@@ -5,6 +5,7 @@
* the repository, `#N` tabs and "New Pull Request at {repo}" — in the header.
*/
import { useEffect, useRef, useState, type RefObject } from "react";
import type { GhProjectAccountStatus } from "@/bindings";
import type { GhAvailability } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
@@ -14,6 +15,12 @@ import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMe
import { CreatePanel } from "../create/CreatePanel";
import { DetailsPanel } from "../details/DetailsPanel";
import { ListPanel } from "../list/ListPanel";
import {
loadProjectGithubAccount,
projectAccountOptions,
setProjectGithubAccount,
useGhProjectAccount,
} from "../data/account";
import { reloadList, useGhPrList } from "../data/list";
import { cancelBusy, openInBrowser, useGhBusy } from "../data/local";
import { repositoryDisplayName } from "../data/model";
@@ -29,6 +36,42 @@ import {
import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
import styles from "./ToolWindow.module.css";
function ProjectAccountInline() {
const status = useGhProjectAccount((s) => s.status);
const saving = useGhProjectAccount((s) => s.saving);
if (!status || status.accounts.length === 0) return null;
const suggested = !status.configuredAccount ? status.suggestedAccount : null;
return (
<div className={styles.accountInline}>
{suggested && (
<Button
size="small"
variant="primary"
disabled={saving}
onClick={() => void setProjectGithubAccount(suggested)}
>
{tx`Use ${suggested} for this project`}
</Button>
)}
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={saving}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and run
configurations).
</T>
</div>
)}
</div>
);
}
function Unavailable({ availability }: { availability: GhAvailability }) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
@@ -101,6 +144,7 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
}
>
<T>Run</T> <code>gh auth login</code> <T>in a terminal, then retry.</T>
<ProjectAccountInline />
</EmptyState>
);
case "notGitHub":
@@ -115,7 +159,8 @@ function Unavailable({ availability }: { availability: GhAvailability }) {
case "error":
return (
<EmptyState title="Could not reach GitHub" actions={retry}>
{availability.message}
<div>{availability.message}</div>
<ProjectAccountInline />
</EmptyState>
);
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<string | null>(null);
const value =
chosen ??
@@ -136,6 +183,36 @@ function RepositorySelector() {
const target = remotes.find((r) => nameWithOwner(r) === value);
return (
<div className={styles.selector}>
{status && status.accounts.length > 0 && (
<>
<div className={styles.selectorRow}>
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={savingAccount}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
{!status.configuredAccount && status.suggestedAccount && (
<Button
size="small"
disabled={savingAccount}
onClick={() => void setProjectGithubAccount(status.suggestedAccount!)}
>
{tx`Use ${status.suggestedAccount} for this project`}
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
</div>
)}
</>
)}
<div className={styles.selectorRow}>
<Select
value={value}
@@ -231,6 +308,7 @@ export function PullRequestsToolWindow() {
const connected = useGhRepository((s) => !!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 && (
<button
type="button"
className={styles.accountBadge}
title={suggested ? tx`Use ${suggested} for this project` : tx`GitHub account: @${activeLogin}`}
onClick={(e) => {
const configured = status.configuredAccount;
const defaultLogin = status.accounts.find((a) => a.active)?.login ?? null;
const autoLabel = defaultLogin ? tx`Automatic (${defaultLogin})` : tx("Automatic");
const items: MenuItem[] = [
...(suggested
? [
{
label: tx`Use ${suggested} for this project`,
verbatim: true,
run: () => void setProjectGithubAccount(suggested),
},
{ kind: "separator" as const },
]
: []),
{
label: autoLabel,
verbatim: true,
checked: configured === "",
run: () => void setProjectGithubAccount(""),
},
...status.accounts.map((a) => ({
label: `@${a.login}`,
verbatim: true,
checked: configured === a.login,
run: () => void setProjectGithubAccount(a.login),
})),
];
showContextMenu(e, items);
}}
>
@{activeLogin}
</button>
)}
<IconButton icon="plus" size="small" iconSize={16} action="github.createPullRequest" />
<IconButton icon="locate" size="small" iconSize={16} action="github.selectOpenedPullRequest" />
</>
);
}
/** The "⋮" menu's own items: Change Repository or Account… (connected, several GitHub remotes). */
export function headerMenu(s: Pick<ReturnType<typeof useGhRepository.getState>, "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<ReturnType<typeof useGhRepository.getState>, "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[] = [];
+28
Переглянути файл
@@ -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 {
+45 -1
Переглянути файл
@@ -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(<PullRequestsHeaderActions />);
const badge = screen.getByRole("button", { name: "@alice" });
expect(badge).toHaveAttribute("title", "Use alice-work for this project");
});
});
+21 -3
Переглянути файл
@@ -3675,8 +3675,6 @@
"Branch '{branchName}' is already the current branch": "Branch '{branchName}' is already the current branch",
"Checkout '{name}'": "Checkout '{name}'",
"GitHub account": "GitHub account",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.",
"github-username": "github-username",
"Find actions": "Find actions",
"Resize find preview": "Resize find preview",
"Caret": "Caret",
@@ -4187,5 +4185,25 @@
"Install GitHub CLI": "Install GitHub CLI",
"Download manually…": "Download manually…",
"Show Scratches and Consoles": "Show Scratches and Consoles",
"The terminal is not available in this window.": "The terminal is not available in this window."
"The terminal is not available in this window.": "The terminal is not available in this window.",
"{value} (not signed in)": "{value} (not signed in)",
"Add account…": "Add account…",
"Sign In to GitHub CLI": "Sign In to GitHub CLI",
"Copilot CLI default ({login} via GitHub CLI)": "Copilot CLI default ({login} via GitHub CLI)",
"Copilot CLI default ({login})": "Copilot CLI default ({login})",
"Copilot CLI default (not signed in)": "Copilot CLI default (not signed in)",
"Copilot CLI default": "Copilot CLI default",
"GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch and never stored.": "GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch and never stored.",
"Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.": "Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.",
"Download GitHub CLI…": "Download GitHub CLI…",
"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…",
"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)."
}
-2
Переглянути файл
@@ -9792,8 +9792,6 @@
"Unshelve Silently": "Восстановить без подтверждения",
"Remove All Watches": "Удалить все контрольные выражения",
"GitHub account": "Аккаунт GitHub",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Оставьте пустым, чтобы использовать активный аккаунт GitHub CLI. OpenIDEA определяет токен при запуске и никогда не сохраняет его.",
"github-username": "имя-пользователя-github",
"Change File Encoding": "Изменить кодировку файла",
"Convert": "Преобразовать",
"Use {label} for this file?": "Использовать {label} для этого файла?",
-2
Переглянути файл
@@ -2760,8 +2760,6 @@
"Pause Output": "Çıktıyı Duraklat",
"Remove All Watches": "İzlenen Tüm İfadeleri Kaldır",
"GitHub account": "GitHub hesabı",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "Etkin GitHub CLI hesabını kullanmak için boş bırakın. OpenIDEA tokeni başlatma sırasında çözümler ve saklamaz.",
"github-username": "github-username",
"Find actions": "Eylemleri bul",
"Resize find preview": "Arama önizlemesini yeniden boyutlandır",
"Caret": "İmleç",
-2
Переглянути файл
@@ -9200,8 +9200,6 @@
"Unshelve Silently": "靜默取消擱置",
"Remove All Watches": "移除所有監視",
"GitHub account": "GitHub 帳號",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空則使用 GitHub CLI 目前登入的帳號。OpenIDEA 在啟動時取得令牌,不會儲存它。",
"github-username": "GitHub 使用者名稱",
"Change File Encoding": "更改檔案編碼",
"Convert": "轉換",
"Use {label} for this file?": "對此檔案使用 {label} 編碼?",
+21 -3
Переглянути файл
@@ -10058,8 +10058,6 @@
"Unshelve Silently": "静默取消搁置",
"Remove All Watches": "移除所有监视",
"GitHub account": "GitHub 账号",
"Leave empty to use the active GitHub CLI account. OpenIDEA resolves the token at launch and never stores it.": "留空则使用 GitHub CLI 当前登录的账号。OpenIDEA 在启动时获取令牌,不会保存它。",
"github-username": "GitHub 用户名",
"Change File Encoding": "更改文件编码",
"Convert": "转换",
"Use {label} for this file?": "对此文件使用 {label} 编码?",
@@ -10635,5 +10633,25 @@
"Install GitHub CLI": "安装 GitHub CLI",
"Download manually…": "手动下载…",
"Show Scratches and Consoles": "显示临时文件和控制台",
"The terminal is not available in this window.": "此窗口中无法使用终端。"
"The terminal is not available in this window.": "此窗口中无法使用终端。",
"{value} (not signed in)": "{value}(未登录)",
"Add account…": "添加账户…",
"Sign In to GitHub CLI": "登录 GitHub CLI",
"Copilot CLI default ({login} via GitHub CLI)": "Copilot CLI 默认(通过 GitHub CLI:{login})",
"Copilot CLI default ({login})": "Copilot CLI 默认({login})",
"Copilot CLI default (not signed in)": "Copilot CLI 默认(未登录)",
"Copilot CLI default": "Copilot CLI 默认",
"GitHub account whose Copilot subscription is used for AI model requests. Tokens are resolved at launch and never stored.": "用于 AI 模型请求的 Copilot 订阅所属 GitHub 账户。令牌在启动时解析,从不存储。",
"Install GitHub CLI (`gh`) to switch between multiple GitHub accounts.": "安装 GitHub CLI(`gh`)以在多个 GitHub 账户之间切换。",
"Download GitHub CLI…": "下载 GitHub CLI…",
"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…": "正在加载此账户的模型…",
"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 和运行配置)。"
}
+72
Переглянути файл
@@ -8,6 +8,7 @@ import {
withOwnFileColor,
} from "./fileColors";
import { useProject } from "./project";
import { projectModules } from "./projectRoots";
import { filePatternRegExp, inScope, parseScope, scopeError, type ScopeContext } from "./scopes";
const ctx = (scopes: ScopeContext["scopes"] = [], extra: Partial<ScopeContext> = {}): ScopeContext => ({
@@ -61,6 +62,77 @@ describe("scope expressions", () => {
expect(inScope("Web", "/p/src/app.ts", c)).toBe(false);
});
it("matches absolute module paths on POSIX and Windows drives", () => {
useProject.setState({
project: {
name: "ws",
root: "/ws",
trusted: true,
settings: {},
workspace: { version: 1, name: "ws", projects: ["/ws/app", "/ws/svc"] },
} as never,
});
const posix = ctx([{ name: "Svc", pattern: "file[svc]:*.java" }], {
modules: [
{ name: "app", path: "/ws/app" },
{ name: "svc", path: "/ws/svc" },
],
});
expect(inScope("Svc", "/ws/svc/src/App.java", posix)).toBe(true);
expect(inScope("Svc", "/ws/app/src/App.java", posix)).toBe(false);
useProject.setState({
project: {
name: "ws",
root: "C:/ws",
trusted: true,
settings: {},
workspace: { version: 1, name: "ws", projects: ["C:/ws/app", "C:/ws/svc"] },
} as never,
});
const win = ctx([{ name: "Svc", pattern: "file[svc]:*.java" }], {
modules: [
{ name: "app", path: "C:/ws/app" },
{ name: "svc", path: "C:/ws/svc" },
],
});
expect(inScope("Svc", "C:/ws/svc/src/App.java", win)).toBe(true);
expect(inScope("Svc", "C:/ws/app/src/App.java", win)).toBe(false);
});
it("keeps subproject and root module scopes matching when synced from a subproject folder", () => {
// Opened at `/checkout/composite/app` while Gradle reports ancestor `composite` as plain `Gradle`,
// in-project `app` as `Gradle`, child `app:lib` as `lib/Gradle`, and sibling included build `svc`.
useProject.setState({
project: { name: "app", root: "/checkout/composite/app", trusted: true, settings: {} } as never,
});
const modules = projectModules(
[
{ path: "checkout/composite/src/main/java", kind: "source", detectedFrom: "Gradle" },
{ path: "src/main/java", kind: "source", detectedFrom: "Gradle" },
{ path: "lib/src/main/java", kind: "source", detectedFrom: "lib/Gradle" },
{ path: "checkout/svc/src/main/java", kind: "source", detectedFrom: "/checkout/svc/Gradle" },
],
"app",
);
expect(modules).toEqual([
{ path: "", name: "app" },
{ path: "/checkout/svc", name: "svc" },
{ path: "lib", name: "lib" },
]);
const c = ctx(
[
{ name: "App", pattern: "file[app]:*.java" },
{ name: "Lib", pattern: "file[lib]:*.java" },
],
{ modules },
);
expect(inScope("Lib", "/checkout/composite/app/lib/src/main/java/A.java", c)).toBe(true);
expect(inScope("App", "/checkout/composite/app/src/main/java/B.java", c)).toBe(true);
expect(inScope("Lib", "/checkout/composite/app/src/main/java/B.java", c)).toBe(false);
expect(inScope("App", "/checkout/composite/app/lib/src/main/java/A.java", c)).toBe(false);
});
it("reports where a pattern goes wrong", () => {
expect(scopeError("file:a && (file:b")).toEqual({ message: "')' expected", at: 17 });
expect(scopeError("src/*")).toEqual({ message: "'file:' expected", at: 0 });
+4 -2
Переглянути файл
@@ -149,12 +149,14 @@ export interface ScopeContext {
ownFolders?: readonly string[];
}
const isAbsolute = (path: string) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path);
/** The innermost module holding the file (`rel` in the project, `path` absolute). */
function moduleOf(rel: string, path: string, modules: readonly ProjectModule[]): ProjectModule | undefined {
let best: ProjectModule | undefined;
for (const m of modules) {
// Workspace members have absolute paths.
const at = m.path.startsWith("/") ? path : rel;
// Workspace members and external modules have absolute paths.
const at = isAbsolute(m.path) ? path : rel;
const holds = m.path === "" || at === m.path || at.startsWith(`${m.path}/`);
if (holds && (!best || m.path.length > best.path.length)) best = m;
}
+6 -1
Переглянути файл
@@ -83,17 +83,22 @@ describe("shared search pieces", () => {
});
it("keeps Gradle modules after a sync", () => {
// Root shapes ide-host `with_gradle_roots` writes for a synced multi-module build.
// Root shapes ide-host `with_gradle_roots` writes for a synced multi-module build,
// including included builds outside the project root.
const synced = projectModules(
[
{ path: "src/main/java", kind: "source", detectedFrom: "Gradle" },
{ path: "lib/src/main/java", kind: "source", detectedFrom: "lib/Gradle" },
{ path: "lib/build", kind: "excluded", detectedFrom: "lib/Gradle" },
{ path: "ws/svc/src/main/java", kind: "source", detectedFrom: "/ws/svc/Gradle" },
{ path: "C:/ws/win-svc/src/main/java", kind: "source", detectedFrom: "C:/ws/win-svc/Gradle" },
],
"app",
);
expect(synced).toEqual([
{ path: "", name: "app" },
{ path: "/ws/svc", name: "svc" },
{ path: "C:/ws/win-svc", name: "win-svc" },
{ path: "lib", name: "lib" },
]);
});