дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
1a1c3174ae | ||
|
|
dd1ab68e11 | ||
|
|
fc3614a3ee |
No files matched your search
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
|
||||
@@ -33,6 +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 skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -53,6 +54,21 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Resolves agent `id`'s interactive sign-in command without an open project.
|
||||
pub fn login_launch_without_project(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
) -> IdeResult<LoginLaunch> {
|
||||
let spec = provider::load(custom_agents_dir, secrets)
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
spec.login_launch(cwd, None)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
@@ -201,6 +217,8 @@ struct Shared {
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
probes: Mutex<HashMap<String, AgentProbe>>,
|
||||
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
|
||||
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
|
||||
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
|
||||
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
|
||||
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
|
||||
@@ -706,6 +724,7 @@ impl AgentManager {
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
terminal_auth_args: RwLock::new(HashMap::new()),
|
||||
copilot_acp_fallback: Mutex::new(HashSet::new()),
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
@@ -790,11 +809,14 @@ impl AgentManager {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.can_sign_in =
|
||||
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
@@ -802,6 +824,7 @@ impl AgentManager {
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
@@ -815,6 +838,21 @@ impl AgentManager {
|
||||
list
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = specs
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
|
||||
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
|
||||
})?;
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
@@ -3509,6 +3547,14 @@ impl Task {
|
||||
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
|
||||
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
|
||||
})?;
|
||||
if let Some(args) = init.auth_methods.iter().find_map(|method| {
|
||||
if method.get("type").and_then(Value::as_str) != Some("terminal") {
|
||||
return None;
|
||||
}
|
||||
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
|
||||
}) {
|
||||
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
|
||||
}
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
|
||||
@@ -623,6 +623,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -647,6 +650,14 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// 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")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
|
||||
@@ -73,7 +73,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -176,6 +176,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -389,6 +463,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -901,6 +976,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1458,4 +1549,27 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -1212,7 +1212,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
|
||||
@@ -6,9 +6,9 @@ use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
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,
|
||||
};
|
||||
@@ -108,6 +108,73 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
pub(crate) fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: std::path::PathBuf,
|
||||
launch: LoginLaunch,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
crate::ops::term::apply_output_rate(host, window);
|
||||
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
let options = ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(launch.program.to_string_lossy().into_owned()),
|
||||
args: launch.args,
|
||||
env: launch.env,
|
||||
cols: if cols == 0 { 80 } else { cols },
|
||||
rows: if rows == 0 { 20 } else { rows },
|
||||
shell_integration: false,
|
||||
};
|
||||
let exit_channel = on_event.clone();
|
||||
host.terminals.spawn_program(
|
||||
options,
|
||||
format!("agent-login:{window}"),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| {
|
||||
let _ = on_event.send(AgentLoginEvent::Output { data });
|
||||
}),
|
||||
Some(std::sync::Arc::new(move |code| {
|
||||
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&id)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
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)?;
|
||||
@@ -1472,6 +1539,7 @@ ide_command::domain!(
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
|
||||
@@ -16,7 +16,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
|
||||
@@ -16,7 +16,7 @@ OpenIDEA 本身不带模型或账号:它启动你已安装并登录的 agent
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { AgentConfigOption, AgentProvider } 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("signs in to an agent in an IDE terminal dialog and refreshes its model catalog", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(() => {
|
||||
const model: AgentConfigOption = {
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: null,
|
||||
category: "model",
|
||||
current: "claude-sonnet-4.5",
|
||||
defaultValue: "claude-sonnet-4.5",
|
||||
via: "option",
|
||||
values: [
|
||||
{ value: "claude-sonnet-4.5", name: "Claude Sonnet 4.5", description: null },
|
||||
{ value: "gpt-5", name: "GPT-5", description: null },
|
||||
],
|
||||
};
|
||||
let signedIn = false;
|
||||
Object.assign(window.__ipc.handlers, {
|
||||
settings_get_global: () => ({}),
|
||||
agent_registry_list: () => ({ agents: [], warning: null }),
|
||||
agent_providers: () => {
|
||||
const provider: AgentProvider = {
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
program: "/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"],
|
||||
loginHint:
|
||||
"Run `'/Users/alice/Library/Application Support/ai.l0ng.openidea/agents/tools/copilot/1.0.116/copilot' login` in a terminal.",
|
||||
commandOverridden: false,
|
||||
commandEditable: false,
|
||||
commandReadOnlyReason: "registry",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
canCheckCliUpdate: false,
|
||||
env: {},
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
commands: [],
|
||||
source: { kind: "registry", version: "1.0.116", update: null },
|
||||
};
|
||||
return [provider];
|
||||
},
|
||||
agent_refresh_models: () => ({
|
||||
provider: "copilot",
|
||||
config: signedIn ? [model] : [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: signedIn ? Date.now() : null,
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
}),
|
||||
agent_login_spawn: ({ onEvent }: { onEvent: unknown }) => {
|
||||
setTimeout(() => {
|
||||
window.__ipc.send(onEvent, { type: "output", data: "Opening GitHub in browser...\r\n" });
|
||||
signedIn = true;
|
||||
window.__ipc.send(onEvent, { type: "exited", code: 0 });
|
||||
}, 40);
|
||||
return { id: 1, pid: 1001, title: "copilot" };
|
||||
},
|
||||
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" });
|
||||
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(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"]);
|
||||
});
|
||||
@@ -22,6 +22,7 @@ agent_fork_session trusted project_host bin
|
||||
agent_grouped_changes trusted project_host bindings async
|
||||
agent_hermes_profiles trusted project_host bindings async
|
||||
agent_import_session trusted project_host bindings async
|
||||
agent_login_spawn outside_restricted project_host bindings async
|
||||
agent_mcp_discover_sources always project_host bindings async
|
||||
agent_mcp_import always project_host bindings sync
|
||||
agent_mcp_import_selected always project_host bindings async
|
||||
|
||||
@@ -75,6 +75,8 @@ export const commands = {
|
||||
agentHermesProfiles: () => typedError<HermesProfile[], IdeError>(__TAURI_INVOKE("agent_hermes_profiles")),
|
||||
/** Imports an external session as a task: its first turn loads and replays it. */
|
||||
agentImportSession: (provider: string, sessionId: string) => typedError<AgentTask_Serialize, IdeError>(__TAURI_INVOKE("agent_import_session", { provider, sessionId })),
|
||||
/** Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code. */
|
||||
agentLoginSpawn: (id: string, cols: number, rows: number, onEvent: Channel<AgentLoginEvent>) => typedError<TerminalInfo, IdeError>(__TAURI_INVOKE("agent_login_spawn", { id, cols, rows, onEvent })),
|
||||
/** Discovers external MCP configuration files on disk (CLI user configs + workspace `.mcp.json`). */
|
||||
agentMcpDiscoverSources: () => typedError<McpExternalSource[], IdeError>(__TAURI_INVOKE("agent_mcp_discover_sources")),
|
||||
/** Copies MCP servers from `.mcp.json` and `.vscode/mcp.json` into the workspace settings once. */
|
||||
@@ -2899,6 +2901,9 @@ export type AgentLimit = {
|
||||
resetsMs: number | null,
|
||||
};
|
||||
|
||||
/** Output and completion of an interactive sign-in PTY started by the IDE. */
|
||||
export type AgentLoginEvent = { type: "output"; data: string } | { type: "exited"; code: number | null };
|
||||
|
||||
/** An MCP server passed to coding agents in `session/new`, `session/load` and `session/fork`. */
|
||||
export type AgentMcpServer = AgentMcpServer_Serialize | AgentMcpServer_Deserialize;
|
||||
|
||||
@@ -3013,6 +3018,8 @@ export type AgentProvider_Deserialize = {
|
||||
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
|
||||
/** Whether the command was found (on `PATH`). */
|
||||
installed: boolean,
|
||||
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
|
||||
canSignIn?: boolean,
|
||||
/** The built-in command can be owned by a global npm package. */
|
||||
canCheckCliUpdate?: boolean,
|
||||
/** Environment variables it starts with (from its agent file). */
|
||||
@@ -3044,6 +3051,8 @@ export type AgentProvider_Serialize = {
|
||||
commandReadOnlyReason: AgentCommandReadOnlyReason | null,
|
||||
/** Whether the command was found (on `PATH`). */
|
||||
installed: boolean,
|
||||
/** Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal. */
|
||||
canSignIn: boolean,
|
||||
/** The built-in command can be owned by a global npm package. */
|
||||
canCheckCliUpdate: boolean,
|
||||
/** Environment variables it starts with (from its agent file). */
|
||||
|
||||
@@ -237,6 +237,26 @@
|
||||
.text code {
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.signInRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
margin: 4px 0;
|
||||
}
|
||||
.signInHint {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-1);
|
||||
margin: 0;
|
||||
color: var(--fg);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.signInHint code {
|
||||
font-family: var(--font-mono);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
/* "Label: control" rows; a hint sits under its control. */
|
||||
.form {
|
||||
display: grid;
|
||||
|
||||
@@ -19,9 +19,23 @@ import { isCancelled, nextRequestId } from "@/platform/ipc";
|
||||
import { tx, useTxTemplate } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
import clsx from "clsx";
|
||||
import { Button, Dialog, Icon, IconButton, Input, List, ProgressBar, SearchField, Select, Spinner, T } from "@/ui";
|
||||
import {
|
||||
Button,
|
||||
copyText,
|
||||
Dialog,
|
||||
Icon,
|
||||
IconButton,
|
||||
Input,
|
||||
List,
|
||||
ProgressBar,
|
||||
SearchField,
|
||||
Select,
|
||||
Spinner,
|
||||
T,
|
||||
} from "@/ui";
|
||||
import { useSettingsForm } from "@/workbench/contributions";
|
||||
import { confirm } from "@/workbench/messages";
|
||||
import { AgentSignInDialog, type SignInTarget } from "./AgentSignInDialog";
|
||||
import { LocalCliUpdate } from "./LocalCliUpdate";
|
||||
import { approvalDefaults, cursorModelDefaults, isPerModelOption } from "./composerModel";
|
||||
import { providerIcon, slugifyId } from "./model";
|
||||
@@ -863,6 +877,7 @@ function ProviderSettings({
|
||||
return formatEnv(launchEnv(parsed));
|
||||
});
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [signInTarget, setSignInTarget] = useState<SignInTarget | null>(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(() => {
|
||||
@@ -875,16 +890,39 @@ function ProviderSettings({
|
||||
? [agent.defaultProgram, ...agent.defaultArgs].join(" ")
|
||||
: formatArgs([agent.program, ...agent.args]);
|
||||
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;
|
||||
return (
|
||||
<>
|
||||
{value.trim() === current && agent.installed && agent.canCheckCliUpdate && (
|
||||
<LocalCliUpdate key={agent.program} agent={agent} backend={backend} />
|
||||
)}
|
||||
{agent.loginHint && (
|
||||
{(agent.loginHint || canSignInInIde) && (
|
||||
<Section title="Sign In">
|
||||
<p className={styles.text}>
|
||||
<LoginHint text={agent.loginHint} />
|
||||
</p>
|
||||
<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">
|
||||
@@ -1011,6 +1049,29 @@ function ProviderSettings({
|
||||
</p>
|
||||
)}
|
||||
</Section>
|
||||
{signInTarget && (
|
||||
<AgentSignInDialog
|
||||
target={signInTarget}
|
||||
spawner={backend}
|
||||
onClose={() => setSignInTarget(null)}
|
||||
onCompleted={() => {
|
||||
void refresh().catch((e: unknown) => setError(errorText(e)));
|
||||
onChanged?.();
|
||||
if (backend.refreshModels) {
|
||||
void backend
|
||||
.refreshModels(agent.id, null, true)
|
||||
.then((cat) =>
|
||||
useAgents.setState((s) => {
|
||||
const modelCatalogs = new Map(s.modelCatalogs);
|
||||
modelCatalogs.set(agent.id, cat);
|
||||
return { modelCatalogs };
|
||||
}),
|
||||
)
|
||||
.catch(() => {});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
padding: 12px 16px 8px;
|
||||
}
|
||||
|
||||
.terminal {
|
||||
width: 100%;
|
||||
height: 300px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--bg-editor, var(--bg));
|
||||
overflow: hidden;
|
||||
padding: 6px 8px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
color: var(--fg-subtle);
|
||||
font-size: var(--fs-small);
|
||||
}
|
||||
|
||||
.error {
|
||||
margin: 0;
|
||||
color: var(--fg-error, var(--danger, #d93025));
|
||||
font-size: var(--fs-small);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { AgentLoginEvent, TerminalId } from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import { Dialog, Spinner, T } from "@/ui";
|
||||
import { embeddedTerminal, type EmbeddedTerminal } from "@/workbench/contributions";
|
||||
import styles from "./AgentSignInDialog.module.css";
|
||||
import { tauriCommands } from "./registry";
|
||||
|
||||
export type SignInTarget = { kind: "agent"; id: string; name: string };
|
||||
|
||||
export interface SignInSpawner {
|
||||
loginSpawn?(id: string, cols: number, rows: number, onEvent: (e: AgentLoginEvent) => void): Promise<TerminalId>;
|
||||
}
|
||||
|
||||
export function AgentSignInDialog({
|
||||
target,
|
||||
spawner,
|
||||
onClose,
|
||||
onCompleted,
|
||||
}: {
|
||||
target: SignInTarget;
|
||||
spawner?: SignInSpawner;
|
||||
onClose: () => void;
|
||||
onCompleted: () => void;
|
||||
}) {
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const ptyIdRef = useRef<TerminalId | null>(null);
|
||||
const completedRef = useRef(false);
|
||||
const callbacksRef = useRef({ onClose, onCompleted, spawner });
|
||||
useEffect(() => {
|
||||
callbacksRef.current = { onClose, onCompleted, spawner };
|
||||
});
|
||||
|
||||
const [attempt, setAttempt] = useState(0);
|
||||
const [exitCode, setExitCode] = useState<number | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const agentId = target.id;
|
||||
|
||||
useEffect(() => {
|
||||
const el = hostRef.current;
|
||||
if (!el) return;
|
||||
let disposed = false;
|
||||
let term: EmbeddedTerminal | null = null;
|
||||
const pendingOutput: string[] = [];
|
||||
let pendingSize: { cols: number; rows: number } = { cols: 80, rows: 18 };
|
||||
completedRef.current = false;
|
||||
setExitCode(null);
|
||||
setError(null);
|
||||
|
||||
const killPty = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
};
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
// Provided by the terminal feature (workbench windows) or the Settings window's boot.
|
||||
const factory = embeddedTerminal();
|
||||
if (!factory) throw new Error(tx("The terminal is not available in this window."));
|
||||
const instance = await factory(el, {
|
||||
onData: (data) => {
|
||||
const id = ptyIdRef.current;
|
||||
if (id !== null) void commands.termWrite(id, data).catch(() => {});
|
||||
},
|
||||
onResize: (cols, rows) => {
|
||||
pendingSize = { cols, rows };
|
||||
const id = ptyIdRef.current;
|
||||
if (id !== null) void commands.termResize(id, cols, rows).catch(() => {});
|
||||
},
|
||||
});
|
||||
if (disposed) {
|
||||
instance.dispose();
|
||||
return;
|
||||
}
|
||||
term = instance;
|
||||
for (const chunk of pendingOutput.splice(0)) {
|
||||
term.write(chunk);
|
||||
}
|
||||
term.focus();
|
||||
} catch (e) {
|
||||
if (!disposed) setError(e instanceof Error ? e.message : String(e));
|
||||
return;
|
||||
}
|
||||
|
||||
const onEvent = (event: AgentLoginEvent) => {
|
||||
if (disposed) return;
|
||||
if (event.type === "output") {
|
||||
if (term) term.write(event.data);
|
||||
else pendingOutput.push(event.data);
|
||||
} else {
|
||||
ptyIdRef.current = null;
|
||||
const code = event.code ?? -1;
|
||||
setExitCode(code);
|
||||
if (code === 0 && !completedRef.current) {
|
||||
completedRef.current = true;
|
||||
callbacksRef.current.onCompleted();
|
||||
callbacksRef.current.onClose();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const custom = callbacksRef.current.spawner;
|
||||
const ptyId = await (custom?.loginSpawn ?? tauriCommands.loginSpawn!)(
|
||||
agentId,
|
||||
pendingSize.cols,
|
||||
pendingSize.rows,
|
||||
onEvent,
|
||||
);
|
||||
if (disposed) {
|
||||
void commands.termKill(ptyId).catch(() => {});
|
||||
return;
|
||||
}
|
||||
ptyIdRef.current = ptyId;
|
||||
void commands.termResize(ptyId, pendingSize.cols, pendingSize.rows).catch(() => {});
|
||||
term?.focus();
|
||||
} catch (e) {
|
||||
if (!disposed) setError(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
killPty();
|
||||
term?.dispose();
|
||||
};
|
||||
}, [agentId, attempt]);
|
||||
|
||||
const running = exitCode === null && !error;
|
||||
const title = tx`Sign In to ${target.name}`;
|
||||
|
||||
const finishAndClose = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
if (!completedRef.current) {
|
||||
completedRef.current = true;
|
||||
onCompleted();
|
||||
}
|
||||
onClose();
|
||||
};
|
||||
|
||||
const cancelAndClose = () => {
|
||||
const id = ptyIdRef.current;
|
||||
ptyIdRef.current = null;
|
||||
if (id !== null) void commands.termKill(id).catch(() => {});
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
blockWorkbenchShortcuts
|
||||
onClose={cancelAndClose}
|
||||
title={title}
|
||||
width={640}
|
||||
footerStart={
|
||||
running ? (
|
||||
<span className={styles.status}>
|
||||
<Spinner size={12} /> <T>Complete sign-in in your browser or the terminal above…</T>
|
||||
</span>
|
||||
) : exitCode !== null && exitCode !== 0 ? (
|
||||
<span className={styles.error}>{tx`Sign-in exited with code ${exitCode}.`}</span>
|
||||
) : undefined
|
||||
}
|
||||
buttons={
|
||||
running
|
||||
? [
|
||||
{ label: "Done", onClick: finishAndClose },
|
||||
{ label: "Cancel", role: "cancel", onClick: cancelAndClose },
|
||||
]
|
||||
: [
|
||||
{ label: "Retry", role: "default", onClick: () => setAttempt((n) => n + 1) },
|
||||
{ label: "Close", role: "cancel", onClick: cancelAndClose },
|
||||
]
|
||||
}
|
||||
>
|
||||
<div className={styles.body}>
|
||||
<div ref={hostRef} className={styles.terminal} data-autofocus />
|
||||
{error && <p className={styles.error}>{error}</p>}
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1071,6 +1071,12 @@
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.errorContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.working {
|
||||
display: flex;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import type {
|
||||
AcpImportOutcome,
|
||||
AgentLoginEvent,
|
||||
AgentProvider,
|
||||
AgentRegistry,
|
||||
InstallEvent,
|
||||
@@ -13,7 +14,7 @@ import { setLocale, tx } from "@/platform/i18n";
|
||||
import { iconMarkup } from "@/ui/icons";
|
||||
import { MessagesHost } from "@/workbench/messages";
|
||||
import { AgentRegistryPage as RegistryPage } from "./AgentRegistryPage";
|
||||
import { SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { provideEmbeddedTerminal, SettingsFormContext, registerSettingsPage } from "@/workbench/contributions";
|
||||
import { useSettingsFormFor } from "@/features/settings/components/context";
|
||||
import { closeSettings, openSettings, selectPage } from "@/features/settings/model/staging";
|
||||
import { SettingsDialog } from "@/features/settings/dialog/SettingsDialog";
|
||||
@@ -419,6 +420,8 @@ class FakeCommands implements CommandsBackend {
|
||||
list: AgentProvider[] = [];
|
||||
saved: [string, string | null][] = [];
|
||||
providers = vi.fn(async () => this.list);
|
||||
loginSpawn?: CommandsBackend["loginSpawn"];
|
||||
refreshModels?: CommandsBackend["refreshModels"];
|
||||
chooseExecutable = vi.fn(async () => "/chosen/agent");
|
||||
saveCustom = vi.fn(async () => {});
|
||||
setAdditionalArgs = vi.fn<CommandsBackend["setAdditionalArgs"]>();
|
||||
@@ -640,6 +643,68 @@ describe("Built-in executable overrides", () => {
|
||||
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 () => {
|
||||
const written: string[] = [];
|
||||
provideEmbeddedTerminal(async () => ({
|
||||
write: (d) => written.push(d),
|
||||
clear: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
fit: vi.fn(),
|
||||
dispose: vi.fn(),
|
||||
}));
|
||||
let onLoginEvent: ((e: AgentLoginEvent) => void) | null = null;
|
||||
try {
|
||||
const commands = new FakeCommands();
|
||||
commands.loginSpawn = vi.fn(async (_id, _cols, _rows, cb) => {
|
||||
onLoginEvent = cb;
|
||||
return 101;
|
||||
});
|
||||
const refreshModels = vi.fn().mockResolvedValue({
|
||||
provider: "copilot",
|
||||
config: [],
|
||||
thoughtLevels: {},
|
||||
refreshing: false,
|
||||
refreshedAtMs: Date.now(),
|
||||
retryAtMs: null,
|
||||
error: null,
|
||||
});
|
||||
commands.refreshModels = refreshModels;
|
||||
commands.list = [
|
||||
{
|
||||
...claudeProvider("copilot"),
|
||||
id: "copilot",
|
||||
name: "GitHub Copilot",
|
||||
command: "copilot --headless --no-auto-update --stdio",
|
||||
defaultProgram: "copilot",
|
||||
loginHint: "Run `copilot login` in a terminal.",
|
||||
installed: true,
|
||||
canSignIn: true,
|
||||
commandReadOnlyReason: "registry",
|
||||
},
|
||||
];
|
||||
await openCommands(commands, vi.fn(), "GitHub Copilot");
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Sign In…" }));
|
||||
expect(await screen.findByRole("dialog", { name: "Sign In to GitHub Copilot" })).toBeInTheDocument();
|
||||
await waitFor(() =>
|
||||
expect(commands.loginSpawn).toHaveBeenCalledWith(
|
||||
"copilot",
|
||||
expect.any(Number),
|
||||
expect.any(Number),
|
||||
expect.any(Function),
|
||||
),
|
||||
);
|
||||
act(() => {
|
||||
onLoginEvent?.({ type: "output", data: "Opening browser…\r\n" });
|
||||
onLoginEvent?.({ type: "exited", code: 0 });
|
||||
});
|
||||
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);
|
||||
} finally {
|
||||
provideEmbeddedTerminal(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
it("Cancel discards command edits without writing", async () => {
|
||||
const commands = new FakeCommands();
|
||||
commands.list = [
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { _resetI18nForTests, setLocale } from "@/platform/i18n";
|
||||
import { useAgentErrorText } from "./loginHint";
|
||||
import { isSignInErrorMessage, useAgentErrorText } from "./loginHint";
|
||||
|
||||
afterEach(() => _resetI18nForTests());
|
||||
|
||||
it("recognizes IDE sign-in guidance messages", () => {
|
||||
expect(isSignInErrorMessage("GitHub Copilot needs you to sign in. Run `copilot login` in a terminal.")).toBe(true);
|
||||
expect(isSignInErrorMessage("Agent says: authentication failed")).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["Run `cursor-agent login` in a terminal.", "在终端中运行 `cursor-agent login`。"],
|
||||
["Run `'/registry path/cursor-agent' login` in a terminal.", "在终端中运行 `'/registry path/cursor-agent' login`。"],
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { useTx, useTxTemplate } from "@/platform/i18n";
|
||||
|
||||
const SIGN_IN_RE = /^(.+?) needs you to sign in\. ([^\n]+)([\s\S]*)$/;
|
||||
|
||||
export const isSignInErrorMessage = (message: string): boolean => SIGN_IN_RE.test(message);
|
||||
|
||||
/** Translate the IDE's sign-in guidance while preserving the agent's own errors. */
|
||||
export function useAgentErrorText(message: string): string {
|
||||
const tx = useTx();
|
||||
const translate = useTxTemplate();
|
||||
const auth = /^(.+?) needs you to sign in\. ([^\n]+)([\s\S]*)$/.exec(message);
|
||||
const auth = SIGN_IN_RE.exec(message);
|
||||
return auth ? `${tx`${auth[1]} needs you to sign in. ${translate(auth[2]!)}`}${auth[3]}` : message;
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
AcpImportOutcome,
|
||||
AgentCliOffer,
|
||||
AgentCliUpdateResult,
|
||||
AgentLoginEvent,
|
||||
AgentModelCatalog,
|
||||
AgentProvider,
|
||||
AgentRegistry,
|
||||
@@ -15,6 +16,7 @@ import type {
|
||||
RegistryAgent,
|
||||
RegistryDistribution,
|
||||
RequestId,
|
||||
TerminalId,
|
||||
} from "@/bindings";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
@@ -32,7 +34,8 @@ export interface CommandsBackend {
|
||||
updateCli(id: string, offer: AgentCliOffer, request: RequestId): Promise<AgentCliUpdateResult>;
|
||||
cancel(request: RequestId): void;
|
||||
providers(): Promise<AgentProvider[]>;
|
||||
refreshModels?(id: string, model: string | null): Promise<AgentModelCatalog>;
|
||||
loginSpawn?(id: string, 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>;
|
||||
setEnv(id: string, env: Record<string, string>): Promise<void>;
|
||||
@@ -61,7 +64,13 @@ export const tauriCommands: CommandsBackend = {
|
||||
updateCli: (id, offer, request) => call(commands.agentCliUpdate(id, offer, request)),
|
||||
cancel: tauriRegistry.cancel,
|
||||
providers: () => call(commands.agentProviders()),
|
||||
refreshModels: (id, model) => call(commands.agentRefreshModels(id, false, model)),
|
||||
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;
|
||||
},
|
||||
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 });
|
||||
const picked = await open({ title, defaultPath: current || undefined, directory: false, multiple: false });
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import type { AgentEntry, AgentImage, AgentTask } from "@/bindings";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { call, commands, isTauri } from "@/platform/ipc";
|
||||
import { basename } from "@/platform/project";
|
||||
import { copyText, fileIconName, Icon, IconButton, T } from "@/ui";
|
||||
import { Button, copyText, fileIconName, Icon, IconButton, T } from "@/ui";
|
||||
import { notifications } from "@/workbench/contributions";
|
||||
import clsx from "clsx";
|
||||
import { memo, useLayoutEffect, useRef, useState, type RefObject } from "react";
|
||||
import { AgentReply, MessageActions, ReplyActions } from "../AgentReply";
|
||||
import { AgentSignInDialog } from "../AgentSignInDialog";
|
||||
import { ImageStrip } from "../ImageStrip";
|
||||
import { ReferencedText } from "../ReferenceChip";
|
||||
import styles from "../Session.module.css";
|
||||
@@ -14,12 +16,12 @@ import { SubmitButton } from "../SubmitButton";
|
||||
import { useAgentSettings } from "../agentSettings";
|
||||
import { messageTokens, parseMention } from "../composerModel";
|
||||
import { formatDuration, formatSentAt, userMessageText } from "../conversation";
|
||||
import { useAgentErrorText } from "../loginHint";
|
||||
import { isSignInErrorMessage, useAgentErrorText } from "../loginHint";
|
||||
import { isBusy, type ReplyTimes, type ReplyTurn } from "../model";
|
||||
import { useRevealedText } from "../reveal";
|
||||
import { forkTask, rerunFrom, resendMessage } from "../store";
|
||||
import { forkTask, refreshProviders, rerunFrom, resendMessage, useAgents } from "../store";
|
||||
import { PermissionLine, QuestionForm, type QuestionAnswer } from "./QuestionForm";
|
||||
import { samePropsExcept, type UserEntry } from "./shared";
|
||||
import { providerName, samePropsExcept, type UserEntry } from "./shared";
|
||||
import { SubagentCard, ThoughtEntry, ToolEntry } from "./toolEntries";
|
||||
|
||||
/** When a message was sent, or when the turn behind a reply finished, and how long it took. */
|
||||
@@ -219,12 +221,7 @@ function EntryView({
|
||||
</div>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<div className={styles.error} role="alert">
|
||||
<Icon name="error" size={14} />
|
||||
<AgentErrorText message={entry.message} />
|
||||
</div>
|
||||
);
|
||||
return <AgentErrorEntry task={task} message={entry.message} />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -244,8 +241,37 @@ export const Entry = memo(
|
||||
}),
|
||||
);
|
||||
|
||||
function AgentErrorText({ message }: { message: string }) {
|
||||
return <span>{useAgentErrorText(message)}</span>;
|
||||
function AgentErrorEntry({ task, message }: { task: AgentTask; message: string }) {
|
||||
const [signingIn, setSigningIn] = useState(false);
|
||||
const text = useAgentErrorText(message);
|
||||
const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false);
|
||||
const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message);
|
||||
const name = providerName(task.provider);
|
||||
return (
|
||||
<div className={styles.error} role="alert">
|
||||
<Icon name="error" size={14} />
|
||||
<div className={styles.errorContent}>
|
||||
<span>{text}</span>
|
||||
{canSignIn && (
|
||||
<div>
|
||||
<Button size="small" onClick={() => setSigningIn(true)}>
|
||||
<T>Sign In…</T>
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{signingIn && (
|
||||
<AgentSignInDialog
|
||||
target={{ kind: "agent", id: task.provider, name }}
|
||||
onClose={() => setSigningIn(false)}
|
||||
onCompleted={() => {
|
||||
void refreshProviders();
|
||||
void call(commands.agentRefreshModels(task.provider, true, null)).catch(() => {});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UserMessage({
|
||||
|
||||
@@ -4179,7 +4179,13 @@
|
||||
"SVG editor layout": "SVG editor layout",
|
||||
"Resize SVG preview": "Resize SVG preview",
|
||||
"The SVG source is not valid.": "The SVG source is not valid.",
|
||||
"Sign In…": "Sign In…",
|
||||
"Copy command": "Copy command",
|
||||
"Sign In to {name}": "Sign In to {name}",
|
||||
"Complete sign-in in your browser or the terminal above…": "Complete sign-in in your browser or the terminal above…",
|
||||
"Sign-in exited with code {exitCode}.": "Sign-in exited with code {exitCode}.",
|
||||
"Install GitHub CLI": "Install GitHub CLI",
|
||||
"Download manually…": "Download manually…",
|
||||
"Show Scratches and Consoles": "Show Scratches and Consoles"
|
||||
"Show Scratches and Consoles": "Show Scratches and Consoles",
|
||||
"The terminal is not available in this window.": "The terminal is not available in this window."
|
||||
}
|
||||
@@ -33,7 +33,6 @@
|
||||
"Run `auggie login` in a terminal.": "Ejecuta `auggie login` en una terminal.",
|
||||
"Run `claude` in a terminal and sign in.": "Ejecuta `claude` en una terminal e inicia sesión.",
|
||||
"Run `codex login` in a terminal.": "Ejecuta `codex login` en una terminal.",
|
||||
"Run `copilot` in a terminal and sign in.": "Ejecuta `copilot` en una terminal e inicia sesión.",
|
||||
"Run `cursor-agent login` in a terminal.": "Ejecuta `cursor-agent login` en una terminal.",
|
||||
"Run `gemini` in a terminal and sign in.": "Ejecuta `gemini` en una terminal e inicia sesión.",
|
||||
"Run `goose configure` in a terminal.": "Ejecuta `goose configure` en una terminal.",
|
||||
|
||||
@@ -5690,7 +5690,6 @@
|
||||
"Run `auggie login` in a terminal.": "Exécutez `auggie login` dans un terminal.",
|
||||
"Run `claude` in a terminal and sign in.": "Exécutez `claude` dans un terminal et connectez-vous.",
|
||||
"Run `codex login` in a terminal.": "Exécutez `codex login` dans un terminal.",
|
||||
"Run `copilot` in a terminal and sign in.": "Exécutez `copilot` dans un terminal et connectez-vous.",
|
||||
"Run `cursor-agent login` in a terminal.": "Exécutez `cursor-agent login` dans un terminal.",
|
||||
"Run `gemini` in a terminal and sign in.": "Exécutez `gemini` dans un terminal et connectez-vous.",
|
||||
"Run `goose configure` in a terminal.": "Exécutez `goose configure` dans un terminal.",
|
||||
|
||||
@@ -64,7 +64,6 @@
|
||||
"Run `auggie login` in a terminal.": "터미널에서 `auggie login`을 실행하세요.",
|
||||
"Run `claude` in a terminal and sign in.": "터미널에서 `claude`를 실행하고 로그인하세요.",
|
||||
"Run `codex login` in a terminal.": "터미널에서 `codex login`을 실행하세요.",
|
||||
"Run `copilot` in a terminal and sign in.": "터미널에서 `copilot`을 실행하고 로그인하세요.",
|
||||
"Run `cursor-agent login` in a terminal.": "터미널에서 `cursor-agent login`을 실행하세요.",
|
||||
"Run `gemini` in a terminal and sign in.": "터미널에서 `gemini`를 실행하고 로그인하세요.",
|
||||
"Run `goose configure` in a terminal.": "터미널에서 `goose configure`를 실행하세요.",
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
"Run `auggie login` in a terminal.": "Uruchom `auggie login` w terminalu.",
|
||||
"Run `claude` in a terminal and sign in.": "Uruchom `claude` w terminalu i zaloguj się.",
|
||||
"Run `codex login` in a terminal.": "Uruchom `codex login` w terminalu.",
|
||||
"Run `copilot` in a terminal and sign in.": "Uruchom `copilot` w terminalu i zaloguj się.",
|
||||
"Run `cursor-agent login` in a terminal.": "Uruchom `cursor-agent login` w terminalu.",
|
||||
"Run `gemini` in a terminal and sign in.": "Uruchom `gemini` w terminalu i zaloguj się.",
|
||||
"Run `goose configure` in a terminal.": "Uruchom `goose configure` w terminalu.",
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
"Run `auggie login` in a terminal.": "Execute `auggie login` em um terminal.",
|
||||
"Run `claude` in a terminal and sign in.": "Execute `claude` em um terminal e entre.",
|
||||
"Run `codex login` in a terminal.": "Execute `codex login` em um terminal.",
|
||||
"Run `copilot` in a terminal and sign in.": "Execute `copilot` em um terminal e entre.",
|
||||
"Run `cursor-agent login` in a terminal.": "Execute `cursor-agent login` em um terminal.",
|
||||
"Run `gemini` in a terminal and sign in.": "Execute `gemini` em um terminal e entre.",
|
||||
"Run `goose configure` in a terminal.": "Execute `goose configure` em um terminal.",
|
||||
|
||||
@@ -927,7 +927,6 @@
|
||||
"Run `auggie login` in a terminal.": "Выполните `auggie login` в терминале.",
|
||||
"Run `claude` in a terminal and sign in.": "Запустите `claude` в терминале и выполните вход.",
|
||||
"Run `codex login` in a terminal.": "Выполните `codex login` в терминале.",
|
||||
"Run `copilot` in a terminal and sign in.": "Запустите `copilot` в терминале и выполните вход.",
|
||||
"Run `cursor-agent login` in a terminal.": "Выполните `cursor-agent login` в терминале.",
|
||||
"Run `gemini` in a terminal and sign in.": "Запустите `gemini` в терминале и выполните вход.",
|
||||
"Run `goose configure` in a terminal.": "Выполните `goose configure` в терминале.",
|
||||
|
||||
@@ -2837,7 +2837,6 @@
|
||||
"Run `auggie login` in a terminal.": "Bir terminalde `auggie login` komutunu çalıştırın.",
|
||||
"Run `claude` in a terminal and sign in.": "Bir terminalde `claude` komutunu çalıştırın ve oturum açın.",
|
||||
"Run `codex login` in a terminal.": "Bir terminalde `codex login` komutunu çalıştırın.",
|
||||
"Run `copilot` in a terminal and sign in.": "Bir terminalde `copilot` komutunu çalıştırın ve oturum açın.",
|
||||
"Run `cursor-agent login` in a terminal.": "Bir terminalde `cursor-agent login` komutunu çalıştırın.",
|
||||
"Run `gemini` in a terminal and sign in.": "Bir terminalde `gemini` komutunu çalıştırın ve oturum açın.",
|
||||
"Run `goose configure` in a terminal.": "Bir terminalde `goose configure` komutunu çalıştırın.",
|
||||
|
||||
@@ -611,7 +611,6 @@
|
||||
"Run `auggie login` in a terminal.": "在終端機中執行 `auggie login`。",
|
||||
"Run `claude` in a terminal and sign in.": "在終端機中執行 `claude` 並登入。",
|
||||
"Run `codex login` in a terminal.": "在終端機中執行 `codex login`。",
|
||||
"Run `copilot` in a terminal and sign in.": "在終端機中執行 `copilot` 並登入。",
|
||||
"Run `cursor-agent login` in a terminal.": "在終端機中執行 `cursor-agent login`。",
|
||||
"Run `gemini` in a terminal and sign in.": "在終端機中執行 `gemini` 並登入。",
|
||||
"Run `goose configure` in a terminal.": "在終端機中執行 `goose configure`。",
|
||||
|
||||
@@ -971,7 +971,6 @@
|
||||
"Run `auggie login` in a terminal.": "在终端中运行 `auggie login`。",
|
||||
"Run `claude` in a terminal and sign in.": "在终端中运行 `claude` 并登录。",
|
||||
"Run `codex login` in a terminal.": "在终端中运行 `codex login`。",
|
||||
"Run `copilot` in a terminal and sign in.": "在终端中运行 `copilot` 并登录。",
|
||||
"Run `cursor-agent login` in a terminal.": "在终端中运行 `cursor-agent login`。",
|
||||
"Run `gemini` in a terminal and sign in.": "在终端中运行 `gemini` 并登录。",
|
||||
"Run `goose configure` in a terminal.": "在终端中运行 `goose configure`。",
|
||||
@@ -10628,7 +10627,13 @@
|
||||
"SVG editor layout": "SVG 编辑器布局",
|
||||
"Resize SVG preview": "调整 SVG 预览大小",
|
||||
"The SVG source is not valid.": "SVG 源代码无效。",
|
||||
"Sign In…": "登录…",
|
||||
"Copy command": "复制命令",
|
||||
"Sign In to {name}": "登录 {name}",
|
||||
"Complete sign-in in your browser or the terminal above…": "请在浏览器或上方终端中完成登录…",
|
||||
"Sign-in exited with code {exitCode}.": "登录已退出,代码为 {exitCode}。",
|
||||
"Install GitHub CLI": "安装 GitHub CLI",
|
||||
"Download manually…": "手动下载…",
|
||||
"Show Scratches and Consoles": "显示临时文件和控制台"
|
||||
"Show Scratches and Consoles": "显示临时文件和控制台",
|
||||
"The terminal is not available in this window.": "此窗口中无法使用终端。"
|
||||
}
|
||||
@@ -13,6 +13,17 @@ import { activateSettingsPages as toolsPages } from "./features/tools/settingsPa
|
||||
import { activateSettingsPages as vcsPages } from "./features/vcs/settingsPages";
|
||||
import { activateSettingsPages as vimPages } from "./features/vim/settingsPages";
|
||||
import { activateList } from "./windowBoot";
|
||||
import { provideEmbeddedTerminal } from "./workbench/contributions";
|
||||
|
||||
/** The embedded terminal of the agents' Sign In dialog, loaded on first use. */
|
||||
function embeddedTerminal(): () => void {
|
||||
provideEmbeddedTerminal(async (host, options) =>
|
||||
(await import("./features/terminal/loader"))
|
||||
.loadTerminalRuntime()
|
||||
.then((rt) => rt.createEmbeddedTerminal(host, options)),
|
||||
);
|
||||
return () => provideEmbeddedTerminal(undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Native Settings window of project window `parent`: only the settings pages
|
||||
@@ -28,6 +39,7 @@ export function bootSettingsWindow(parent: string): ComponentType {
|
||||
["plugins", pluginsPages],
|
||||
["tools", toolsPages],
|
||||
["agents", agentsPages],
|
||||
["terminal", embeddedTerminal],
|
||||
["vim", vimPages],
|
||||
["vcs", vcsPages],
|
||||
["github", githubPages],
|
||||
|
||||
Reference in new issue
Заблокувати користувача