дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-29 22:02:59 +02:00
Порівняти коміти
2
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
9a9be3136e | ||
|
|
cb6e47c52d |
No files matched your search
@@ -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>;
|
||||
|
||||
@@ -853,6 +881,20 @@ impl AgentManager {
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
|
||||
let status = copilot_auth_status_with(
|
||||
self.shared.paths.custom_agents_dir.as_deref(),
|
||||
self.shared.env_secrets(),
|
||||
&self.shared.paths.project_root,
|
||||
)
|
||||
.await;
|
||||
if status.authenticated || !status.gh_accounts.is_empty() {
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
|
||||
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
|
||||
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
|
||||
@@ -875,7 +917,9 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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);
|
||||
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>,
|
||||
|
||||
@@ -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;
|
||||
@@ -268,16 +271,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 +305,124 @@ 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;
|
||||
}
|
||||
if matches!(entry.token_source.as_deref(), Some("GITHUB_TOKEN" | "GH_TOKEN" | "COPILOT_GITHUB_TOKEN")) {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<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();
|
||||
if !login.is_empty() {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -1251,12 +1371,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1265,7 +1385,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1550,6 +1670,45 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -132,6 +132,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
|
||||
|
||||
对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。
|
||||
|
||||
对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。完成登录或点击**应用**后,**新任务**会加载该已验证账号对应的可用模型列表。
|
||||
|
||||
**设置 › 智能体 › 聊天** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。
|
||||
|
||||
### 外部 MCP 服务器
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -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"]);
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -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. */
|
||||
@@ -4994,6 +5001,16 @@ export type ContributionInfo = {
|
||||
label: string,
|
||||
};
|
||||
|
||||
/** GitHub Copilot's default sign-in status alongside the accounts available through `gh`. */
|
||||
export type CopilotAuthStatus = {
|
||||
authenticated: boolean,
|
||||
login: string | null,
|
||||
authType: string | null,
|
||||
statusMessage: string | null,
|
||||
ghInstalled: boolean,
|
||||
ghAccounts: GhAuthAccount[],
|
||||
};
|
||||
|
||||
export type CoveragePrepared = CoveragePrepared_Serialize | CoveragePrepared_Deserialize;
|
||||
|
||||
export type CoveragePrepared_Deserialize = ({ status: "ready"; runner: string;
|
||||
@@ -7683,6 +7700,12 @@ export type GhApiRequest = {
|
||||
paginate: boolean,
|
||||
};
|
||||
|
||||
/** An authenticated `github.com` account stored in GitHub CLI (`gh`). */
|
||||
export type GhAuthAccount = {
|
||||
login: string,
|
||||
active: boolean,
|
||||
};
|
||||
|
||||
/** Whether pull requests can be shown for the project, and why not. */
|
||||
export type GhAvailability = { kind: "ready"; repo: GhRepo;
|
||||
/** The signed-in user. */
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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,19 @@
|
||||
"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…"
|
||||
}
|
||||
@@ -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} для этого файла?",
|
||||
|
||||
@@ -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ç",
|
||||
|
||||
@@ -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} 編碼?",
|
||||
|
||||
@@ -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,19 @@
|
||||
"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…": "正在加载此账户的模型…"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача