diff --git a/crates/ide-agent/src/acp/discover.rs b/crates/ide-agent/src/acp/discover.rs index 5e494be0e3..44c8c2f140 100644 --- a/crates/ide-agent/src/acp/discover.rs +++ b/crates/ide-agent/src/acp/discover.rs @@ -24,7 +24,7 @@ pub(crate) async fn run(shared: &Arc, spec: &ProviderSpec, model: Option match run_once(shared, spec, prefer_stored, model).await { Err(err) if !prefer_stored - && crate::provider::is_copilot_provider(&spec.id) + && crate::provider::is_copilot_provider(spec.base_id()) && crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root) && super::auth_required(0, &err) => { @@ -53,7 +53,7 @@ async fn run_once( .await .map_err(|e| e.to_string())??; let cwd = dunce::canonicalize(&root).unwrap_or(root); - let updates = Arc::new(DiscoveryUpdates { provider: spec.id.clone(), ..Default::default() }); + let updates = Arc::new(DiscoveryUpdates { provider: spec.base_id().to_owned(), ..Default::default() }); let client = Dialect::wrap(updates.clone()); let on_stderr: Box = Box::new(|_| {}); let peer = (shared.connector)(&launch, &cwd, client.clone(), on_stderr) @@ -69,7 +69,7 @@ async fn run_once( .await .map_err(discovery_error)?; let mut options = config::options_of(&new); - config::add_client_options(&launch.id, &mut options); + config::add_client_options(launch.base_id(), &mut options); let model_option = options.iter().find(|o| o.category.as_deref() == Some("model")); let mut levels = BTreeMap::new(); let has_config = new.get("configOptions").is_some_and(Value::is_array); @@ -119,7 +119,7 @@ async fn run_once( .commands .lock() .clone() - .or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, &launch.id))); + .or_else(|| new.get("availableCommands").map(|_| config::commands_of(&new, launch.base_id()))); Ok::<_, String>(Discovered { config: options, commands, levels }) }; let result = tokio::time::timeout(DISCOVER_TIMEOUT, work).await; diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index fca560f85e..a4cce8d2c1 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -680,7 +680,7 @@ async fn discover( Ok(Discovered { commands: Some(config::commands_of( &serde_json::json!({ "availableCommands": found.commands }), - &spec.id, + spec.base_id(), )), config: config::options_of(&serde_json::json!({ "configOptions": found.options })), levels: found @@ -704,7 +704,7 @@ async fn discover( Ok(found) => Ok(Discovered { commands: Some(config::commands_of( &serde_json::json!({ "availableCommands": found.commands }), - &spec.id, + spec.base_id(), )), config: config::options_of(&serde_json::json!({ "configOptions": found.options })), levels: found diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 9eba6c7a65..521f8a1626 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -79,6 +79,12 @@ pub fn login_launch_without_project( .ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))) } +/// The built-in agent `id` is an instance of, or `id` itself, outside a project. +pub fn base_provider_id_without_project(custom_agents_dir: Option<&Path>, id: &str) -> String { + let specs = provider::load(custom_agents_dir, None); + specs.iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned() +} + /// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts. pub async fn copilot_auth_status_with( custom_agents_dir: Option<&Path>, @@ -231,11 +237,13 @@ impl AgentPaths { fn provider_specs(&self) -> Vec { let mut specs = provider::load(self.custom_agents_dir.as_deref(), self.env_secrets.as_deref()); for spec in &mut specs { - if spec.source == AgentSource::Builtin - && let Some(pkg) = cli_update::package(&spec.id) - && let Some(builtin) = provider::builtin_spec(&spec.id) + // An instance launching its base's command shares the base's managed install. + let base = spec.base_id().to_owned(); + if (spec.source == AgentSource::Builtin || spec.base.is_some()) + && let Some(pkg) = cli_update::package(&base) + && let Some(builtin) = provider::builtin_spec(&base) && spec.command == builtin.command - && let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&spec.id), pkg, &spec.command) + && let Some(link) = cli_update::managed_cli(&self.cli_dir.join(&base), pkg, &spec.command) && !provider::installed_with_env(&spec.command, &spec.env) { spec.managed_cli = link.to_str().map(str::to_owned); @@ -397,6 +405,11 @@ impl Shared { self.providers.read().iter().find(|p| p.id == id).cloned() } + /// The built-in id agent `id` is an instance of, or else `id` itself. + fn base_id(&self, id: &str) -> String { + self.providers.read().iter().find(|p| p.id == id).map_or(id, |p| p.base_id()).to_owned() + } + fn env_secrets(&self) -> Option<&dyn EnvSecrets> { self.paths.env_secrets.as_deref() } @@ -420,7 +433,7 @@ impl Shared { async fn probe_network(&self, provider: &str) -> bool { let hook = self.network_probe_hook.read().clone(); - let provider = provider.to_owned(); + let provider = self.base_id(provider); tokio::task::spawn_blocking(move || match hook { Some(hook) => hook(&provider), None => default_network_probe(&provider), @@ -511,7 +524,7 @@ impl Shared { fn config_for_new_task(&self, mut config: Vec, provider: &str) -> Vec { // Model-specific options are offered separately, never as provider-wide defaults. config.retain(|o| !config::is_per_model_option(o)); - config::add_client_options(provider, &mut config); + config::add_client_options(&self.base_id(provider), &mut config); let hook = self.new_task_approvals.read().clone(); if hook.is_some_and(|ask| ask() == ide_core::settings::NewTaskApprovals::Ask) { config::ask_for_approvals(&mut config); @@ -526,8 +539,9 @@ impl Shared { mut levels: BTreeMap>, provider: &str, ) -> BTreeMap> { + let base = self.base_id(provider); for options in levels.values_mut() { - config::apply_model_defaults(provider, options); + config::apply_model_defaults(&base, options); } levels } @@ -1306,10 +1320,20 @@ impl AgentManager { /// The agents (custom ones re-read), whether each is installed, and what they offered last time. pub fn providers(&self) -> Vec { let specs = self.shared.paths.provider_specs(); + { + let mut prev = self.shared.providers.write(); + let mut probes = self.shared.probes.lock(); + probes.retain(|id, _| { + let old = prev.iter().find(|p| &p.id == id); + let new = specs.iter().find(|p| &p.id == id); + matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env) + }); + *prev = specs.clone(); + } let in_use: std::collections::HashSet = 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 + specs .iter() .filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id)) .map(|p| { @@ -1329,19 +1353,12 @@ impl AgentManager { info.commands = self.shared.known_commands(&p.id); info }) - .collect(); - drop(terminal_auth); - let mut prev = self.shared.providers.write(); - let mut probes = self.shared.probes.lock(); - probes.retain(|id, _| { - let old = prev.iter().find(|p| &p.id == id); - let new = specs.iter().find(|p| &p.id == id); - matches!((old, new), (Some(a), Some(b)) if a.executable() == b.executable() && a.args == b.args && a.env == b.env) - }); - *prev = specs.clone(); - drop(probes); - drop(prev); - list + .collect() + } + + /// The built-in id agent `id` is an instance of, or else `id` itself. + pub fn base_provider_id(&self, id: &str) -> String { + self.shared.base_id(id) } /// Resolves the interactive sign-in command for agent `id`. @@ -1386,7 +1403,7 @@ impl AgentManager { provider::set_builtin_additional_args(dir, self.shared.env_secrets(), id, args) } - /// Sets the environment variables built-in `id` starts with; empty clears them. + /// Sets the environment variables built-in `id` (or an instance of one) starts with; empty clears them. pub fn set_builtin_env(&self, id: &str, env: std::collections::BTreeMap) -> IdeResult<()> { let Some(dir) = self.shared.paths.custom_agents_dir.clone() else { return Err(IdeError::unavailable("there is no custom agents directory")); @@ -1396,12 +1413,14 @@ impl AgentManager { Ok(()) } - /// Saves a new custom ACP agent through its agent file. + /// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent file. pub fn save_custom_agent(&self, input: CustomAgentInput) -> IdeResult<()> { let Some(dir) = self.shared.paths.custom_agents_dir.clone() else { return Err(IdeError::unavailable("there is no custom agents directory")); }; - provider::save_custom(&dir, self.shared.env_secrets(), &input) + provider::save_custom(&dir, self.shared.env_secrets(), &input)?; + *self.shared.providers.write() = self.shared.paths.provider_specs(); + Ok(()) } /// Removes a custom agent's file (registry installs go through `registry_remove`). @@ -1409,7 +1428,10 @@ impl AgentManager { let Some(dir) = self.shared.paths.custom_agents_dir.clone() else { return Err(IdeError::unavailable("there is no custom agents directory")); }; - provider::remove_custom(&dir, self.shared.env_secrets(), id) + provider::remove_custom(&dir, self.shared.env_secrets(), id)?; + *self.shared.providers.write() = self.shared.paths.provider_specs(); + self.shared.paths.catalogs.evict_if_idle(&self.shared, id); + Ok(()) } /// Imports a JetBrains `acp.json` file's `agent_servers` entries as custom agents. @@ -1490,23 +1512,26 @@ impl AgentManager { } offered = self.shared.known_commands(&provider); } - for command in builtin_commands(&provider) { + let base_id = self.shared.base_id(&provider); + for command in builtin_commands(&base_id) { if !offered.iter().any(|c| c.name == command.name) { offered.push(command); } } let home = self.shared.paths.home_dir.clone(); - if provider == "hermes" || provider.starts_with("hermes-") { + if base_id == "hermes" || provider.starts_with("hermes-") { let hermes_home = home.clone(); let hermes_provider = provider.clone(); + let hermes_base = base_id.clone(); let found = blocking(move || { - let profile = - hermes::root(hermes_home.as_deref()).and_then(|root| hermes::profile_home(&root, &hermes_provider)); + let profile = hermes::root(hermes_home.as_deref()).and_then(|root| { + hermes::profile_home(&root, &hermes_provider).or_else(|| hermes::profile_home(&root, &hermes_base)) + }); Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default()) }) .await?; offered = skills::merge(offered, found); - } else if provider == "claude" || provider == "claude-acp" { + } else if base_id == "claude" || base_id == "claude-acp" { let claude_cwd = cwd.clone(); let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?; offered = skills::merge(offered, found); @@ -1527,7 +1552,7 @@ impl AgentManager { let plugin_dirs = policy.plugin_dirs; let indexed_skill_files = policy.indexed_skill_files; let home = self.shared.paths.home_dir.clone(); - let cmd_provider = provider.clone(); + let cmd_provider = base_id.clone(); blocking(move || { let mut p_pol = plug_policy; if p_pol.workspace_roots.is_empty() { @@ -1896,7 +1921,7 @@ impl AgentManager { .map(|h| h()) .unwrap_or(ide_core::settings::NewTaskApprovals::Bypass); let mode = Some(meta.permissions.unwrap_or_default()); - config::clamp_automation_permissions(&spec.id, mode, interactive, &mut config, &mut wanted); + config::clamp_automation_permissions(spec.base_id(), mode, interactive, &mut config, &mut wanted); } let now = now_ms(); // Copies of the files the user had changed already, for rolling back the task's changes to them. @@ -2329,10 +2354,16 @@ impl AgentManager { let epoch = self.shared.shutdown_epoch(); // A Codex fork must be opened by its own task: the creating app-server owns its writer. // It can also fork a recorded thread whose writer is held by another process. - let codex_source = { + let (source_provider, source_session) = { let s = source.state.lock(); - (s.task.provider == "codex").then(|| s.session_id.clone()).flatten() + (s.task.provider.clone(), s.session_id.clone()) }; + let codex_source = source + .shared + .spec(&source_provider) + .is_some_and(|spec| spec.driver == provider::Driver::Codex) + .then_some(source_session) + .flatten(); let live = if codex_source.is_none() { Some(source.ensure_session(epoch).await.map_err(IdeError::internal)?) } else { @@ -2354,10 +2385,11 @@ impl AgentManager { let t = &s.task; (t.cwd.0.clone(), t.provider.clone(), t.mcp_overrides.clone(), t.project_root.clone().map(|p| p.0)) }; - let mcp_servers = source.shared.mcp_servers_for_session(&provider_id, &live.init, &mcp_overrides, None); + let base_id = source.shared.base_id(&provider_id); + let mcp_servers = source.shared.mcp_servers_for_session(&base_id, &live.init, &mcp_overrides, None); let roots = source.shared.additional_directories(&live.init, &cwd, project_root.as_deref()); let skills_delivery = source.stage_skills(stage_key(live.driver), &cwd).await; - let memory_delivery = source.stage_memory(&provider_id, &cwd).await; + let memory_delivery = source.stage_memory(&base_id, &cwd).await; let cwd_s = dunce::canonicalize(&cwd).unwrap_or(cwd).to_string_lossy().into_owned(); let reply: Value = live .peer @@ -3897,7 +3929,7 @@ impl Task { /// The task from the parts of `file` other than its history, which `history` holds. fn assemble(file: TaskFile, history: StoredHistory, adopt: bool, shared: Arc) -> Arc { let mut task = file.task; - config::add_client_options(&task.provider, &mut task.config); + config::add_client_options(&shared.base_id(&task.provider), &mut task.config); let mut wanted = file.wanted; let mut pending_model = file.pending_switch.or_else(|| { let id = file.pending_model?; @@ -4500,7 +4532,11 @@ impl Task { .as_ref() .map(|h| h()) .unwrap_or(ide_core::settings::NewTaskApprovals::Bypass); - let (provider, mut non_approval_choices) = { + let base = { + let provider = self.state.lock().task.provider.clone(); + self.shared.base_id(&provider) + }; + let mut non_approval_choices = { let mut s = self.state.lock(); let model_opt_id = s.task.config.iter().find(|o| o.category.as_deref() == Some("model")).map(|o| o.id.clone()); @@ -4521,10 +4557,9 @@ impl Task { s.wanted.push(choice.clone()); } } - let provider = s.task.provider.clone(); let mut target_config = s.task.config.clone(); let mut target_wanted = s.wanted.clone(); - config::clamp_automation_permissions(&provider, mode, interactive, &mut target_config, &mut target_wanted); + config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted); s.wanted = target_wanted; let non_approval: Vec = extra_choices .iter() @@ -4535,7 +4570,7 @@ impl Task { }) .cloned() .collect(); - (provider, non_approval) + non_approval }; self.persist(); @@ -4608,13 +4643,7 @@ impl Task { let mut s = self.state.lock(); let mut target_config = s.task.config.clone(); let mut target_wanted = s.wanted.clone(); - config::clamp_automation_permissions( - &provider, - mode, - interactive, - &mut target_config, - &mut target_wanted, - ); + config::clamp_automation_permissions(&base, mode, interactive, &mut target_config, &mut target_wanted); let mut diffs = Vec::new(); for next_opt in &target_config { let prev_cur = @@ -4655,7 +4684,7 @@ impl Task { } } let current_cfg = self.state.lock().task.config.clone(); - config::verify_automation_ceiling(&provider, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?; + config::verify_automation_ceiling(&base, mode, interactive, ¤t_cfg).map_err(IdeError::invalid)?; self.approve_pending(); self.persist(); self.emit_task(); @@ -4982,10 +5011,11 @@ impl Task { } fn cursor_at_capacity(&self, result: &Result) -> bool { - let s = self.state.lock(); - if s.task.provider != "cursor" { + let provider = self.state.lock().task.provider.clone(); + if self.shared.base_id(&provider) != "cursor" { return false; } + let s = self.state.lock(); matches!(result, Ok(stop) if stop == "end_turn") && matches!( s.history.conversation.main.entries.last(), @@ -5307,11 +5337,13 @@ impl Task { /// Adds `prompt` to the running turn when the agent takes that; gives it back otherwise. async fn steer(self: &Arc, prompt: AgentPrompt) -> Result<(), AgentPrompt> { let live = self.live.lock().clone().filter(|l| l.capabilities.steer && !l.peer.is_closed()); + let provider = self.state.lock().task.provider.clone(); + let cursor = self.shared.base_id(&provider) == "cursor"; let running = { let s = self.state.lock(); // During Cursor backoff the ACP turn has already ended. Send Now must // cancel the wait and dispatch the new prompt as a turn of its own. - s.busy && s.task.status == AgentStatus::Running && !(s.task.provider == "cursor" && s.task.retry.is_some()) + s.busy && s.task.status == AgentStatus::Running && !(cursor && s.task.retry.is_some()) }; let Some((live, method)) = live .filter(|l| running && (prompt.images.is_empty() || l.capabilities.images)) @@ -5563,11 +5595,13 @@ impl Task { if self.recorded_load_started.load(Ordering::Acquire) || !self.adopts_replay() || self.live.lock().is_some() { return false; } + let provider = self.state.lock().task.provider.clone(); + let base = self.shared.base_id(&provider); let s = self.state.lock(); !s.busy && s.session_id.is_some() && s.pending_native_fork.is_none() - && RECORDED_SESSION_AGENTS.contains(&s.task.provider.as_str()) + && RECORDED_SESSION_AGENTS.contains(&base.as_str()) } /// Opens the recorded session in the background, once per run: its replay shows the history @@ -5669,6 +5703,7 @@ impl Task { .map_err(|e| SessionOpenError { message: e.to_string(), allow_acp_fallback: false })?; let cwd = verified_cwd.as_path(); let launch_cwd = cwd.to_path_buf(); + let base_id = spec.base_id().to_owned(); let mut spec = tokio::task::spawn_blocking(move || { spec.resolve_for_launch_with_copilot_env(&launch_cwd, provider::prefer_stored_copilot_auth()) }) @@ -5678,10 +5713,10 @@ impl Task { if self.shared.shut_down_since(epoch) { return Err(SessionOpenError { message: "The agent manager shut down.".into(), allow_acp_fallback: false }); } - let memory_delivery = self.stage_memory(provider_id, cwd).await; - if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(provider_id) { + let memory_delivery = self.stage_memory(&base_id, cwd).await; + if spec.driver == provider::Driver::Acp && provider::is_copilot_provider(&base_id) { let mcp_overrides = self.state.lock().task.mcp_overrides.clone(); - for name in self.shared.mcp_servers_off_for_session(provider_id, &mcp_overrides) { + for name in self.shared.mcp_servers_off_for_session(&base_id, &mcp_overrides) { spec.args.push("--disable-mcp-server".into()); spec.args.push(name); } @@ -5757,7 +5792,7 @@ impl Task { }) }; let mcp_servers = self.shared.mcp_servers_for_session( - provider_id, + &base_id, &init, &mcp_overrides, mcp_nonce.as_ref().map(|g| g.nonce.as_str()), @@ -5959,7 +5994,7 @@ impl Task { let effective_perm_mode = sched_perm.unwrap_or(auto_perm); (options, wanted, ceiling_active, effective_perm_mode) }; - config::add_client_options(provider_id, &mut options); + config::add_client_options(&base_id, &mut options); let interactive = self .shared .new_task_approvals @@ -5971,13 +6006,7 @@ impl Task { // Compute clamped choices on a scratch copy of `options` so `options[i].current` still // reflects what the CLI reported and the `wanted` loop below sends any needed downgrade! let mut scratch = options.clone(); - config::clamp_automation_permissions( - provider_id, - effective_perm_mode, - interactive, - &mut scratch, - &mut wanted, - ); + config::clamp_automation_permissions(&base_id, effective_perm_mode, interactive, &mut scratch, &mut wanted); } // Changing model can replace the effort / context-tier choices; validate those only afterwards. wanted.sort_by_key(|c| { @@ -6094,7 +6123,7 @@ impl Task { } } if ceiling_active { - config::verify_automation_ceiling(provider_id, effective_perm_mode, interactive, &options) + config::verify_automation_ceiling(&base_id, effective_perm_mode, interactive, &options) .map_err(|message| SessionOpenError { message, allow_acp_fallback: false })?; } if self.shared.shut_down_since(epoch) { @@ -6327,6 +6356,7 @@ impl Task { } // Session state (also while `session/load` replays history). let provider = self.state.lock().task.provider.clone(); + let base = self.shared.base_id(&provider); let task_changed = { let mut s = self.state.lock(); match kind { @@ -6344,7 +6374,7 @@ impl Task { true } "available_commands_update" => { - s.task.commands = config::commands_of(update, &provider); + s.task.commands = config::commands_of(update, &base); true } "usage_update" => { diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index a912535828..9ac321e761 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -769,6 +769,12 @@ pub struct AgentProvider { /// The built-in command can be owned by a global npm package. #[serde(default)] pub can_check_cli_update: bool, + /// The built-in agent this one is an instance of. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, + /// A built-in agent, of which another instance can be added. + #[serde(default)] + pub can_duplicate: bool, /// Environment variables it starts with (from its agent file). pub env: BTreeMap, /// Settings (models, modes…) the agent offered last time it ran; empty before its first session. @@ -1876,13 +1882,16 @@ pub struct McpProbeResult { pub error: Option, } -/// Payload for creating a custom ACP agent (always the ACP driver); the id -/// becomes the `/agents/.toml` file name. +/// Payload for creating a custom ACP agent, or an instance of built-in `base` (which +/// launches as its base does when `command` is empty); the id becomes the +/// `/agents/.toml` file name. #[derive(Clone, Debug, Deserialize, Type)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct CustomAgentInput { pub id: String, pub name: String, + #[serde(default)] + pub base: Option, pub command: String, #[serde(default)] pub args: Vec, diff --git a/crates/ide-agent/src/native/codex/tests.rs b/crates/ide-agent/src/native/codex/tests.rs index 34dc9ce5dc..a558f22bfa 100644 --- a/crates/ide-agent/src/native/codex/tests.rs +++ b/crates/ide-agent/src/native/codex/tests.rs @@ -131,6 +131,7 @@ for line in sys.stdin: env: Vec::new(), login_hint: String::new(), source: crate::AgentSource::Builtin, + base: None, }; let found = discover(spec, tmp.path().to_path_buf()).await.unwrap(); let models: Vec<_> = found diff --git a/crates/ide-agent/src/provider.rs b/crates/ide-agent/src/provider.rs index 6ff2db54e7..58a531fe9b 100644 --- a/crates/ide-agent/src/provider.rs +++ b/crates/ide-agent/src/provider.rs @@ -43,6 +43,8 @@ pub(crate) struct ProviderSpec { /// How to sign in when the agent reports it needs authentication. pub login_hint: String, pub source: AgentSource, + /// The built-in agent an instance copies (its identity); `None` for every other agent. + pub base: Option, } /// `(id, name, driver, command line, sign-in hint)`. npm adapters are pinned so a @@ -108,11 +110,17 @@ fn builtins() -> Vec { env: Vec::new(), login_hint: (*hint).into(), source: AgentSource::Builtin, + base: None, }) .collect() } impl ProviderSpec { + /// The built-in id this agent is an instance of, or else its own id. + pub(crate) fn base_id(&self) -> &str { + self.base.as_deref().unwrap_or(&self.id) + } + pub(crate) fn executable(&self) -> &str { self.managed_cli.as_deref().unwrap_or(&self.command) } @@ -122,7 +130,7 @@ impl ProviderSpec { return self.login_hint.clone(); } let search = ide_core::tool_path::search_path(); - let builtin = builtin_spec(&self.id); + let builtin = builtin_spec(self.base_id()); let on_path = builtin.as_ref().and_then(|b| ide_core::process::find_executable(&b.command, &search)); render_login_hint(self, program, on_path.as_deref(), cfg!(windows)) } @@ -161,7 +169,7 @@ impl ProviderSpec { cwd: &Path, strip_ambient_tokens: bool, ) -> Result { - let is_copilot = is_copilot_provider(&self.id); + let is_copilot = is_copilot_provider(self.base_id()); let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten(); let explicit_copilot_token = self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty()); @@ -191,7 +199,7 @@ impl ProviderSpec { } else if self.driver != Driver::Acp { self.command = crate::native::newest_install(&self.command); } - if is_copilot_provider(&self.id) { + if is_copilot_provider(self.base_id()) { self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens); self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV); } @@ -217,7 +225,7 @@ impl ProviderSpec { ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd) }; - if let Some((separate_cmd, separate_args)) = match self.id.as_str() { + if let Some((separate_cmd, separate_args)) = match self.base_id() { "claude-acp" => Some(("claude", &[][..])), "codex-acp" => Some(("codex", &["login"][..])), "vibe" => Some(("vibe", &[][..])), @@ -231,7 +239,7 @@ impl ProviderSpec { }); } - if let Some(builtin) = builtin_spec(&self.id) + if let Some(builtin) = builtin_spec(self.base_id()) && !(matches!(self.source, AgentSource::Registry { .. }) && registry_uses_separate_binary(&self.id)) { let args = terminal_auth_args @@ -241,7 +249,7 @@ impl ProviderSpec { let resolved = self.clone().resolve_for_launch_base(cwd, true); let program = resolve_exe(&resolved.command, &resolved.env)?; let mut env: BTreeMap = resolved.env.into_iter().collect(); - if is_copilot_provider(&self.id) { + if is_copilot_provider(self.base_id()) { for key in AMBIENT_COPILOT_AUTH_VARS { env.insert(key.to_owned(), String::new()); } @@ -532,7 +540,7 @@ pub(crate) fn sanitize_copilot_env_with( } fn render_login_hint(spec: &ProviderSpec, program: &Path, on_path: Option<&Path>, windows: bool) -> String { - let Some(builtin) = builtin_spec(&spec.id) else { return spec.login_hint.clone() }; + let Some(builtin) = builtin_spec(spec.base_id()) else { return spec.login_hint.clone() }; let prefix = format!("Run `{}", builtin.command); let Some(rest) = spec.login_hint.strip_prefix(&prefix).filter(|rest| rest.starts_with([' ', '`'])) else { return spec.login_hint.clone(); @@ -620,6 +628,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider { let builtin = builtin_spec(&spec.id); let reason = if matches!(spec.source, AgentSource::Registry { .. }) { Some(AgentCommandReadOnlyReason::Registry) + } else if spec.base.is_some() { + Some(AgentCommandReadOnlyReason::CustomAgent) } else if let Some(default) = &builtin { uses_package_runner(&default.command).then_some(AgentCommandReadOnlyReason::PackageRunner) } else { @@ -649,6 +659,8 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider { cli_install_command: None, 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(), + base: spec.base.clone(), + can_duplicate: builtin.is_some(), env: spec.env.iter().cloned().collect(), config: vec![], thought_levels: BTreeMap::new(), @@ -687,13 +699,17 @@ pub(crate) fn set_builtin_additional_args( }) } -/// The environment built-in `id` starts with, through its agent file (empty clears it). +/// The environment built-in `id` (or an instance of one) starts with, through its agent file +/// (empty clears it). pub(crate) fn set_builtin_env( custom_dir: &Path, secrets: Option<&dyn EnvSecrets>, id: &str, env: BTreeMap, ) -> IdeResult<()> { + if builtin_spec(id).is_none() { + return set_instance_env(custom_dir, secrets, id, env); + } if id == "copilot" { let file = custom_dir.join("copilot.toml"); if file.try_exists()? @@ -725,6 +741,26 @@ pub(crate) fn set_builtin_env( }) } +/// An instance's environment is all its own: never merged with its base's. +fn set_instance_env( + custom_dir: &Path, + secrets: Option<&dyn EnvSecrets>, + id: &str, + env: BTreeMap, +) -> IdeResult<()> { + let id = validated_custom_id(id)?; + let _lock = lock_custom_agents(custom_dir)?; + let file = custom_dir.join(format!("{id}.toml")); + let mut agent = match CustomAgent::read_with(&file, &id, secrets) { + Ok(agent) if agent.registry.is_none() && agent.base.as_deref().is_some_and(|b| builtin_spec(b).is_some()) => { + agent + } + _ => return Err(IdeError::invalid(format!("{id} is not a built-in agent or an instance of one"))), + }; + agent.env = env; + agent.write_with(&file, &id, secrets) +} + /// Changes built-in `id`'s agent file; a file left with only the built-in's values is removed. fn update_builtin( custom_dir: &Path, @@ -741,6 +777,7 @@ fn update_builtin( } else { CustomAgent { name: Some(builtin.name.clone()), + base: None, driver: builtin.driver, command: builtin.command.clone(), args: builtin.args.clone(), @@ -786,7 +823,8 @@ fn lock_custom_agents(custom_dir: &Path) -> std::io::Result { /// Saves a new custom agent; refuses built-in and ACP Registry ids, taken ids /// and an empty command. The id is also the agent file's name, so it must be -/// a safe file stem. +/// a safe file stem. An instance of a built-in (`base`) may leave the command +/// empty to launch as its base does. pub(crate) fn save_custom( custom_dir: &Path, secrets: Option<&dyn EnvSecrets>, @@ -796,9 +834,19 @@ pub(crate) fn save_custom( if builtin_spec(&id).is_some() { return Err(IdeError::invalid(format!("{id} is a built-in agent; change its command instead"))); } - if input.command.trim().is_empty() { + let base = match input.base.as_deref() { + Some(base) => { + Some(builtin_spec(base).ok_or_else(|| IdeError::invalid(format!("{base} is not a built-in agent")))?) + } + None => None, + }; + let inherits = input.command.trim().is_empty(); + if inherits && base.is_none() { return Err(IdeError::invalid("the agent command must not be empty")); } + if inherits && !input.args.is_empty() { + return Err(IdeError::invalid("an agent without its own command takes no arguments")); + } let _lock = lock_custom_agents(custom_dir)?; let file = custom_dir.join(format!("{id}.toml")); if file.try_exists()? { @@ -811,8 +859,9 @@ pub(crate) fn save_custom( } CustomAgent { name: Some(input.name.clone()), - driver: Driver::Acp, - command: input.command.clone(), + driver: base.as_ref().filter(|_| !inherits).map_or(Driver::Acp, |b| b.driver), + command: if inherits { String::new() } else { input.command.clone() }, + base: base.map(|b| b.id), args: input.args.clone(), additional_args: Vec::new(), env: input.env.clone(), @@ -884,6 +933,7 @@ pub(crate) fn import_acp( } else { CustomAgent { name: Some(outcome.name.clone()), + base: None, driver: Driver::Acp, command: server.command, args: server.args, @@ -926,8 +976,12 @@ pub(crate) fn slugify_id(name: &str) -> String { pub(crate) struct CustomAgent { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option, + /// The built-in agent this one is an instance of; without a `command` it launches as the base does. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base: Option, #[serde(default, skip_serializing_if = "Driver::is_acp")] pub driver: Driver, + #[serde(default, skip_serializing_if = "String::is_empty")] pub command: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub args: Vec, @@ -956,9 +1010,13 @@ impl Driver { impl CustomAgent { pub(crate) fn read(path: &Path) -> Result { - std::fs::read_to_string(path) + let agent = std::fs::read_to_string(path) .map_err(|e| e.to_string()) - .and_then(|t| toml::from_str::(&t).map_err(|e| e.to_string())) + .and_then(|t| toml::from_str::(&t).map_err(|e| e.to_string()))?; + if agent.command.is_empty() && agent.base.is_none() { + return Err("missing field `command`".into()); + } + Ok(agent) } /// Writes the file atomically (a reader never sees half of it). @@ -1030,7 +1088,8 @@ fn forget_env(secrets: Option<&dyn EnvSecrets>, id: &str, keep: &[String]) { } /// Built-in agents, then the `*.toml` agents of `custom_dir`; a custom agent with a -/// built-in id replaces it. +/// built-in id replaces it. Instances of a built-in (`base`) are resolved last, against +/// the built-in as its own file left it, so file order does not matter. pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) -> Vec { let mut specs = builtins(); let mut files: Vec = custom_dir @@ -1042,6 +1101,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) .filter(|p| p.extension().is_some_and(|e| e == "toml")) .collect(); files.sort(); + let mut instances = Vec::new(); for path in files { let Some(id) = path.file_stem().and_then(|s| s.to_str()).map(str::to_owned) else { continue }; let explicit_driver = std::fs::read_to_string(&path) @@ -1055,6 +1115,18 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) continue; } }; + if let Some(base) = agent.base.clone() { + if builtin_spec(&id).is_some() { + tracing::warn!("skipping agent {}: a built-in agent cannot have a base", path.display()); + } else if agent.registry.is_some() { + tracing::warn!("skipping agent {}: an ACP Registry install cannot have a base", path.display()); + } else if builtin_spec(&base).is_none() { + tracing::warn!("skipping agent {}: {base} is not a built-in agent", path.display()); + } else { + instances.push((id, agent)); + } + continue; + } let env: Vec<(String, String)> = agent.env.into_iter().collect(); let source = match agent.registry { Some(r) => AgentSource::Registry { version: r.version, update: None }, @@ -1070,6 +1142,7 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) env, login_hint: "Sign in with the agent's own command line first.".into(), source, + base: None, id, }; match specs.iter_mut().find(|s| s.id == spec.id) { @@ -1097,6 +1170,34 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>) None => specs.push(spec), } } + for (id, agent) in instances { + let base = agent.base.expect("instances have a base"); + let Some(base_spec) = specs.iter().find(|s| s.id == base && s.base.is_none()) else { continue }; + let (driver, command, args) = if agent.command.is_empty() { + (base_spec.driver, base_spec.command.clone(), base_spec.args.clone()) + } else { + (agent.driver, agent.command, agent.args) + }; + let login_hint = base_spec.login_hint.clone(); + // Copies of one agent follow it, in the order of their file names. + let at = specs.iter().rposition(|s| s.base_id() == base).map_or(specs.len(), |i| i + 1); + specs.insert( + at, + ProviderSpec { + name: agent.name.unwrap_or_else(|| id.clone()), + driver, + command, + managed_cli: None, + args, + additional_args_len: 0, + env: agent.env.into_iter().collect(), + login_hint, + source: AgentSource::Custom, + base: Some(base), + id, + }, + ); + } specs } @@ -1169,6 +1270,7 @@ mod tests { } CustomAgent { name: Some("Google Antigravity".into()), + base: None, driver: Driver::Acp, command: bin.to_string_lossy().into_owned(), args: Vec::new(), @@ -1509,6 +1611,7 @@ mod tests { let file = dir.path().join("copilot.toml"); CustomAgent { name: Some("GitHub Copilot".into()), + base: None, driver: Driver::Acp, command: "/tools/copilot".into(), args: vec!["--acp".into()], @@ -1566,6 +1669,7 @@ mod tests { let path = dir.path().join("codex.toml"); CustomAgent { name: None, + base: None, driver: Driver::Acp, command: "amp".into(), args: vec![], @@ -1592,6 +1696,7 @@ mod tests { for field in ["name", "driver", "args", "env", "unnamed"] { let mut agent = CustomAgent { name: Some("Claude Code".into()), + base: None, driver: Driver::Claude, command: "/old/claude".into(), args: vec![], @@ -1646,6 +1751,7 @@ mod tests { let path = dir.path().join("agents").join("amp-acp.toml"); let agent = CustomAgent { name: Some("Amp".into()), + base: None, driver: Driver::Acp, command: "/data/agents/tools/amp-acp/0.10.0/amp-acp".into(), args: vec!["acp".into()], @@ -1666,6 +1772,7 @@ mod tests { CustomAgentInput { id: id.into(), name: "Mine".into(), + base: None, command: "/opt/mine".into(), args: vec!["acp".into()], env: BTreeMap::from([("K".to_owned(), "v".to_owned())]), @@ -1887,4 +1994,188 @@ github.com 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("")); } + + fn write_agent(dir: &Path, id: &str, text: &str) { + std::fs::write(dir.join(format!("{id}.toml")), text).unwrap(); + } + + fn spec_of(dir: &Path, id: &str) -> Option { + load(Some(dir), None).into_iter().find(|s| s.id == id) + } + + #[test] + fn instances_inherit_the_base_launch_whatever_the_file_order() { + let dir = tempfile::tempdir().unwrap(); + let instance = + "base = \"claude\"\nname = \"Claude Work\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n"; + // `a-claude` sorts before the base's own file, `z-claude` after it. + write_agent(dir.path(), "a-claude", instance); + write_agent(dir.path(), "z-claude", instance); + write_agent( + dir.path(), + "claude", + "name = \"Claude Code\"\ndriver = \"claude\"\ncommand = \"/opt/claude\"\n[env]\nB = \"1\"\n", + ); + let builtin = builtin_spec("claude").unwrap(); + for id in ["a-claude", "z-claude"] { + let spec = spec_of(dir.path(), id).unwrap(); + assert_eq!((spec.driver, spec.command.as_str()), (Driver::Claude, "/opt/claude"), "{id}"); + assert_eq!(spec.args, builtin.args); + assert_eq!(spec.env, [("CLAUDE_CONFIG_DIR".to_owned(), "/home/me/.claude-work".to_owned())]); + assert_eq!(spec.login_hint, builtin.login_hint); + assert_eq!( + (&spec.source, spec.base.as_deref(), spec.base_id()), + (&AgentSource::Custom, Some("claude"), "claude") + ); + assert_eq!(spec.name, "Claude Work"); + } + std::fs::remove_file(dir.path().join("claude.toml")).unwrap(); + assert_eq!(spec_of(dir.path(), "a-claude").unwrap().command, "claude"); + } + + #[test] + fn instances_follow_their_base_in_the_list() { + let dir = tempfile::tempdir().unwrap(); + write_agent(dir.path(), "z-claude", "base = \"claude\"\n"); + write_agent(dir.path(), "a-claude", "base = \"claude\"\n"); + write_agent(dir.path(), "codex-2", "base = \"codex\"\n"); + write_agent(dir.path(), "mine", "command = \"/opt/mine\"\n"); + let ids: Vec = load(Some(dir.path()), None).into_iter().map(|s| s.id).collect(); + let at = |id: &str| ids.iter().position(|i| i == id).unwrap(); + assert_eq!((at("a-claude"), at("z-claude")), (at("claude") + 1, at("claude") + 2)); + assert_eq!(at("codex-2"), at("codex") + 1); + assert_eq!(at("mine"), ids.len() - 1); + } + + #[test] + fn an_instance_with_its_own_command_keeps_it() { + let dir = tempfile::tempdir().unwrap(); + write_agent( + dir.path(), + "codex-2", + "base = \"codex\"\ndriver = \"codex\"\ncommand = \"/opt/codex2\"\nargs = [\"app-server\", \"-v\"]\n", + ); + write_agent(dir.path(), "codex", "driver = \"codex\"\ncommand = \"/opt/codex\"\nargs = [\"app-server\"]\n"); + let spec = spec_of(dir.path(), "codex-2").unwrap(); + assert_eq!((spec.driver, spec.command.as_str()), (Driver::Codex, "/opt/codex2")); + assert_eq!(spec.args, ["app-server", "-v"]); + assert_eq!(spec.base.as_deref(), Some("codex")); + assert_eq!(spec.login_hint, builtin_spec("codex").unwrap().login_hint); + } + + #[test] + fn invalid_instances_are_skipped() { + let dir = tempfile::tempdir().unwrap(); + write_agent(dir.path(), "unknown-base", "base = \"nope\"\n"); + write_agent(dir.path(), "first", "base = \"claude\"\n"); + write_agent(dir.path(), "chained", "base = \"first\"\n"); + write_agent(dir.path(), "codex", "base = \"claude\"\n"); + write_agent(dir.path(), "no-command", "name = \"Nothing\"\n"); + let specs = load(Some(dir.path()), None); + let ids: Vec<&str> = specs.iter().filter(|s| s.source != AgentSource::Builtin).map(|s| s.id.as_str()).collect(); + assert_eq!(ids, ["first"]); + assert_eq!(specs.iter().find(|s| s.id == "codex").unwrap(), &builtin_spec("codex").unwrap()); + } + + #[test] + fn save_custom_writes_instances() { + let dir = tempfile::tempdir().unwrap(); + let instance = |id: &str, base: &str| CustomAgentInput { + base: Some(base.into()), + command: String::new(), + args: Vec::new(), + ..custom_input(id) + }; + save_custom(dir.path(), None, &instance("work", "claude")).unwrap(); + let text = std::fs::read_to_string(dir.path().join("work.toml")).unwrap(); + assert!(text.contains("base = \"claude\"") && !text.contains("command") && !text.contains("driver"), "{text}"); + let spec = spec_of(dir.path(), "work").unwrap(); + assert_eq!( + (spec.driver, spec.command.as_str(), spec.base.as_deref()), + (Driver::Claude, "claude", Some("claude")) + ); + + save_custom(dir.path(), None, &CustomAgentInput { command: "/opt/codex".into(), ..instance("own", "codex") }) + .unwrap(); + let own = spec_of(dir.path(), "own").unwrap(); + assert_eq!((own.driver, own.command.as_str()), (Driver::Codex, "/opt/codex")); + + save_custom(dir.path(), None, &instance("work", "claude")).unwrap_err(); + save_custom(dir.path(), None, &instance("other", "nope")).unwrap_err(); + save_custom(dir.path(), None, &instance("other", "work")).unwrap_err(); + save_custom(dir.path(), None, &instance("codex", "claude")).unwrap_err(); + save_custom(dir.path(), None, &CustomAgentInput { args: vec!["x".into()], ..instance("other", "claude") }) + .unwrap_err(); + assert!(!dir.path().join("other.toml").exists()); + } + + #[test] + fn instances_describe_their_base() { + let dir = tempfile::tempdir().unwrap(); + write_agent(dir.path(), "work", "base = \"claude\"\n"); + save_custom(dir.path(), None, &custom_input("mine")).unwrap(); + let info = |id: &str| describe(&spec_of(dir.path(), id).unwrap()); + let work = info("work"); + assert_eq!(work.base.as_deref(), Some("claude")); + assert!(!work.can_duplicate && !work.can_check_cli_update && !work.command_editable); + assert_eq!(work.command_read_only_reason, Some(AgentCommandReadOnlyReason::CustomAgent)); + assert_eq!(work.login_hint.as_deref(), Some("Run `claude` in a terminal and sign in.")); + let claude = info("claude"); + assert!(claude.can_duplicate && claude.base.is_none()); + let mine = info("mine"); + assert!(!mine.can_duplicate && mine.base.is_none()); + } + + #[cfg(unix)] + #[test] + fn instances_sign_in_with_their_own_environment() { + use std::os::unix::fs::PermissionsExt; + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("claude"); + std::fs::write(&bin, "#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); + write_agent(dir.path(), "claude", &format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy())); + write_agent(dir.path(), "work", "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"/home/me/.claude-work\"\n"); + let spec = spec_of(dir.path(), "work").unwrap(); + assert!(spec.can_sign_in(dir.path(), None)); + let launch = spec.login_launch(dir.path(), None).unwrap(); + assert_eq!(launch.program, bin); + assert!(launch.args.is_empty()); + assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work")); + } + + #[test] + fn instance_environment_is_set_and_forgotten_through_the_secrets() { + let dir = tempfile::tempdir().unwrap(); + let secrets = MemorySecrets::default(); + let s = Some(&secrets as &dyn EnvSecrets); + let instance = CustomAgentInput { + base: Some("copilot".into()), + command: String::new(), + args: Vec::new(), + env: BTreeMap::new(), + ..custom_input("copilot-work") + }; + save_custom(dir.path(), s, &instance).unwrap(); + let env = BTreeMap::from([ + (COPILOT_GITHUB_ACCOUNT_ENV.to_owned(), "octo-work".to_owned()), + ("COPILOT_HOME".to_owned(), "/home/me/.copilot-work".to_owned()), + ]); + set_builtin_env(dir.path(), s, "copilot-work", env.clone()).unwrap(); + let text = std::fs::read_to_string(dir.path().join("copilot-work.toml")).unwrap(); + assert!(text.contains("base = \"copilot\"") && !text.contains("octo-work"), "{text}"); + let spec = load(Some(dir.path()), s).into_iter().find(|p| p.id == "copilot-work").unwrap(); + assert_eq!(describe(&spec).env, env); + assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("octo-work")); + assert!(load(Some(dir.path()), s).iter().find(|p| p.id == "copilot").unwrap().env.is_empty()); + + save_custom(dir.path(), s, &custom_input("mine")).unwrap(); + set_builtin_env(dir.path(), s, "mine", env.clone()).unwrap_err(); + write_agent(dir.path(), "bad-base", "base = \"nope\"\n"); + set_builtin_env(dir.path(), s, "bad-base", env).unwrap_err(); + assert!(secrets.keys("agent/bad-base/").is_empty()); + remove_custom(dir.path(), s, "copilot-work").unwrap(); + assert!(!dir.path().join("copilot-work.toml").exists()); + assert!(secrets.keys("agent/copilot-work/").is_empty()); + } } diff --git a/crates/ide-agent/src/registry.rs b/crates/ide-agent/src/registry.rs index 0eeace03d0..e77764f772 100644 --- a/crates/ide-agent/src/registry.rs +++ b/crates/ide-agent/src/registry.rs @@ -587,6 +587,7 @@ fn install_entry_with( } let agent = CustomAgent { name: Some(entry.name.clone()), + base: None, driver: Driver::Acp, command: exe.to_string_lossy().into_owned(), args, @@ -985,6 +986,7 @@ mod tests { let entries = parse(INDEX).unwrap(); let installed = |id: &str, version: &str| CustomAgent { name: None, + base: None, driver: Driver::Acp, command: "/x".into(), args: vec![], @@ -1222,6 +1224,7 @@ esac CustomAgent { name: Some("GitHub Copilot".into()), + base: None, driver: Driver::Acp, command: "/data/tools/copilot/1.0.104/node_modules/.bin/copilot".into(), args: vec!["--acp".into()], diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 994ac26e86..9fca7b2552 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1395,6 +1395,31 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() { assert_eq!(names(mgr_a.providers().into_iter().find(|p| p.id == "claude").unwrap().commands), ["review"]); } +fn instance_of(id: &str, base: &str) -> crate::CustomAgentInput { + crate::CustomAgentInput { + id: id.into(), + name: id.into(), + base: Some(base.into()), + command: String::new(), + args: Vec::new(), + env: std::collections::BTreeMap::new(), + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn instances_offer_the_commands_of_their_base() { + let tmp = tempfile::tempdir().unwrap(); + let agent = Arc::new(FakeAgent::default()); + let mgr = manager_at(tmp.path(), &tmp.path().join("models.json"), agent); + mgr.save_custom_agent(instance_of("codex-work", "codex")).unwrap(); + mgr.reload_providers(); + assert_eq!((mgr.base_provider_id("codex-work"), mgr.base_provider_id("custom")), ("codex".into(), "custom".into())); + let names = |commands: Vec| commands.into_iter().map(|c| c.name).collect::>(); + let instance = names(mgr.commands("codex-work", None).await.unwrap()); + assert!(instance.iter().any(|name| name == "review"), "{instance:?}"); + assert_eq!(instance, names(mgr.commands("codex", None).await.unwrap())); +} + #[tokio::test(flavor = "multi_thread")] async fn builtin_commands_only_fill_verified_gaps_and_preserve_advertised_metadata() { let tmp = tempfile::tempdir().unwrap(); @@ -2272,14 +2297,25 @@ async fn a_session_that_fails_to_load_is_reported_and_replaced_only_when_sent_ag assert_eq!(calls(&agent), ["session/load", "session/new", "session/prompt"]); } -/// A locked Codex recording can be forked without resuming it or moving its writer between tasks. +/// A locked Codex recording can be forked without resuming it or moving its writer between tasks, +/// also when the task runs an instance of Codex. #[tokio::test(flavor = "multi_thread")] async fn codex_writer_conflict_can_retry_or_fork_on_a_new_connection() { + for provider in ["codex", "codex-work"] { + codex_writer_conflict_forks_on_a_new_connection(provider).await; + } +} + +async fn codex_writer_conflict_forks_on_a_new_connection(provider: &str) { let tmp = tempfile::tempdir().unwrap(); let task = { let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + if provider != "codex" { + mgr.save_custom_agent(instance_of(provider, "codex")).unwrap(); + mgr.reload_providers(); + } let task = mgr - .create(NewAgentTask { prompt: text("again"), provider: "codex".into(), ..Default::default() }) + .create(NewAgentTask { prompt: text("again"), provider: provider.into(), ..Default::default() }) .await .unwrap(); wait_for(&mgr, &task.id, AgentStatus::Ready).await; @@ -4229,6 +4265,59 @@ async fn cursor_approval_switch_resolves_pending_and_survives_restart() { mgr.shutdown(); } +/// Saving or dropping a Cursor instance on disk is reflected on the very first `providers()` call. +#[tokio::test(flavor = "multi_thread")] +async fn new_cursor_instance_has_approval_option_on_first_providers_call() { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let _down = ShutDown(&mgr); + // Saved through the API: base_provider_id and providers() see it immediately without reload_providers(). + mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap(); + assert_eq!(mgr.base_provider_id("cursor-work"), "cursor"); + // Hand-written on disk: providers() updates its cache before mapping per-provider options. + std::fs::write(tmp.path().join("agents/cursor-disk.toml"), "base = \"cursor\"\nname = \"Cursor Disk\"\n").unwrap(); + let list = mgr.providers(); + for id in ["cursor-work", "cursor-disk"] { + let info = list.iter().find(|p| p.id == id).unwrap_or_else(|| panic!("{id}")); + assert!(info.config.iter().any(|o| o.id == config::CURSOR_APPROVAL), "{id}: {:?}", info.config); + } +} + +/// An instance of Cursor offers Cursor's client-side approval option, and a scheduled turn +/// clamps it as it clamps Cursor's own. +#[tokio::test(flavor = "multi_thread")] +async fn instances_take_the_approval_options_and_automation_clamp_of_their_base() { + for provider in ["cursor", "cursor-work"] { + let tmp = tempfile::tempdir().unwrap(); + let mgr = manager(tmp.path(), Arc::new(FakeAgent::default())); + let _down = ShutDown(&mgr); + mgr.save_custom_agent(instance_of("cursor-work", "cursor")).unwrap(); + mgr.reload_providers(); + let task = mgr + .create(NewAgentTask { + prompt: text("again"), + provider: provider.into(), + config: vec![AgentConfigChoice { id: config::CURSOR_APPROVAL.into(), value: "bypass".into() }], + ..Default::default() + }) + .await + .unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + let approval = || { + let snapshot = mgr.task_snapshot(&task.id).unwrap(); + snapshot.config.iter().find(|o| o.id == config::CURSOR_APPROVAL).and_then(|o| o.current.clone()) + }; + assert_eq!(approval().as_deref(), Some("bypass"), "{provider}"); + let meta = ScheduledTurnMeta { + permissions: Some(automation::AutomationPermissionMode::Default), + ..Default::default() + }; + mgr.prompt_scheduled(&task.id, text("again"), meta).await.unwrap(); + wait_for(&mgr, &task.id, AgentStatus::Ready).await; + assert_eq!(approval().as_deref(), Some("ask"), "{provider}"); + } +} + #[tokio::test(flavor = "multi_thread")] async fn bypass_approvals_keeps_both_question_dialects_pending_but_allows_permissions() { for prompt in ["ask", "qwen ask"] { diff --git a/crates/ide-build/src/lib.rs b/crates/ide-build/src/lib.rs index 168ae6d3be..1a80427112 100644 --- a/crates/ide-build/src/lib.rs +++ b/crates/ide-build/src/lib.rs @@ -103,9 +103,19 @@ pub fn load_linked_with_jdk( let mut m = maven::load_with_linked_jdk(root, repo, &profiles, maven_jdk_version, &settings.linked_projects); maven::UnlinkedProjects::from_model(&m, settings).filter(&mut m); // The user settings' profiles can be chosen too (`-P` applies to them as well). - for p in maven::user_settings_file(root, settings).map(|f| maven::settings_profiles(&f)).unwrap_or_default() { - if !m.profiles.iter().any(|x| x.id == p.id) { - m.profiles.push(p); + if let Some(settings_file) = maven::user_settings_file(root, settings) { + for p in maven::settings_profiles(&settings_file) { + if let Some(existing) = m.profiles.iter_mut().find(|x| x.id == p.id) { + existing.active_by_default |= p.active_by_default; + } else { + m.profiles.push(p); + } + } + let active_in_settings = maven::settings_active_profiles(&settings_file); + for existing in &mut m.profiles { + if active_in_settings.iter().any(|id| id == &existing.id) { + existing.active_by_default = true; + } } } sync::apply_maven_cache(root, cache_dir, &mut m); @@ -358,6 +368,49 @@ mod tests { assert!(modules(&settings).is_empty()); } + #[test] + fn settings_xml_active_profiles_mark_pom_profiles_active_by_default() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + std::fs::create_dir(root.join("child")).unwrap(); + std::fs::write( + root.join("pom.xml"), + r#"demoroot1.0pom + child + + test3 + devTRUE + "#, + ) + .unwrap(); + std::fs::write( + root.join("child/pom.xml"), + r#"demoroot1.0 + child + child-defaulttrue"#, + ) + .unwrap(); + let settings_xml = root.join("settings.xml"); + std::fs::write( + &settings_xml, + r#"test3"#, + ) + .unwrap(); + let cache = root.join("cache"); + let settings = ide_core::settings::MavenSettings { + user_settings: settings_xml.to_string_lossy().into_owned(), + ..Default::default() + }; + let model = load_linked(root, &cache, None, &settings, &Default::default()).maven.unwrap(); + let flags: Vec<(&str, bool)> = model.profiles.iter().map(|p| (p.id.as_str(), p.active_by_default)).collect(); + assert!( + flags.contains(&("test3", true)), + "activeProfile from settings.xml marks POM profile active: {flags:?}" + ); + assert!(flags.contains(&("dev", true)), "case-insensitive activeByDefault: {flags:?}"); + assert!(flags.contains(&("child-default", true)), "child module activeByDefault: {flags:?}"); + } + #[test] fn detects_build_systems_and_build_files() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-build/src/maven.rs b/crates/ide-build/src/maven.rs index 770310cd34..d1ce13d955 100644 --- a/crates/ide-build/src/maven.rs +++ b/crates/ide-build/src/maven.rs @@ -437,7 +437,9 @@ fn read_raw(project: &Element) -> RawPom { for p in project.list("profiles", "profile") { let mut profile = RawProfile { id: p.text_of("id").unwrap_or_else(|| "default".into()), - active_by_default: p.at("activation/activeByDefault").is_some_and(|a| a.text.trim() == "true"), + active_by_default: p + .at("activation/activeByDefault") + .is_some_and(|a| a.text.trim().eq_ignore_ascii_case("true")), activation_jdk: p.at("activation/jdk").map(|jdk| jdk.text.trim().to_owned()).filter(|jdk| !jdk.is_empty()), modules: module_names(p), properties: read_properties(p.child("properties")), @@ -601,12 +603,25 @@ pub fn settings_profiles(settings: &Path) -> Vec { if profiles.iter().any(|p| p.id == id) { continue; } - let by_default = profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim() == "true"); + let by_default = + profile.at("activation/activeByDefault").is_some_and(|e| e.text.trim().eq_ignore_ascii_case("true")); profiles.push(MavenProfile { active_by_default: by_default || active.contains(&id), id, ..Default::default() }); } profiles } +/// Profile IDs listed under `` in `settings.xml` (may refer to profiles defined in POMs). +pub fn settings_active_profiles(settings: &Path) -> Vec { + let Some(root) = xml::read_text(settings).as_deref().and_then(xml::parse) else { + return Vec::new(); + }; + root.list("activeProfiles", "activeProfile") + .iter() + .map(|e| e.text.trim().to_owned()) + .filter(|id| !id.is_empty()) + .collect() +} + /// `` of a settings file, when it names one: the repository a build /// with `-s ` resolves into, which is not necessarily the user's default. pub fn local_repository_of(settings: &Path) -> Option { @@ -1708,7 +1723,9 @@ pub fn load_with_linked_jdk( // The project can activate the profiles of its own POM and its ancestors'. for (id, active) in &ctx.profiles { - if !model.profiles.iter().any(|x| x.id == *id) { + if let Some(existing) = model.profiles.iter_mut().find(|x| x.id == *id) { + existing.active_by_default |= *active; + } else { model.profiles.push(MavenProfile { id: id.clone(), active_by_default: *active, ..Default::default() }); } } diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index d1384345b6..7e5a2c6e5f 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -142,8 +142,8 @@ pub fn agent_set_additional_args(host: &Host, window: &str, id: String, args: Ve host.project(window)?.agents.set_builtin_additional_args(&id, args) } -/// Environment variables built-in agent `id` starts with (saved in its agent file); -/// an empty map clears them. +/// Environment variables built-in agent `id`, or an instance of one, starts with (saved in +/// its agent file); an empty map clears them. #[command(trust = trusted)] pub fn agent_set_env( host: &Host, @@ -250,6 +250,42 @@ fn spawn_login_pty( ) } +async fn resolve_login_launch( + host: &Host, + window: &str, + id: &str, +) -> IdeResult<(std::path::PathBuf, LoginLaunch, String)> { + let agent = id.to_owned(); + match host.project(window) { + Ok(project) => { + let root = project.root.clone(); + let agents = project.agents.clone(); + let base = agents.base_provider_id(&agent); + let launch = host.blocking(move || agents.login_launch(&agent)).await?; + Ok((root, launch, base)) + } + Err(_) => { + let custom_dir = host.config_dir.join("agents"); + let secrets = host.agent_secrets.clone(); + let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir); + let cwd_for_lookup = cwd.clone(); + let (launch, base) = host + .blocking(move || { + let base = ide_agent::base_provider_id_without_project(Some(&custom_dir), &agent); + ide_agent::login_launch_without_project( + Some(&custom_dir), + Some(secrets.as_ref()), + &cwd_for_lookup, + &agent, + ) + .map(|launch| (launch, base)) + }) + .await?; + Ok((cwd, launch, base)) + } + } +} + /// 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( @@ -261,28 +297,9 @@ pub async fn agent_login_spawn( on_event: Channel, ) -> IdeResult { host.require_trust_if_project(window)?; - let agent = id.clone(); - let (cwd, mut 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(&agent)).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, &agent) - }) - .await?; - (cwd, launch) - } - }; + let (cwd, mut launch, base) = resolve_login_launch(host, window, &id).await?; apply_remote_login_env(host, &cwd, false, &mut launch); - use_device_auth(host.environment.is_remote(), &id, &mut launch.args); + use_device_auth(host.environment.is_remote(), &base, &mut launch.args); spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) } @@ -306,8 +323,8 @@ pub async fn agent_gh_login_spawn( spawn_login_pty(host, window, cwd, launch, cols, rows, on_event) } -/// Saves a new custom ACP agent through its agent file; refuses built-in and -/// ACP Registry ids and taken ids. +/// Saves a new custom ACP agent, or an instance of a built-in agent, through its agent +/// file; refuses built-in and ACP Registry ids and taken ids. #[command(trust = trusted)] pub async fn agent_custom_save(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> { host.require_trust(window)?; @@ -1890,11 +1907,10 @@ pub async fn agent_memory_set_auto( ) -> IdeResult { let project = host.project(window).ok().filter(|p| !p.light); let (mut user, mut workspace) = memory_settings_layers(host, project.as_ref()); - let prov_key = provider - .as_deref() - .map(str::trim) - .filter(|s| !s.is_empty()) - .map(|s| ide_agent::memory::normalize_provider_id(s).to_owned()); + let prov_key = provider.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| { + let base = project.as_ref().map(|p| p.agents.base_provider_id(s)); + ide_agent::memory::normalize_provider_id(base.as_deref().unwrap_or(s)).to_owned() + }); let apply = |layer: &mut AgentMemorySettings| -> bool { match &prov_key { None => { @@ -2887,6 +2903,45 @@ mod tests { assert!(!ssh_env.contains_key("GH_BROWSER")); assert!(!ssh_env.contains_key("GLAMOUR_STYLE")); } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn resolve_login_launch_without_project_reads_instance_env_from_secrets() { + ide_ssh::secrets::testing::use_memory_store(); + let tmp = tempfile::tempdir().unwrap(); + let host = Host::new(crate::HostConfig { + config_dir: tmp.path().join("config"), + data_dir: tmp.path().join("data"), + local_data_dir: tmp.path().join("data"), + languages: std::sync::Arc::new(ide_language::LanguageRegistry::load(None).unwrap()), + syntax: std::sync::Arc::default(), + sink_for: Box::new(|_| std::sync::Arc::new(ide_core::NullSink)), + owner: |w| w, + runtime: tokio::runtime::Handle::current(), + project_environment: false, + }); + let bin = tmp.path().join(if cfg!(windows) { "claude.cmd" } else { "claude" }); + std::fs::write(&bin, if cfg!(windows) { "@echo off\r\n" } else { "#!/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 agents_dir = host.config_dir.join("agents"); + std::fs::create_dir_all(&agents_dir).unwrap(); + std::fs::write( + agents_dir.join("claude.toml"), + format!("driver = \"claude\"\ncommand = {:?}\n", bin.to_string_lossy()), + ) + .unwrap(); + std::fs::write(agents_dir.join("claude-work.toml"), "base = \"claude\"\n[env]\nCLAUDE_CONFIG_DIR = \"\"\n") + .unwrap(); + host.agent_secrets.set("agent/claude-work/env/CLAUDE_CONFIG_DIR", "/home/me/.claude-work").unwrap(); + + let (_, launch, base) = resolve_login_launch(&host, "no-project", "claude-work").await.unwrap(); + assert_eq!(base, "claude"); + assert_eq!(launch.program, bin); + assert_eq!(launch.env.get("CLAUDE_CONFIG_DIR").map(String::as_str), Some("/home/me/.claude-work")); + } } ide_command::domain!( diff --git a/crates/ide-host/tests/agent_automations.rs b/crates/ide-host/tests/agent_automations.rs index d8121d082c..715ae55173 100644 --- a/crates/ide-host/tests/agent_automations.rs +++ b/crates/ide-host/tests/agent_automations.rs @@ -526,6 +526,7 @@ fn setup_host_and_repo(base: &Path) -> (Arc, PathBuf) { .save_custom_agent(CustomAgentInput { id: "mock-acp".into(), name: "Mock ACP".into(), + base: None, command: "node".into(), args: vec![script_path.to_string_lossy().into_owned()], env: Default::default(), @@ -2071,6 +2072,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo .save_custom_agent(CustomAgentInput { id: "mock-acp-stubborn".into(), name: "Mock ACP Stubborn".into(), + base: None, command: "node".into(), args: vec![script_path.to_string_lossy().into_owned()], env: std::collections::BTreeMap::from([("MOCK_REJECT_DOWNGRADE".to_owned(), "1".to_owned())]), @@ -2081,6 +2083,7 @@ async fn ceiling_rejection_persist_rollback_cross_owner_auth_queued_trust_and_wo .save_custom_agent(CustomAgentInput { id: "mock-acp-err".into(), name: "Mock ACP Error".into(), + base: None, command: "node".into(), args: vec![script_path.to_string_lossy().into_owned()], env: std::collections::BTreeMap::from([("MOCK_ERROR_DOWNGRADE".to_owned(), "1".to_owned())]), @@ -2611,6 +2614,7 @@ async fn scheduled_runs_cannot_recursively_mutate_automations_via_mcp_stdio_whil .save_custom_agent(CustomAgentInput { id: "mock-acp".into(), name: "Mock ACP".into(), + base: None, command: "node".into(), args: vec![script_path.to_string_lossy().into_owned()], env: std::collections::BTreeMap::from([( @@ -3085,6 +3089,7 @@ async fn oneshot_self_chaining_and_override_preservation_on_edit() { .save_custom_agent(CustomAgentInput { id: "mock-acp-mcp".into(), name: "Mock ACP MCP".into(), + base: None, command: "node".into(), args: vec![script_path.to_string_lossy().into_owned()], env: std::collections::BTreeMap::from([( diff --git a/crates/ide-host/tests/agent_env_secrets.rs b/crates/ide-host/tests/agent_env_secrets.rs index e60ab980b8..684f9b785e 100644 --- a/crates/ide-host/tests/agent_env_secrets.rs +++ b/crates/ide-host/tests/agent_env_secrets.rs @@ -40,6 +40,7 @@ async fn agent_environment_values_stay_out_of_agent_files() { ide_agent::CustomAgentInput { id: "mine".into(), name: "Mine".into(), + base: None, command: "/opt/mine".into(), args: vec![], env: env.clone(), diff --git a/crates/ide-language/src/syntax/rearrange.rs b/crates/ide-language/src/syntax/rearrange.rs index 87c2cd28af..70dfa9efdf 100644 --- a/crates/ide-language/src/syntax/rearrange.rs +++ b/crates/ide-language/src/syntax/rearrange.rs @@ -428,6 +428,17 @@ fn script_class_change(body: Node, text: &str) -> Option { return None; } let ranges: Vec> = blocks.into_iter().map(|b| b.3).collect(); + // A method moved to the top would continue a field left open above it when it starts with an + // operator: `x = 1` then `*gen() {}` reads as `1 * gen()`. + let children: Vec = body.children(&mut body.walk()).filter(|n| n.kind() != "comment").collect(); + let top = children.iter().find(|n| n.start_byte() >= ranges[order[0]].start); + let above = children.iter().rev().find(|n| n.end_byte() <= ranges[0].start); + if order[0] != 0 + && top.is_some_and(|n| n.child(0).is_some_and(|c| matches!(&text[c.byte_range()], "*" | "in" | "instanceof"))) + && !above.is_some_and(|n| n.kind() == "class_static_block" || text[n.byte_range()].ends_with(['{', ';'])) + { + return None; + } // Whole lines move: what shares the last method's last line (the closing brace, a comment // running on below it) stays at the end, so the last method must too. let end = ranges.last()?.end; @@ -664,10 +675,18 @@ mod tests { "const A = class {\n b() {}\n constructor() {} };", // So would the first line of a comment running on below it. "class A {\n b() {}\n constructor() {}; /* note\n */\n}\n", + // A generator moved below a field without a semicolon would continue its initializer, + // and so would one moved above the semicolon ending it. + "class A {\n x = 1\n #p() {}\n *gen() {}\n}\n", + "class A {\n x = {}\n #p() {}\n *gen() {}\n}\n", + "class A {\n x = 1\n #p() {}\n in(a) {}\n}\n", + "class A {\n x = 1\n #p() {}\n instanceof(a) {}\n}\n", + "class A {\n x = 1\n /* c */ ;\n #p() {}\n *gen() {}\n}\n", // A syntax error anywhere in the file. "class A {\n b() {}\n constructor() {}\n}\nlet = ;\n", ] { assert_eq!(script("typescript", text), None, "{text}"); + assert_eq!(script("javascript", text), None, "{text}"); } } @@ -696,6 +715,21 @@ mod tests { ); } + #[test] + fn a_generator_moves_to_the_top_only_below_a_closed_member() { + let text = "class A {\n x = 1;\n #p() {}\n *gen() {}\n}\n"; + let expected = "class A {\n x = 1;\n *gen() {}\n #p() {}\n}\n"; + assert_eq!(script("javascript", text).as_deref(), Some(expected)); + let text = "class A {\n static {}\n #p() {}\n *gen() {}\n}\n"; + let expected = "class A {\n static {}\n *gen() {}\n #p() {}\n}\n"; + assert_eq!(script("javascript", text).as_deref(), Some(expected)); + // The first method stays first, so the field's line ending is untouched. + let text = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n #p() {}\n *gen() {}\n}\n"; + let expected = "class A {\n x = 1\n /* c */ ;\n constructor() {}\n *gen() {}\n #p() {}\n}\n"; + assert_eq!(script("typescript", text).as_deref(), Some(expected)); + assert_eq!(script("javascript", text).as_deref(), Some(expected)); + } + #[test] fn static_and_instance_methods_with_one_name_stay_separate() { let text = "class A {\n of() {}\n static of() {}\n}\n"; diff --git a/crates/ide-lsp/src/handler.rs b/crates/ide-lsp/src/handler.rs index 5e12df3e6e..7b79683fd7 100644 --- a/crates/ide-lsp/src/handler.rs +++ b/crates/ide-lsp/src/handler.rs @@ -513,6 +513,10 @@ impl ClientHandler { fn show_message(&self, mgr: &LspManager, params: &Value) { let text = params.get("message").and_then(Value::as_str).unwrap_or_default().to_owned(); + // "Renew or activate a license" doesn't apply to a free preview build: its status offers the update. + if self.expired_license(mgr, &text) { + return; + } // rust-analyzer built from source reports its own slow main-loop turns as errors, meant for // its developers (`poke_rust_analyzer_developer`); nothing for the user to act on. if text.starts_with("overly long loop turn") { @@ -534,6 +538,16 @@ impl ClientHandler { mgr.sink().emit(IdeEvent::Notify { level, title: self.server.name.clone(), body: Some(text) }); } + /// Whether `text` says the running build's license ran out; if so, its status says so. + fn expired_license(&self, mgr: &LspManager, text: &str) -> bool { + if !crate::server::reports_expired_license(text) { + return false; + } + tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name); + self.server.report_expired_while_running(self.generation, mgr.sink()); + true + } + /// `window/showMessageRequest` expects `MessageActionItem | null`. Showing /// the question as a plain notification and replying null made Dart cancel /// renames with a warning (`Renamed field will be invisible in …`). @@ -770,6 +784,7 @@ impl Handler for ClientHandler { "window/showMessage" => self.show_message(&mgr, ¶ms), "window/logMessage" => { let text = params.get("message").and_then(Value::as_str).unwrap_or_default(); + self.expired_license(&mgr, text); if self.server.config.tsserver_project && tsserver_ran_out_of_memory(text) { tracing::warn!(server = ?self.server.id, generation = self.generation, "[{}] {text}", self.server.name); // The tasks of the dead tsserver never see their `end`: end them now diff --git a/crates/ide-lsp/src/server.rs b/crates/ide-lsp/src/server.rs index c3a21516bf..3b1f8c4f89 100644 --- a/crates/ide-lsp/src/server.rs +++ b/crates/ide-lsp/src/server.rs @@ -175,6 +175,9 @@ pub struct Server { /// Why the current instance's `initialize` failed, for the crash report. start_error: Mutex>, stderr: Mutex>, + /// The instance whose JetBrains preview build reported, while running, that its license + /// ran out: it stops serving after a short grace period, and only an update helps. + expired_while_running: Mutex>, pub progress: Mutex>, /// What the editor shows per path: the pushed and the pulled diagnostics together. diagnostics: Mutex>>, @@ -240,6 +243,7 @@ impl Server { started: Mutex::new(None), start_error: Mutex::new(None), stderr: Mutex::new(VecDeque::new()), + expired_while_running: Mutex::new(None), progress: Mutex::new(HashMap::new()), diagnostics: Mutex::new(HashMap::new()), pushed: Mutex::new(HashMap::new()), @@ -750,11 +754,35 @@ impl Server { return; } let busy = self.is_busy(); - self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, None); + let message = self.expired_message(st.generation); + self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message); drop(st); self.publish(sink); } + /// A running JetBrains preview build (kotlin-lsp) said its license ran out: it keeps the + /// process alive but stops serving once a short grace period ends, without crashing. Its + /// status then says the build expired, which offers the update a crashed one gets. + pub fn report_expired_while_running(&self, generation: u64, sink: &SharedSink) { + let mut st = self.state.lock(); + if st.generation != generation || !matches!(st.conn, Conn::Ready(_)) { + return; + } + if self.expired_while_running.lock().replace(generation) == Some(generation) { + return; + } + let busy = self.is_busy(); + let message = self.expired_message(generation); + self.queue_status(&mut st, if busy { ServerStatus::Busy } else { ServerStatus::Ready }, message); + drop(st); + self.publish(sink); + } + + fn expired_message(&self, generation: u64) -> Option { + (*self.expired_while_running.lock() == Some(generation)) + .then(|| format!("This build of {} has expired and stops working soon; update it.", self.name)) + } + /// Whether the server reports work in progress (indexing, analysis). A task marked /// stuck stays visible but no longer holds the server busy. pub fn is_busy(&self) -> bool { @@ -1167,6 +1195,14 @@ fn is_expired_build_line(line: &str) -> bool { line.contains("This build of ") && line.contains(" has expired") } +/// What a running JetBrains preview build says once its date passes: "Your JetBrains license has +/// expired or is no longer valid. The language server keeps working for a short grace period…", +/// then a parked license gate. +pub(crate) fn reports_expired_license(text: &str) -> bool { + let text = text.to_ascii_lowercase(); + text.contains("jetbrains license has expired") || text.contains("license gate: parked") +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 53b5f15e81..8f04bce166 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -2094,6 +2094,28 @@ async fn apply_edit_hook_and_server_requests() { "showMessageRequest is now a question with actions, not a notification; info and developer notices are not surfaced" ); + // A JetBrains preview build past its date keeps running but stops serving after a grace + // period: its status says the build expired (the UI offers the update), once per instance. + let expired = |e: &IdeEvent| matches!(e, IdeEvent::LanguageServer { status: ide_core::event::ServerStatus::Ready | ide_core::event::ServerStatus::Busy, message: Some(m), .. } if m.contains("has expired")); + peer.notify( + "window/showMessage", + json!({ "type": 2, "message": "Your JetBrains license has expired or is no longer valid. The language server keeps working for a short grace period; renew or activate a license to avoid interruption." }), + ) + .unwrap(); + peer.notify( + "window/logMessage", + json!({ "type": 3, "message": "#LicenseManager - License gate: Parked(reason=GraceExpired)" }), + ) + .unwrap(); + peer.notify("window/showMessage", json!({ "type": 2, "message": "after" })).unwrap(); + eventually(|| h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b == "after"))) + .await; + assert_eq!(h.events.lock().iter().filter(|e| expired(e)).count(), 1); + assert!( + !h.events.lock().iter().any(|e| matches!(e, IdeEvent::Notify { body: Some(b), .. } if b.contains("license"))), + "the license notice is not shown as is" + ); + // Dynamically registered capability is now usable. s.respond( "textDocument/documentHighlight", diff --git a/crates/ide-syntax/src/nodes.rs b/crates/ide-syntax/src/nodes.rs index f3a66f30af..8d9e72b8d6 100644 --- a/crates/ide-syntax/src/nodes.rs +++ b/crates/ide-syntax/src/nodes.rs @@ -32,28 +32,66 @@ fn is_word(c: char) -> bool { c.is_alphanumeric() || c == '_' || c == '$' } +/// Characters that can end an expression (`foo|)`, `new ArrayList<>()|`, `arr[0]|`, `"a"|`, `{a}|`). +fn is_expr_end(c: char) -> bool { + is_word(c) || matches!(c, ')' | ']' | '}' | '"' | '\'' | '`') +} + /// The byte a caret query should probe: the char after the caret, or the one -/// before it when the caret sits right after a word (`foo|)`). +/// before it when the caret sits right after a word or closing delimiter +/// (`foo|)`, `new ArrayList<>()|`). fn probe(text: &str, b: usize) -> usize { let after = text[b..].chars().next(); let before = text[..b].chars().next_back(); match (after, before) { - (Some(c), Some(p)) if !is_word(c) && is_word(p) => b - p.len_utf8(), + (Some(c), Some(p)) if !is_word(c) && is_expr_end(p) => b - p.len_utf8(), (None, Some(p)) => b - p.len_utf8(), _ => b, } } +fn expression_at_byte<'t>(cx: &Ctx<'t>, byte: usize) -> Option> { + let text = cx.text(); + let end = (byte + text[byte..].chars().next().map_or(0, char::len_utf8)).min(text.len()); + let node = cx.tree.root_node().named_descendant_for_byte_range(byte, end.max(byte))?; + enclosing_expression(cx, node) +} + +fn expression_at_caret<'t>(cx: &Ctx<'t>, byte: usize) -> Option> { + let text = cx.text(); + let p = probe(text, byte); + let expr = expression_at_byte(cx, p); + if p != byte { + return expr.or_else(|| (byte < text.len()).then(|| expression_at_byte(cx, byte)).flatten()); + } + if expr.is_some() && text[byte..].chars().next().is_some_and(is_word) { + return expr; + } + let Some(prev) = text[..byte].chars().next_back().filter(|c| !c.is_whitespace()) else { + return expr; + }; + let left = expression_at_byte(cx, byte - prev.len_utf8()); + match (expr, left) { + (None, left) => left, + (Some(right), Some(left)) + if left.end_byte() == byte + && left.start_byte() >= right.start_byte() + && left.end_byte() <= right.end_byte() + && left != right => + { + Some(left) + } + (right, _) => right, + } +} + pub(crate) fn expression_at(cx: &Ctx, range: Range) -> ExpressionAt { let text = cx.text(); let (a, b) = cx.lines.bytes(range); let (a, b) = trim(text, a, b); let root = cx.tree.root_node(); let (expression, exact) = if a == b { - let p = probe(text, a); - let end = (p + text[p..].chars().next().map_or(0, char::len_utf8)).min(text.len()); - let node = root.named_descendant_for_byte_range(p, end.max(p)); - (node.and_then(|n| enclosing_expression(cx, n)), false) + (expression_at_caret(cx, a), false) } else { match root.named_descendant_for_byte_range(a, b) { Some(node) => { diff --git a/crates/ide-syntax/src/tests/structure.rs b/crates/ide-syntax/src/tests/structure.rs index cc8c594d4c..91080f0a83 100644 --- a/crates/ide-syntax/src/tests/structure.rs +++ b/crates/ide-syntax/src/tests/structure.rs @@ -114,6 +114,119 @@ fn expression_at_exact_enclosing_and_caret() { assert!(e.expression.is_none(), "{e:?}"); } +#[test] +fn expression_at_caret_after_closing_delimiters_and_postfix() { + let java = lang("java"); + // Caret right after `)` on bare `new ArrayList<>()` / `new Object()` (no semicolon, next line follows). + let src = "class A {\n void f() {\n new ArrayList<>()\n new Object()\n run();\n }\n}\n"; + let s = snap(&java, src); + for needle in ["new ArrayList<>()", "new Object()"] { + let end = span(src, needle).end; + let e = service().expression_at(&s, Range::point(end), &none()).unwrap(); + let expr = e.expression.as_ref().unwrap_or_else(|| panic!("missing expression after `{needle}`: {e:?}")); + assert_eq!((expr.kind.as_str(), expr.range), ("object_creation_expression", span(src, needle))); + assert_eq!(e.candidates.len(), 1, "{e:?}"); + assert!(!expr.has_error, "{e:?}"); + } + + // Caret right after `)`, `]`, `"`, `}` before `;` or outer `)`, and NOT after `;` or block `}`. + let src = "class A {\n void f(int[] arr, boolean c) {\n new ArrayList<>();\n bar(foo());\n foo(\"hi\");\n arr[0];\n new int[] { 1, 2 };\n if (c) { bar(1); }\n return(1 + 2);\n }\n}\n"; + let s = snap(&java, src); + + let e = service().expression_at(&s, Range::point(span(src, "new ArrayList<>()").end), &none()).unwrap(); + assert_eq!( + e.expression.as_ref().map(|n| (n.kind.as_str(), n.range)), + Some(("object_creation_expression", span(src, "new ArrayList<>()"))) + ); + + // After `;` is outside the expression. + let e = service().expression_at(&s, Range::point(span(src, "new ArrayList<>();").end), &none()).unwrap(); + assert!(e.expression.is_none(), "{e:?}"); + + // Nested call `bar(foo()|)` offers both `foo()` and `bar(foo())`. + let e = service().expression_at(&s, Range::point(span(src, "foo()").end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [span(src, "foo()"), span(src, "bar(foo())")]); + + // String argument `foo("hi"|)` offers both `"hi"` and `foo("hi")`. + let e = service().expression_at(&s, Range::point(span(src, "\"hi\"").end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [span(src, "\"hi\""), span(src, "foo(\"hi\")")]); + + // Array access `arr[0]|;` and array creation `new int[] { 1, 2 }|;`. + let e = service().expression_at(&s, Range::point(span(src, "arr[0]").end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(src, "arr[0]"))); + let e = service().expression_at(&s, Range::point(span(src, "new int[] { 1, 2 }").end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(src, "new int[] { 1, 2 }"))); + + // After a statement block `if (c) { bar(1); }|` or method params `f(...)|` is not an expression. + let e = service().expression_at(&s, Range::point(span(src, "if (c) { bar(1); }").end), &none()).unwrap(); + assert!(e.expression.is_none(), "{e:?}"); + let e = service().expression_at(&s, Range::point(span(src, "(int[] arr, boolean c)").end), &none()).unwrap(); + assert!(e.expression.is_none(), "{e:?}"); + + // Between keyword and `(`: `return|(1 + 2);` falls back to `(`. + let e = service().expression_at(&s, Range::point(span(src, "return").end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(src, "(1 + 2)"))); + + // Postfix `?` in Rust (`foo()?|;`, `bar(foo()?|)`, `foo()?| + 1`) and `!` in TypeScript (`foo()!|`, `bar(foo()!|)`). + let rust = lang("rust"); + let rsrc = "fn f() -> Result {\n foo()?;\n bar(foo()?);\n let n = foo()? + 1;\n Ok(n)\n}\n"; + let rsnap = snap(&rust, rsrc); + let e = service().expression_at(&rsnap, Range::point(occ(rsrc, "foo()?", 1).end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(occ(rsrc, "foo()?", 1))); + let e = service().expression_at(&rsnap, Range::point(occ(rsrc, "foo()?", 2).end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [occ(rsrc, "foo()?", 2), span(rsrc, "bar(foo()?)")]); + let e = service().expression_at(&rsnap, Range::point(occ(rsrc, "foo()?", 3).end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [occ(rsrc, "foo()?", 3), span(rsrc, "foo()? + 1")]); + + let ts = lang("typescript"); + let tsrc = "function f() {\n foo()!\n bar(foo()!)\n}\n"; + let tsnap = snap(&ts, tsrc); + let e = service().expression_at(&tsnap, Range::point(occ(tsrc, "foo()!", 1).end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(occ(tsrc, "foo()!", 1))); + let e = service().expression_at(&tsnap, Range::point(occ(tsrc, "foo()!", 2).end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [occ(tsrc, "foo()!", 2), span(tsrc, "bar(foo()!)")]); + + // Closing `>` in TSX (`render(|)`) offers both `` and `render()`. + let tsx = lang("tsx"); + let xsrc = "function f() {\n return render();\n}\n"; + let e = service().expression_at(&snap(&tsx, xsrc), Range::point(span(xsrc, "").end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [span(xsrc, ""), span(xsrc, "render()")]); + + // Postfix `++` in nested call (`foo(i++|)`) offers `i++` and `foo(i++)`, while prefix/infix + // operators before `(` (`!(a)`, `a ?(b) : c`, `a >(b)`) still probe `(` instead of widening. + let jsrc = "class A {\n void f(int i, boolean a, int b, int c) {\n foo(i++);\n boolean x = !(a);\n int y = a ?(b) : c;\n boolean z = i >(b);\n foo(\"😀\");\n }\n}\n"; + let jsnap = snap(&java, jsrc); + let e = service().expression_at(&jsnap, Range::point(span(jsrc, "i++").end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [span(jsrc, "i++"), span(jsrc, "foo(i++)")]); + let e = service().expression_at(&jsnap, Range::point(span(jsrc, "(a)").start), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(jsrc, "(a)"))); + let e = service().expression_at(&jsnap, Range::point(occ(jsrc, "(b)", 1).start), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(occ(jsrc, "(b)", 1))); + let e = service().expression_at(&jsnap, Range::point(occ(jsrc, "(b)", 2).start), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(occ(jsrc, "(b)", 2))); + // UTF-16 surrogate pair inside string literal: caret right after closing `"`. + let e = service().expression_at(&jsnap, Range::point(span(jsrc, "\"😀\"").end), &none()).unwrap(); + let ranges: Vec = e.candidates.iter().map(|c| c.range).collect(); + assert_eq!(ranges, [span(jsrc, "\"😀\""), span(jsrc, "foo(\"😀\")")]); + + // Boundary offsets: empty file, offset 0, and EOF without trailing newline. + let e = service().expression_at(&snap(&java, ""), Range::point(Pos::new(0, 0)), &none()).unwrap(); + assert!(e.expression.is_none(), "{e:?}"); + let py = lang("python"); + let psrc = "len(a)"; + let e = service().expression_at(&snap(&py, psrc), Range::point(Pos::new(0, 0)), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(psrc, "len"))); + let e = service().expression_at(&snap(&py, psrc), Range::point(span(psrc, "len(a)").end), &none()).unwrap(); + assert_eq!(e.expression.as_ref().map(|n| n.range), Some(span(psrc, "len(a)"))); +} + #[test] fn expression_at_flags_lambda_boundary_and_errors() { let ts = lang("typescript"); diff --git a/crates/ide-vcs/src/commit_rewrite.rs b/crates/ide-vcs/src/commit_rewrite.rs index aea13b8ca6..84930b43c6 100644 --- a/crates/ide-vcs/src/commit_rewrite.rs +++ b/crates/ide-vcs/src/commit_rewrite.rs @@ -6,7 +6,7 @@ use crate::{AmendTarget, CommitOptions, HeadChange, HistoryTip, Repo, RewrittenC use gix::bstr::ByteSlice; use ide_core::error::ErrorData; use ide_core::{CancellationToken, IdeError, IdeResult}; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::OsStr; use std::fs; use std::io::Write; @@ -56,6 +56,34 @@ impl History { Ok(Self { head, branch, commits }) } + fn load_reword(repo: &Repo, target: &str) -> IdeResult { + if repo.branch_info()?.operation.is_some() { + return Err(IdeError::invalid("cannot rewrite history while a Git operation is in progress")); + } + let objects = repo.gix()?; + let head = objects.head().map_err(gx)?; + let branch = head.referent_name().map(|name| name.as_bstr().to_string()); + let head = head.id().ok_or_else(|| IdeError::invalid("there is no commit to edit"))?.detach(); + let commit = objects.find_object(resolve(&objects, target)?).map_err(gx)?.peel_to_commit().map_err(gx)?; + let target = commit.id.to_string(); + let head_str = head.to_string(); + if target != head_str + && run_raw(repo.root(), &["merge-base", "--is-ancestor", &target, &head_str], None)?.code != Some(0) + { + return Err(IdeError::invalid("the commit is not in the current branch")); + } + let range = format!("{target}..{head_str}"); + let listed = run(repo.root(), &["rev-list", "--reverse", "--topo-order", "--ancestry-path", &range], None)?; + let mut commits = vec![target]; + for line in listed.stdout_str().lines() { + let id = line.trim(); + if !id.is_empty() { + commits.push(id.to_owned()); + } + } + Ok(Self { head, branch, commits }) + } + fn ensure_current(&self, repo: &Repo) -> IdeResult<()> { let objects = repo.gix()?; let head = objects.head().map_err(gx)?; @@ -71,7 +99,7 @@ impl History { fn rewrite_descendants(self, repo: &Repo, mut parent: String, reason: &str) -> IdeResult { for id in &self.commits[1..] { let commit = Commit::read(repo, id)?; - parent = commit.write(repo, &commit.tree, Some(&parent), None)?; + parent = commit.write(repo, &commit.tree, &[parent.as_str()], None)?; } self.ensure_current(repo)?; let before = self.head.to_string(); @@ -79,6 +107,23 @@ impl History { Ok(HeadChange { before, after: parent }) } + fn rewrite_reword_descendants(self, repo: &Repo, rewritten: String, reason: &str) -> IdeResult { + let mut mapped = HashMap::with_capacity(self.commits.len()); + mapped.insert(self.commits[0].clone(), rewritten); + for id in &self.commits[1..] { + let commit = Commit::read(repo, id)?; + let parents: Vec<&str> = + commit.parents.iter().map(|p| mapped.get(p).map_or(p.as_str(), String::as_str)).collect(); + let next = commit.write(repo, &commit.tree, &parents, None)?; + mapped.insert(id.clone(), next); + } + self.ensure_current(repo)?; + let before = self.head.to_string(); + let after = mapped.get(&before).cloned().ok_or_else(|| IdeError::invalid("failed to rewrite branch tip"))?; + self.move_tip(repo, &before, &after, reason)?; + Ok(HeadChange { before, after }) + } + fn move_tip(&self, repo: &Repo, from: &str, to: &str, reason: &str) -> IdeResult<()> { run( repo.root(), @@ -128,7 +173,7 @@ impl History { struct Commit { tree: String, - parent: Option, + parents: Vec, author: String, encoding: Option, data: Vec, @@ -141,22 +186,20 @@ impl Commit { let header_end = data.find(b"\n\n").ok_or_else(|| IdeError::invalid("invalid commit data"))?; let headers = data[..header_end].to_str_lossy(); let header = |prefix| headers.lines().find_map(|line| line.strip_prefix(prefix)).map(str::to_owned); + let parents = headers.lines().filter_map(|line| line.strip_prefix("parent ").map(str::to_owned)).collect(); let tree = header("tree ").ok_or_else(|| IdeError::invalid("commit has no tree"))?; let author = header("author ").ok_or_else(|| IdeError::invalid("commit has no author"))?; - Ok(Self { - tree, - parent: header("parent "), - author, - encoding: header("encoding "), - data, - message_start: header_end + 2, - }) + Ok(Self { tree, parents, author, encoding: header("encoding "), data, message_start: header_end + 2 }) } - fn write(&self, repo: &Repo, tree: &str, parent: Option<&str>, new_message: Option<&str>) -> IdeResult { + fn first_parent(&self) -> Option<&str> { + self.parents.first().map(String::as_str) + } + + fn write(&self, repo: &Repo, tree: &str, parents: &[&str], new_message: Option<&str>) -> IdeResult { let (message, encoding) = new_message.map_or_else(|| (self.message(), self.encoding()), |message| (message.as_bytes(), "UTF-8")); - Self::write_commit(repo, tree, parent, message, encoding, self.identity()) + Self::write_commit(repo, tree, parents, message, encoding, self.identity()) } fn identity(&self) -> (&str, &str, &str) { @@ -168,7 +211,7 @@ impl Commit { fn write_commit( repo: &Repo, tree: &str, - parent: Option<&str>, + parents: &[&str], message: &[u8], encoding: &str, author: (&str, &str, &str), @@ -181,7 +224,7 @@ impl Commit { ]; let encoding = format!("i18n.commitEncoding={encoding}"); let mut args = vec!["-c", &encoding, "commit-tree", tree]; - if let Some(parent) = parent { + for parent in parents { args.extend(["-p", parent]); } Ok(run_env(repo.root(), &args, Some(message), &env)?.stdout_str().trim().to_string()) @@ -206,11 +249,12 @@ fn new_message(message: &str) -> IdeResult { pub(crate) fn reword(repo: &Repo, id: &str, message: &str) -> IdeResult { let message = new_message(message)?; - let history = History::load(repo, id, None)?; + let history = History::load_reword(repo, id)?; let commit = Commit::read(repo, &history.commits[0])?; - let rewritten = commit.write(repo, &commit.tree, commit.parent.as_deref(), Some(&message))?; + let parents: Vec<&str> = commit.parents.iter().map(String::as_str).collect(); + let rewritten = commit.write(repo, &commit.tree, &parents, Some(&message))?; let reason = format!("reword: {}", message.lines().next().unwrap_or_default()); - history.rewrite_descendants(repo, rewritten, &reason) + history.rewrite_reword_descendants(repo, rewritten, &reason) } /// Builds the selected commit in a detached Git directory, using the real @@ -281,7 +325,8 @@ pub(crate) fn amend( history.ensure_current(repo)?; let mut message = format!("amend! {original}\n\n").into_bytes(); message.extend_from_slice(addition.message()); - let commit = Commit::write_commit(repo, &addition.tree, Some(&before), &message, addition.encoding(), author)?; + let commit = + Commit::write_commit(repo, &addition.tree, &[before.as_str()], &message, addition.encoding(), author)?; let entries = affected_index_entries(repo, &before, index.as_deref(), &paths)?; *repo.amend_recovery.lock().unwrap_or_else(|e| e.into_inner()) = Some(PendingAmend { commit: commit.clone(), history, paths, entries }); @@ -311,8 +356,9 @@ fn replay_amend( } else { commit.tree.clone() }; + let parent_slice: Vec<&str> = commit.first_parent().into_iter().collect(); let mut rewritten = - Commit::write_commit(repo, &tree, commit.parent.as_deref(), addition.message(), addition.encoding(), author)?; + Commit::write_commit(repo, &tree, &parent_slice, addition.message(), addition.encoding(), author)?; let mut final_tree = tree; for pair in history.commits.windows(2) { let next = Commit::read(repo, &pair[1])?; @@ -322,7 +368,7 @@ fn replay_amend( } else { next.tree.clone() }; - rewritten = next.write(repo, &final_tree, Some(&rewritten), None)?; + rewritten = next.write(repo, &final_tree, &[rewritten.as_str()], None)?; } // The replay must consume exactly the selected changes. The worktree can then // stay as it is, including local edits and untracked files on the same paths. @@ -479,8 +525,9 @@ pub(crate) fn extract( let target = &history.commits[0]; let commit = Commit::read(repo, target)?; let remaining = remaining_tree(repo, target, &commit, paths)?; - let rewritten = commit.write(repo, &remaining, commit.parent.as_deref(), None)?; - let extracted = commit.write(repo, &commit.tree, Some(&rewritten), Some(&message))?; + let parent_slice: Vec<&str> = commit.first_parent().into_iter().collect(); + let rewritten = commit.write(repo, &remaining, &parent_slice, None)?; + let extracted = commit.write(repo, &commit.tree, &[rewritten.as_str()], Some(&message))?; let head = history.rewrite_descendants(repo, extracted.clone(), "extract selected changes")?; Ok(RewrittenCommit { head, commit: extracted }) } @@ -500,7 +547,8 @@ pub(crate) fn drop_changes( let target = &history.commits[0]; let commit = Commit::read(repo, target)?; let remaining = remaining_tree(repo, target, &commit, paths)?; - let replacement = commit.write(repo, &remaining, commit.parent.as_deref(), None)?; + let parent_slice: Vec<&str> = commit.first_parent().into_iter().collect(); + let replacement = commit.write(repo, &remaining, &parent_slice, None)?; let mut todo = format!("drop {target}\npick {replacement}\n"); for descendant in &history.commits[1..] { todo.push_str(&format!("pick {descendant}\n")); @@ -517,7 +565,7 @@ pub(crate) fn drop_changes( "--interactive", "--no-autosquash", "--empty=keep", - commit.parent.as_deref().unwrap_or("--root"), + commit.first_parent().unwrap_or("--root"), ]; crate::ops::run_rebase_todo(repo, work.path(), &todo, &args, cancel, out)?; let after = run(repo.root(), &["rev-parse", "--verify", "HEAD"], None)?.stdout_str().trim().to_string(); @@ -531,7 +579,7 @@ fn remaining_tree(repo: &Repo, id: &str, commit: &Commit, paths: &[PathBuf]) -> if paths.is_empty() || paths.contains("") { return Err(IdeError::invalid("select files from the commit")); } - let source_tree = if let Some(parent) = &commit.parent { + let source_tree = if let Some(parent) = commit.first_parent() { run(repo.root(), &["rev-parse", &format!("{parent}^{{tree}}")], None)? } else { run(repo.root(), &["hash-object", "-t", "tree", "-w", "--stdin"], Some(b""))? diff --git a/crates/ide-vcs/tests/repo.rs b/crates/ide-vcs/tests/repo.rs index f369436764..ff4f0116f9 100644 --- a/crates/ide-vcs/tests/repo.rs +++ b/crates/ide-vcs/tests/repo.rs @@ -3004,6 +3004,75 @@ fn reword_keeps_local_changes_and_can_be_undone() { assert!(repo.restore_head(&change.before, &change.after).is_err()); } +#[test] +fn reword_merge_commit_at_head_preserves_parents_and_local_changes() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["checkout", "-q", "-b", "topic"]); + fx.write("topic.txt", "topic\n"); + let topic = fx.commit_all("topic work"); + fx.git(&["checkout", "-q", "main"]); + fx.write("main.txt", "main\n"); + let main_tip = fx.commit_all("main work"); + fx.git(&["merge", "-q", "--no-ff", "-m", "Merge branch 'topic'", "topic"]); + let merge = fx.git(&["rev-parse", "HEAD"]); + let merge_tree = fx.git(&["rev-parse", "HEAD^{tree}"]); + fx.write("main.txt", "local\n"); + fx.write("staged.txt", "s\n"); + fx.git(&["add", "staged.txt"]); + + let repo = fx.repo(); + let change = repo.reword(&merge, "Custom merge summary\n\nDetails").unwrap(); + assert_eq!(change.before, merge); + assert_ne!(change.after, merge); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), change.after); + assert_eq!(fx.git(&["log", "-1", "--format=%B", "HEAD"]), "Custom merge summary\n\nDetails"); + assert_eq!(fx.git(&["rev-parse", "HEAD^1"]), main_tip); + assert_eq!(fx.git(&["rev-parse", "HEAD^2"]), topic); + assert_eq!(fx.git(&["rev-parse", "HEAD^{tree}"]), merge_tree); + assert_eq!(fx.read("main.txt"), "local\n"); + assert_eq!(fx.git(&["diff", "--cached", "--name-only"]), "staged.txt"); + + repo.restore_head(&change.before, &change.after).unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), merge); + assert_eq!(fx.git(&["log", "-1", "--format=%s", "HEAD"]), "Merge branch 'topic'"); +} + +#[test] +fn reword_merge_commit_with_descendants_and_later_merge_preserves_dag() { + let fx = Fixture::new(); + fx.write("base.txt", "base\n"); + fx.commit_all("base"); + fx.git(&["checkout", "-q", "-b", "topic"]); + fx.write("topic.txt", "topic\n"); + let topic = fx.commit_all("topic work"); + fx.git(&["checkout", "-q", "main"]); + fx.git(&["checkout", "-q", "-b", "other"]); + fx.write("other.txt", "other\n"); + let other = fx.commit_all("other work"); + fx.git(&["checkout", "-q", "main"]); + fx.write("main.txt", "main\n"); + let main_tip = fx.commit_all("main work"); + fx.git(&["merge", "-q", "--no-ff", "-m", "Merge branch 'topic'", "topic"]); + let first_merge = fx.git(&["rev-parse", "HEAD"]); + fx.write("after.txt", "after\n"); + fx.commit_all("after merge"); + fx.git(&["merge", "-q", "--no-ff", "-m", "Merge branch 'other'", "other"]); + let final_tree = fx.git(&["rev-parse", "HEAD^{tree}"]); + + let repo = fx.repo(); + let change = repo.reword(&first_merge, "Reworded topic merge").unwrap(); + assert_eq!(fx.git(&["rev-parse", "HEAD"]), change.after); + assert_eq!(fx.git(&["rev-parse", "HEAD^{tree}"]), final_tree); + assert_eq!(fx.git(&["log", "-1", "--format=%s", "HEAD"]), "Merge branch 'other'"); + assert_eq!(fx.git(&["rev-parse", "HEAD^2"]), other, "second merge keeps side branch parent"); + assert_eq!(fx.git(&["log", "-1", "--format=%s", "HEAD^1"]), "after merge"); + assert_eq!(fx.git(&["log", "-1", "--format=%s", "HEAD^1^1"]), "Reworded topic merge"); + assert_eq!(fx.git(&["rev-parse", "HEAD^1^1^1"]), main_tip); + assert_eq!(fx.git(&["rev-parse", "HEAD^1^1^2"]), topic); +} + #[test] fn amend_earlier_commit_replays_descendants_and_preserves_the_remaining_index() { let fx = Fixture::new(); diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index 8d22cbbd96..bfaa1d6dde 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -135,6 +135,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. +To run a built-in agent a second way, such as Claude Code with another account, select it and click **Duplicate…**. The copy runs the same command as the agent it copies, with its own name, id, **Environment variables**, sign-in, **New Tasks** settings and tasks; it is saved as an agent file whose `base` is the copied agent's id. Give it its own configuration directory with an environment variable, such as `CLAUDE_CONFIG_DIR=/Users/me/.claude-work` for Claude Code or `COPILOT_HOME` for GitHub Copilot, then use **Sign In…** on the copy's page. Paths must be absolute: `~` is not expanded. **Remove** deletes the copy's agent file; its tasks stay. + 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…**). When an agent or `gh` prints an OAuth device verification code during in-IDE sign-in (including on remote hosts), the sign-in dialog surfaces the one-time code above the terminal with **Copy** and **Copy Code & Open Browser** so you can authorize in your local browser in one click. **New Tasks** model options load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions. **Settings › Agents › General** 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**. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index 886916e371..59dca9e84c 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -135,6 +135,8 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的 对于直接启动的内置 ACP agent(例如 OMP),**启动 › 附加实参**会追加到现有启动命令末尾。用空格分隔参数,含空格的值请加引号。点击**应用**保存,下一次启动进程时生效;命令预览显示已保存的结果。**重置附加参数**只清除此字段,不会改动可执行文件、环境变量或配置文件中手写的 `args`。 +要以另一种方式运行内置 agent(例如用另一个账号运行 Claude Code),选中它并点击 **复制…**。副本运行与原 agent 相同的命令,但有自己的名称、ID、**环境变量**、登录、**新任务**设置和任务;它保存为一个 agent 文件,其 `base` 为所复制 agent 的 ID。用环境变量为副本指定独立的配置目录,例如 Claude Code 用 `CLAUDE_CONFIG_DIR=/Users/me/.claude-work`,GitHub Copilot 用 `COPILOT_HOME`,然后在副本页面上点击 **登录…**。路径必须是绝对路径:`~` 不会被展开。**移除** 会删除副本的 agent 文件;其任务会保留。 + 对于 **GitHub Copilot**,**登录 › GitHub 账号**选择用于 AI 模型请求的 Copilot 订阅所属 GitHub 账号——既可使用 Copilot CLI 自身的默认登录(**登录…**),也可选择已在 GitHub CLI 中登录的任意账号(**添加账户…**)。在 IDE 内登录(包括连接远程主机时)过程中,若智能体或 `gh` 输出了 OAuth 设备验证码,登录对话框会在终端上方显示一次性验证码及 **复制**、**复制验证码并打开浏览器** 按钮,方便一键在本地浏览器完成授权。选择已验证的账号后,**新任务**会自动加载该账号对应的可用模型列表,点击**应用**或**确定**保存以供新会话使用。 **设置 › 智能体 › 常规** 决定任务标题栏显示哪些信息:**上下文窗口用量**、**任务耗时**、**用量限额**(agent 报告时,例如 Claude Code)和 **会话花费**。 diff --git a/e2e/agentDuplicate.spec.ts b/e2e/agentDuplicate.spec.ts new file mode 100644 index 0000000000..bbfda3b823 --- /dev/null +++ b/e2e/agentDuplicate.spec.ts @@ -0,0 +1,131 @@ +import type { Page } from "@playwright/test"; +import type { AgentProvider, CustomAgentInput } 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 }); +} + +for (const theme of ["light", "dark"] as const) { + test(`duplicates a built-in agent from the keyboard in ${theme}, also in a narrow window`, async ({ + workbench: page, + }) => { + await stubDesktop(page); + await page.evaluate(async (theme) => { + const themePath = "/src/workbench/theme.ts"; + (await import(/* @vite-ignore */ themePath)).previewTheme(theme); + const claude: AgentProvider = { + id: "claude", + name: "Claude Code", + command: "claude", + program: "claude", + args: [], + defaultProgram: "claude", + defaultArgs: [], + loginHint: null, + commandOverridden: false, + commandEditable: true, + commandReadOnlyReason: null, + installed: true, + canSignIn: true, + canCheckCliUpdate: false, + canDuplicate: true, + env: {}, + config: [], + thoughtLevels: {}, + commands: [], + source: { kind: "builtin" }, + }; + let providers: AgentProvider[] = [claude]; + Object.assign(window.__ipc.handlers, { + settings_get_global: () => ({}), + agent_registry_list: () => ({ agents: [], warning: null }), + agent_providers: () => providers, + agent_custom_save: ({ input }: { input: CustomAgentInput }) => { + providers = [ + ...providers, + { + ...claude, + id: input.id, + name: input.name, + base: input.base, + defaultProgram: null, + defaultArgs: [], + canDuplicate: false, + commandEditable: false, + commandReadOnlyReason: "customAgent", + env: input.env ?? {}, + source: { kind: "custom" }, + }, + ]; + return null; + }, + }); + }, theme); + + const settings = await openAgents(page); + const claudePage = settings.getByRole("region", { name: "Claude Code" }); + const duplicate = claudePage.getByRole("button", { name: "Duplicate…" }); + await duplicate.focus(); + await page.keyboard.press("Enter"); + let dialog = page.getByRole("dialog", { name: "Duplicate Claude Code" }); + await expect(dialog.getByRole("textbox", { name: "Name" })).toBeFocused(); + await expect(dialog.getByRole("textbox", { name: "Name" })).toHaveValue("Claude Code 2"); + await expect(dialog.getByRole("textbox", { name: "ID" })).toHaveValue("claude-code-2"); + await expect(dialog.getByText(/CLAUDE_CONFIG_DIR/)).toBeVisible(); + + // Escape cancels and gives the focus back to the button that opened the dialog. + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + await expect(duplicate).toBeFocused(); + + await page.keyboard.press("Enter"); + dialog = page.getByRole("dialog", { name: "Duplicate Claude Code" }); + await page.setViewportSize({ width: 520, height: 760 }); + const box = (await dialog.boundingBox())!; + expect(box.x).toBeGreaterThanOrEqual(0); + expect(box.x + box.width).toBeLessThanOrEqual(520); + expect(await dialog.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); + await expect(dialog.getByText(/~ is not expanded/)).toBeVisible(); + if (process.env.OPENIDEA_AGENT_DUPLICATE_SHOTS) + await dialog.screenshot({ path: `${process.env.OPENIDEA_AGENT_DUPLICATE_SHOTS}/dialog-${theme}-520.png` }); + + await page.keyboard.press("ControlOrMeta+a"); + await page.keyboard.type("Claude Work"); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("textbox", { name: "ID" })).toBeFocused(); + await expect(dialog.getByRole("textbox", { name: "ID" })).toHaveValue("claude-work"); + await page.keyboard.press("Tab"); + await expect(dialog.getByRole("textbox", { name: "Environment variables" })).toBeFocused(); + await page.keyboard.type("CLAUDE_CONFIG_DIR=/Users/me/.claude-work"); + await page.keyboard.press("Enter"); + await expect(dialog).toBeHidden(); + expect(await ipcCalls(page, "agent_custom_save")).toEqual([ + { + input: { + id: "claude-work", + name: "Claude Work", + command: "", + base: "claude", + env: { CLAUDE_CONFIG_DIR: "/Users/me/.claude-work" }, + }, + }, + ]); + + // The copy is selected and the list keeps the keyboard. + const copyPage = settings.getByRole("region", { name: "Claude Work" }); + await expect(copyPage.getByText("Based on Claude Code · Agent file")).toBeVisible(); + await expect(copyPage.getByRole("region", { name: "Launch" }).locator("code")).toHaveText("claude"); + await expect(settings.getByRole("listbox", { name: "Agents" })).toBeFocused(); + await expect(settings.getByRole("option", { name: /^Claude Work/ })).toHaveAttribute("aria-selected", "true"); + await expect(copyPage.getByRole("textbox", { name: "Environment variables" })).toHaveValue( + "CLAUDE_CONFIG_DIR=/Users/me/.claude-work", + ); + const details = (await copyPage.boundingBox())!; + expect(details.width).toBeGreaterThan(180); + if (process.env.OPENIDEA_AGENT_DUPLICATE_SHOTS) + await settings.screenshot({ path: `${process.env.OPENIDEA_AGENT_DUPLICATE_SHOTS}/copy-${theme}-520.png` }); + }); +} diff --git a/src-tauri/src/macos.rs b/src-tauri/src/macos.rs index 3b8eed9730..1fcc9cafd3 100644 --- a/src-tauri/src/macos.rs +++ b/src-tauri/src/macos.rs @@ -306,6 +306,7 @@ impl PendingTabSwitch { enum PrewarmOutcome { Switched, + MissingNative, Waiting { generation: u64, rx: std::sync::mpsc::Receiver<()> }, } @@ -370,9 +371,19 @@ fn cancel_pending_tab_switch() { } } -fn switch_tab_group_now(members: &[WebviewWindow], anchor: &WebviewWindow, target: &WebviewWindow) { - let Some(shown) = native(target) else { return }; - let Some(anchor_window) = native(anchor) else { return }; +fn switch_tab_group_now(members: &[WebviewWindow], anchor: &WebviewWindow, target: &WebviewWindow) -> bool { + let Some(shown) = native(target) else { + tracing::debug!(target = target.label(), "cannot sync native tab group without the target window"); + return false; + }; + let Some(anchor_window) = native(anchor) else { + tracing::debug!( + anchor = anchor.label(), + target = target.label(), + "cannot sync native tab group without the anchor window" + ); + return false; + }; without_animation(|| { // Joining into a new tab's desktop window would take the existing group out of full screen. for member in members.iter().filter(|m| m.label() != anchor.label()) { @@ -404,6 +415,7 @@ fn switch_tab_group_now(members: &[WebviewWindow], anchor: &WebviewWindow, targe } } }); + true } fn complete_pending_tab_switch( @@ -414,7 +426,7 @@ fn complete_pending_tab_switch( ) { let pending = PENDING_TAB_SWITCH.with(|slot| PendingTabSwitch::take_matching(&mut slot.borrow_mut(), generation)); let Some(pending) = pending else { return }; - switch_tab_group_now(members, anchor, target); + let _ = switch_tab_group_now(members, anchor, target); // Restore occlusion detection only after `target` is visible on screen so WebKit does not // bounce `ActivityState::IsVisible` through `false` -> `true`. pending.finish(|webview| set_window_occlusion_detection_enabled(webview, true)); @@ -436,8 +448,10 @@ pub fn sync_tab_group( let target = selected.clone(); if MainThreadMarker::new().is_some() { cancel_pending_tab_switch(); - switch_tab_group_now(&members, &anchor, &target); - return Ok(()); + if switch_tab_group_now(&members, &anchor, &target) { + return Ok(()); + } + return Err(tauri::Error::WindowNotFound); } let members_for_setup = members.clone(); @@ -445,8 +459,21 @@ pub fn sync_tab_group( let target_for_setup = target.clone(); let outcome = on_main(selected, move || { cancel_pending_tab_switch(); - let Some(shown) = native(&target_for_setup) else { return PrewarmOutcome::Switched }; - let Some(anchor_window) = native(&anchor_for_setup) else { return PrewarmOutcome::Switched }; + let Some(shown) = native(&target_for_setup) else { + tracing::debug!( + target = target_for_setup.label(), + "cannot sync native tab group without the target window" + ); + return PrewarmOutcome::MissingNative; + }; + let Some(anchor_window) = native(&anchor_for_setup) else { + tracing::debug!( + anchor = anchor_for_setup.label(), + target = target_for_setup.label(), + "cannot sync native tab group without the anchor window" + ); + return PrewarmOutcome::MissingNative; + }; let all_grouped = members_for_setup.iter().all(|m| native(m).is_some_and(|w| same_group(anchor_window, w))); let occluded = !shown.occlusionState().contains(NSWindowOcclusionState::Visible); if anchor_for_setup.label() != target_for_setup.label() && all_grouped && occluded { @@ -486,10 +513,16 @@ pub fn sync_tab_group( } } - switch_tab_group_now(&members_for_setup, &anchor_for_setup, &target_for_setup); - PrewarmOutcome::Switched + if switch_tab_group_now(&members_for_setup, &anchor_for_setup, &target_for_setup) { + PrewarmOutcome::Switched + } else { + PrewarmOutcome::MissingNative + } })?; + if matches!(&outcome, PrewarmOutcome::MissingNative) { + return Err(tauri::Error::WindowNotFound); + } if let PrewarmOutcome::Waiting { generation, rx } = outcome && rx.recv_timeout(TAB_PREWARM_TIMEOUT).is_err() { diff --git a/src-tauri/src/window_groups.rs b/src-tauri/src/window_groups.rs index 9571ecae7e..f9bf63a59a 100644 --- a/src-tauri/src/window_groups.rs +++ b/src-tauri/src/window_groups.rs @@ -136,6 +136,11 @@ pub fn select(app: &AppHandle, caller: &str, target: &str) -> IdeResult<()> { let result = native_select(app, &previous, &to); #[cfg(not(target_os = "macos"))] let result = frames::present(app, &previous, target, &to); + if let Err(error) = &result { + tracing::debug!(caller, target, error = %error.message, "window group select failed"); + } else { + tracing::debug!(caller, target, "window group select succeeded"); + } if result.is_err() { let _ = state.groups.lock().select(caller, &previous.selected); #[cfg(target_os = "macos")] @@ -165,8 +170,60 @@ fn native_select(app: &AppHandle, group: &Group, to: &WebviewWindow) -> IdeResul pub fn join(app: &AppHandle, anchor: &str, new_window: &str) -> IdeResult<()> { let state = app.state::(); - state.groups.lock().join(anchor, new_window)?; - select(app, anchor, new_window) + let rollback = { + let mut groups = state.groups.lock(); + if app.get_webview_window(anchor).is_none() || app.get_webview_window(new_window).is_none() { + tracing::debug!(anchor, new_window, "window group join failed: window closed"); + return Err(IdeError::not_found("Window closed")); + } + prepare_join(&mut groups, anchor, new_window)? + }; + let result = select(app, anchor, new_window); + let rolled_back = result.is_err() && rollback_join(&mut state.groups.lock(), anchor, new_window, &rollback); + if rolled_back { + changed(app); + } + if let Err(error) = &result { + tracing::debug!(anchor, new_window, rolled_back, error = %error.message, "window group join failed"); + } else { + tracing::debug!(anchor, new_window, "window group join succeeded"); + } + result +} + +struct JoinRollback { + already_in_anchor_group: bool, + previous_selected: Option, +} + +fn prepare_join( + groups: &mut ide_workspace::window_groups::WindowGroups, + anchor: &str, + new_window: &str, +) -> IdeResult { + let previous = groups.group(anchor).cloned(); + let already_in_anchor_group = previous.as_ref().is_some_and(|g| g.members.iter().any(|m| m == new_window)); + let previous_selected = previous.map(|g| g.selected); + groups.join(anchor, new_window)?; + Ok(JoinRollback { already_in_anchor_group, previous_selected }) +} + +fn rollback_join( + groups: &mut ide_workspace::window_groups::WindowGroups, + anchor: &str, + member: &str, + rollback: &JoinRollback, +) -> bool { + let mut reverted = false; + if !rollback.already_in_anchor_group { + reverted |= groups.detach(member).is_some(); + } + if let Some(selected) = &rollback.previous_selected + && groups.group(anchor).is_some_and(|g| g.selected != *selected) + { + reverted |= groups.select(anchor, selected).is_ok(); + } + reverted } pub async fn merge(app: &AppHandle, caller: &str) -> IdeResult<()> { @@ -726,3 +783,49 @@ pub async fn restore(app: &AppHandle, caller: &str) -> IdeResult<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::{prepare_join, rollback_join}; + use ide_workspace::window_groups::WindowGroups; + + fn members(values: &[&str]) -> Vec { + values.iter().map(|s| (*s).into()).collect() + } + + #[test] + fn rolling_back_a_join_removes_only_the_new_member_and_restores_selection() { + let mut groups = WindowGroups::default(); + groups.merge(members(&["a", "b"]), "a").unwrap(); + let rollback = prepare_join(&mut groups, "b", "c").unwrap(); + + assert!(rollback_join(&mut groups, "b", "c", &rollback)); + + let group = groups.group("a").unwrap(); + assert_eq!(group.members, members(&["a", "b"])); + assert_eq!(group.selected, "a"); + } + + #[test] + fn rolling_back_the_second_member_dissolves_the_group() { + let mut groups = WindowGroups::default(); + let rollback = prepare_join(&mut groups, "a", "b").unwrap(); + + assert!(rollback_join(&mut groups, "a", "b", &rollback)); + + assert!(groups.group("a").is_none()); + } + + #[test] + fn rolling_back_a_duplicate_join_preserves_existing_group_and_selection() { + let mut groups = WindowGroups::default(); + groups.merge(members(&["a", "b"]), "a").unwrap(); + let rollback = prepare_join(&mut groups, "b", "a").unwrap(); + + assert!(rollback_join(&mut groups, "b", "a", &rollback)); + + let group = groups.group("a").unwrap(); + assert_eq!(group.members, members(&["a", "b"])); + assert_eq!(group.selected, "a"); + } +} diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index c326f4970e..bbcbff8964 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -832,8 +832,14 @@ pub fn document_windows(app: &AppHandle, parent: &str) -> Vec { pub fn close_auxiliary_windows(app: &AppHandle, parent: &str) { for (label, window) in app.webview_windows() { match auxiliary(&label) { - Some((kind, p)) if p == parent && kind.shares_documents() => drop(window.destroy()), - Some((_, p)) if p == parent => drop(window.close()), + Some((kind, p)) if p == parent && kind.shares_documents() => { + tracing::debug!(label, parent, kind = kind.name(), "destroying auxiliary window"); + drop(window.destroy()); + } + Some((kind, p)) if p == parent => { + tracing::debug!(label, parent, kind = kind.name(), "closing auxiliary window"); + drop(window.close()); + } _ => {} } } @@ -1288,12 +1294,28 @@ fn create_window_for( } let window = window?; if let Some(target) = tab_target { - if let Err(err) = crate::window_groups::join(app, target.label(), window.label()) { - let _ = window.show(); - focus(&window); - return Err(err); + match crate::window_groups::join(app, target.label(), window.label()) { + Ok(()) => { + tracing::debug!(target = target.label(), label = window.label(), "joined window group"); + return Ok(window); + } + Err(error) => { + tracing::debug!( + target = target.label(), + label = window.label(), + error = %error.message, + "cannot join window group" + ); + // The window was created hidden for tabbing; show it standalone unless it is gone too. + if window.show().is_err() { + return Err(error); + } + if tab_anchor.is_some() { + focus(&window); + return Err(error); + } + } } - return Ok(window); } focus(&window); Ok(window) diff --git a/src/bindings.ts b/src/bindings.ts index 0ae64ce7fc..df93fa2dbf 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -79,8 +79,8 @@ export const commands = { /** Removes a custom agent's file (registry installs go through `agent_registry_remove`). */ agentCustomRemove: (id: string) => typedError(__TAURI_INVOKE("agent_custom_remove", { id })), /** - * Saves a new custom ACP agent through its agent file; refuses built-in and - * ACP Registry ids and taken ids. + * Saves a new custom ACP agent, or an instance of a built-in agent, through its agent + * file; refuses built-in and ACP Registry ids and taken ids. */ agentCustomSave: (input: CustomAgentInput) => typedError(__TAURI_INVOKE("agent_custom_save", { input })), agentDelete: (task: string, removeWorktree: boolean) => typedError(__TAURI_INVOKE("agent_delete", { task, removeWorktree })), @@ -263,8 +263,8 @@ export const commands = { /** Changes a session setting (model, mode, thinking effort…). */ agentSetConfig: (task: string, option: string, value: string) => typedError(__TAURI_INVOKE("agent_set_config", { task, option, value })), /** - * Environment variables built-in agent `id` starts with (saved in its agent file); - * an empty map clears them. + * Environment variables built-in agent `id`, or an instance of one, starts with (saved in + * its agent file); an empty map clears them. */ agentSetEnv: (id: string, env: { [key in string]: string }) => typedError(__TAURI_INVOKE("agent_set_env", { id, env })), /** Updates per-session MCP server enable/disable overrides on `task`. */ @@ -4616,6 +4616,10 @@ export type AgentProvider_Deserialize = { canSignIn?: boolean, /** The built-in command can be owned by a global npm package. */ canCheckCliUpdate?: boolean, + /** The built-in agent this one is an instance of. */ + base?: string | null, + /** A built-in agent, of which another instance can be added. */ + canDuplicate?: boolean, /** Environment variables it starts with (from its agent file). */ env: { [key in string]: string }, /** Settings (models, modes…) the agent offered last time it ran; empty before its first session. */ @@ -4651,6 +4655,10 @@ export type AgentProvider_Serialize = { canSignIn: boolean, /** The built-in command can be owned by a global npm package. */ canCheckCliUpdate: boolean, + /** The built-in agent this one is an instance of. */ + base?: string | null, + /** A built-in agent, of which another instance can be added. */ + canDuplicate: boolean, /** Environment variables it starts with (from its agent file). */ env: { [key in string]: string }, /** Settings (models, modes…) the agent offered last time it ran; empty before its first session. */ @@ -7331,12 +7339,14 @@ export type CssVariable = { }; /** - * Payload for creating a custom ACP agent (always the ACP driver); the id - * becomes the `/agents/.toml` file name. + * Payload for creating a custom ACP agent, or an instance of built-in `base` (which + * launches as its base does when `command` is empty); the id becomes the + * `/agents/.toml` file name. */ export type CustomAgentInput = { id: string, name: string, + base?: string | null, command: string, args?: string[], env?: { [key in string]: string }, diff --git a/src/editor/lsp/semantic/index.test.ts b/src/editor/lsp/semantic/index.test.ts index bde0559fc0..90e7ad8ba0 100644 --- a/src/editor/lsp/semantic/index.test.ts +++ b/src/editor/lsp/semantic/index.test.ts @@ -11,18 +11,36 @@ const lspSemanticTokens = vi.fn(async () => ({ data: { data: [0, 0, 13, 0, 0], tokenTypes: ["property"], tokenModifiers: [] }, })); +const { settles } = vi.hoisted(() => ({ settles: [] as Array<() => void> })); + vi.mock("@/platform/ipc", async (orig) => { const actual = await orig(); return { ...actual, isTauri: () => true, commands: { ...actual.commands, lspSemanticTokens } }; }); +vi.mock("../availability", async (orig) => { + const actual = await orig(); + return { + ...actual, + onServerSettled: (fn: () => void) => { + settles.push(fn); + return () => { + const i = settles.indexOf(fn); + if (i >= 0) settles.splice(i, 1); + }; + }, + }; +}); + const { semanticExtension } = await import("./index"); const { lspDoc } = await import("../lsp"); +const { IpcError } = await import("@/platform/ipc"); const views: EditorView[] = []; afterEach(() => { views.splice(0).forEach((v) => v.destroy()); vi.clearAllMocks(); + settles.length = 0; vi.useRealTimers(); }); @@ -82,3 +100,22 @@ describe("semantic decorations vs the syntax highlighter", () => { } }); }); + +describe("semantic tokens after a slow server load", () => { + it("asks again when the server settles after a long busy spell", async () => { + vi.useFakeTimers(); + // The request sent while csharp-ls was loading times out; a protocol error, not `unavailable`. + lspSemanticTokens.mockRejectedValueOnce( + new IpcError({ kind: "protocol", message: "csharp-ls: textDocument/semanticTokens/full timed out" }), + ); + const view = await editor([semanticExtension()]); + expect(lspSemanticTokens).toHaveBeenCalledTimes(1); + expect(view.contentDOM.querySelector(".cm-sem-property")).toBeNull(); + // csharp-ls sends no `workspace/semanticTokens/refresh` when the load ends; + // the editor learns of it through the server's long busy spell settling. + for (const settle of settles) settle(); + await vi.advanceTimersByTimeAsync(1000); + expect(lspSemanticTokens).toHaveBeenCalledTimes(2); + expect(view.contentDOM.querySelector(".cm-sem-property")).not.toBeNull(); + }); +}); diff --git a/src/editor/lsp/semantic/index.ts b/src/editor/lsp/semantic/index.ts index f49de8aa9e..41bc76eafc 100644 --- a/src/editor/lsp/semantic/index.ts +++ b/src/editor/lsp/semantic/index.ts @@ -20,7 +20,7 @@ import type { EditorDocContext } from "@/editor/api"; import { commands, type SemanticTokens } from "@/platform/ipc"; import { editorPrefs } from "@/platform/editorSettings"; import { debounce, docOf, isUnavailable, lspRequest } from "../lsp"; -import { featureBackoff, onLspRefresh } from "../availability"; +import { featureBackoff, onLspRefresh, onServerSettled } from "../availability"; import { languageSemantics, type SemanticRange } from "./languages"; import { previewHighlights } from "@/editor/core/cm/renderLineContent"; import { highlightingLevelOf, setHighlightingLevel } from "@/editor/core/cm/localAppearance"; @@ -232,6 +232,7 @@ const semanticPlugin = ViewPlugin.fromClass( class { private refresh = debounce(() => void this.run(), 600); private offReady: () => void; + private offSettled: () => void; private rainbow = editorPrefs().semanticHighlighting; private dimInactive = editorPrefs().dimInactiveCode; private docstringFormat = editorPrefs().docstringFormat; @@ -244,6 +245,11 @@ const semanticPlugin = ViewPlugin.fromClass( if (!this.destroyed) this.decorate(this.view.state.doc, null); }); this.offReady = onLspRefresh("semanticTokens", () => this.refresh()); + // A server whose request timed out while it was loading the project + // (`csharp-ls: textDocument/semanticTokens/full timed out`) sends no + // `workspace/semanticTokens/refresh` when the load ends; ask once its + // long busy spell settles, like the other background features do. + this.offSettled = onServerSettled(() => this.refresh()); // Requests semantic tokens while the view opens. // Later refreshes still use the debounced `refresh`. void this.run(); @@ -363,6 +369,7 @@ const semanticPlugin = ViewPlugin.fromClass( this.destroyed = true; this.refresh.cancel(); this.offReady(); + this.offSettled(); } }, ); diff --git a/src/editor/lsp/semantic/typing.test.ts b/src/editor/lsp/semantic/typing.test.ts index 3f7f45ad3b..be754f1ea9 100644 --- a/src/editor/lsp/semantic/typing.test.ts +++ b/src/editor/lsp/semantic/typing.test.ts @@ -15,6 +15,7 @@ vi.mock("../lsp", async (importOriginal) => ({ vi.mock("../availability", () => ({ featureBackoff: () => ({ active: () => false, mark: () => {} }), onLspRefresh: () => () => {}, + onServerSettled: () => () => {}, })); afterEach(() => { diff --git a/src/features/agents/AgentList.tsx b/src/features/agents/AgentList.tsx index d02cb99660..63c660dcad 100644 --- a/src/features/agents/AgentList.tsx +++ b/src/features/agents/AgentList.tsx @@ -61,6 +61,26 @@ const COPILOT_GITHUB_ACCOUNT_ENV = "OPENIDEA_COPILOT_GITHUB_ACCOUNT"; const launchEnv = (env: Record) => Object.fromEntries(Object.entries(env).filter(([name]) => name !== COPILOT_GITHUB_ACCOUNT_ENV)); +/** The variable that gives a copy of a built-in agent its own configuration directory and sign-in. */ +const CONFIG_DIR_ENV: Record = { + claude: "CLAUDE_CONFIG_DIR", + copilot: "COPILOT_HOME", +}; + +/** Paths in environment variables reach the agent as written: nothing expands `~`. */ +function copyEnvHint(base: string): string { + const variable = CONFIG_DIR_ENV[base]; + return variable + ? tx`Set ${variable} to give this copy its own configuration and sign-in. Paths must be absolute: ~ is not expanded.` + : tx( + "Variables this copy starts with, such as its own configuration directory. Paths must be absolute: ~ is not expanded.", + ); +} + +/** The name of agent `id` in the list, else the id itself. */ +const providerName = (providers: readonly AgentProvider[], id: string | null | undefined) => + id ? (providers.find((p) => p.id === id)?.name ?? id) : null; + /** How often the page checks on installs it did not start. */ const BACKGROUND_POLL_MS = 1500; @@ -149,7 +169,7 @@ function AgentItem({ agent, working }: { agent: Agent; working: boolean }) { : null; return (
- + {agent.name}{" "} {working ? ( @@ -190,6 +210,8 @@ export function AgentList({ const [removing, setRemoving] = useState(null); const [errors, setErrors] = useState>({}); const [adding, setAdding] = useState(false); + const [duplicating, setDuplicating] = useState(null); + const master = useRef(null); const [importing, setImporting] = useState(false); const [notice, setNotice] = useState(null); @@ -232,6 +254,19 @@ export function AgentList({ void refresh().catch((e: unknown) => setError(errorText(e))); onChanged?.(); }, [refresh, onChanged]); + // A new copy is selected, and the keyboard continues from it in the list once its dialog is gone. + const focusList = useRef(false); + useEffect(() => { + if (!focusList.current || duplicating) return; + focusList.current = false; + master.current?.querySelector('[role="listbox"]')?.focus(); + }, [duplicating]); + const duplicated = (id: string) => { + setDuplicating(null); + setSelected(id); + focusList.current = true; + changed(); + }; // Installs started before the page opened: follow them until they end. const background = registry?.agents.some((a) => a.installing) ?? false; @@ -395,7 +430,7 @@ export function AgentList({ return (
-
+
setDuplicating(agent.provider)} onInstall={() => void install(agent)} onRemove={() => void remove(agent)} onRemoveCustom={() => void removeCustom(agent)} @@ -496,6 +533,15 @@ export function AgentList({ }} /> )} + {duplicating && ( + setDuplicating(null)} + onSaved={duplicated} + /> + )}
); } @@ -549,6 +595,8 @@ function Details({ busy, removing, error, + baseName, + onDuplicate, onInstall, onRemove, onRemoveCustom, @@ -562,6 +610,9 @@ function Details({ busy: boolean; removing: boolean; error: string | null; + /** The name of the built-in agent this one is a copy of. */ + baseName: string | null; + onDuplicate: () => void; onInstall: () => void; onRemove: () => void; onRemoveCustom: () => void; @@ -574,7 +625,7 @@ function Details({ const hasCliInstall = !!provider?.cliInstallCommand; const update = registryUpdate(provider, registry); const facts = provider - ? [providerStatus(provider)] + ? [baseName ? tx`Based on ${baseName}` : null, providerStatus(provider)] : [ registry?.version, registry?.distribution ? tx(DISTRIBUTION_LABEL[registry.distribution]) : null, @@ -584,7 +635,7 @@ function Details({ return (
- +

{agent.name}

@@ -626,6 +677,11 @@ function Details({ Update )} + {provider?.canDuplicate && ( + + )} {installed && (
)} - {provider && } + {provider && ( + + )} {registry && (

@@ -720,19 +784,13 @@ function CustomAgentModal({ onSaved: () => void; }) { const uid = useId(); - const [name, setName] = useState(""); - const [id, setId] = useState(""); - const [idTouched, setIdTouched] = useState(false); + const { name, id, changeName, changeId } = useNamedId(""); const [command, setCommand] = useState(""); const [argsText, setArgsText] = useState(""); const [envText, setEnvText] = useState(""); const [saving, setSaving] = useState(false); const [error, setError] = useState(null); - const changeName = (next: string) => { - setName(next); - if (!idTouched) setId(slugifyId(next)); - }; const canSave = name.trim().length > 0 && id.trim().length > 0 && command.trim().length > 0 && !saving; const browse = async () => { @@ -802,16 +860,7 @@ function CustomAgentModal({ hint={Letters, digits, dashes and underscores only; names the agent file.} >

- { - setId(e.target.value); - setIdTouched(true); - }} - /> + changeId(e.target.value)} />
Command} htmlFor={`${uid}-command`}> @@ -857,6 +906,127 @@ function CustomAgentModal({ ); } +/** A name and the agent-file id suggested from it, until the id is edited. */ +function useNamedId(initialName: string) { + const [name, setName] = useState(initialName); + const [id, setId] = useState(() => slugifyId(initialName)); + const [idTouched, setIdTouched] = useState(false); + return { + name, + id, + changeName: (next: string) => { + setName(next); + if (!idTouched) setId(slugifyId(next)); + }, + changeId: (next: string) => { + setId(next); + setIdTouched(true); + }, + }; +} + +/** "Claude Code 2", or the first higher number whose name and id are free. */ +function copyName(base: AgentProvider, providers: readonly AgentProvider[]): string { + const ids = new Set(providers.map((p) => p.id)); + const names = new Set(providers.map((p) => p.name)); + for (let n = 2; ; n++) { + const name = `${base.name} ${n}`; + if (!ids.has(slugifyId(name)) && !names.has(name)) return name; + } +} + +/** Adds a copy of a built-in agent: its launch, with its own name, id and environment. */ +function DuplicateAgentModal({ + base, + providers, + backend, + onClose, + onSaved, +}: { + base: AgentProvider; + providers: readonly AgentProvider[]; + backend: CommandsBackend; + onClose: () => void; + onSaved: (id: string) => void; +}) { + const uid = useId(); + const { name, id, changeName, changeId } = useNamedId(copyName(base, providers)); + const [envText, setEnvText] = useState(""); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + const saved = useRef(false); + const canSave = name.trim().length > 0 && id.trim().length > 0 && !saving; + + const save = async () => { + if (!canSave) return; + setSaving(true); + setError(null); + try { + const input: CustomAgentInput = { + id: id.trim(), + name: name.trim(), + command: "", + base: base.id, + env: parseEnv(envText), + }; + await backend.saveCustom(input); + saved.current = true; + onSaved(input.id); + } catch (e) { + setError(errorText(e)); + } finally { + setSaving(false); + } + }; + + return ( + !saved.current} + buttons={[ + { label: "Duplicate", role: "default", disabled: !canSave, onClick: () => void save() }, + { label: "Cancel", role: "cancel", onClick: onClose }, + ]} + > +
+ {error && ( +

+ {error} +

+ )} + Name} htmlFor={`${uid}-name`}> +
+ changeName(e.target.value)} /> +
+
+ ID} + htmlFor={`${uid}-id`} + hint={Letters, digits, dashes and underscores only; names the agent file.} + > +
+ changeId(e.target.value)} /> +
+
+ Environment variables} htmlFor={`${uid}-env`} hint={copyEnvHint(base.id)}> +
+ setEnvText(e.target.value)} + /> +
+
+
+
+ ); +} + function usesManagedCli(agent: AgentProvider): boolean { return ( agent.source.kind === "builtin" && @@ -876,11 +1046,13 @@ function providerStatus(agent: AgentProvider): string { function ProviderSettings({ agent, + baseName, backend, refresh, onChanged, }: { agent: AgentProvider; + baseName: string | null; backend: CommandsBackend; refresh: () => Promise; onChanged?: () => void; @@ -981,10 +1153,11 @@ function ProviderSettings({ } }, [args.current, argsBase, base, current, saving, refresh]); const launch = - agent.additionalArgs == null && !usesManagedCli(agent) + agent.defaultProgram && agent.additionalArgs == null && !usesManagedCli(agent) ? [agent.defaultProgram, ...agent.defaultArgs].join(" ") : formatArgs([agent.program, ...agent.args]); - const envEditable = agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent"; + const envEditable = + agent.base != null || (agent.commandReadOnlyReason !== "registry" && agent.commandReadOnlyReason !== "customAgent"); const canSignInInIde = agent.installed && (agent.canSignIn ?? false); const signIn = useRef(null); const focusSignIn = useRef(false); @@ -1214,6 +1387,8 @@ function ProviderSettings({ This agent runs through a package runner (npm or uv) and has no executable to choose. ) : agent.commandReadOnlyReason === "registry" ? ( This agent is installed from the ACP Registry, which launches it. + ) : baseName ? ( + tx`Runs the same command as ${baseName}.` ) : ( This agent is configured in its agent file. )} @@ -1248,7 +1423,13 @@ function ProviderSettings({ Environment variables} htmlFor={`agent-env-${agent.id}`} - hint={Override the agent process environment. Applies to new sessions.} + hint={ + agent.base ? ( + copyEnvHint(agent.base) + ) : ( + Override the agent process environment. Applies to new sessions. + ) + } >
o.category === "model"); const model = (modelOption && chosen[modelOption.id]) || modelOption?.current; const rawLevels = (model && agent.thoughtLevels?.[model]) || []; - const modelDefaults = cursorModelDefaults(agent.id, rawLevels); + const modelDefaults = cursorModelDefaults(agent.base ?? agent.id, rawLevels); const levels = rawLevels .filter((o) => o.values.length > 1) .map((o) => { diff --git a/src/features/agents/AgentsView.tsx b/src/features/agents/AgentsView.tsx index c4296cbab6..f1b0eec8d5 100644 --- a/src/features/agents/AgentsView.tsx +++ b/src/features/agents/AgentsView.tsx @@ -46,6 +46,7 @@ import { type OrganizeGroup, } from "./organize"; import { + agentIcon, externalKey, forkExternalSession, importExternalSession, @@ -705,7 +706,7 @@ export function AgentsView() { const tooltip = tooltipParts.join(" · "); return ( - + {matches?.get(n.task.id)?.length ? ( diff --git a/src/features/agents/AutomationDialog.tsx b/src/features/agents/AutomationDialog.tsx index b700cab499..6cbd58006e 100644 --- a/src/features/agents/AutomationDialog.tsx +++ b/src/features/agents/AutomationDialog.tsx @@ -451,7 +451,7 @@ function AutomationDialogBody({ backend }: { backend: AutomationsBackend }) { (catalog ?? selectedProvider)?.thoughtLevels?.[model], modelChoices, providerDefaultsMap, - selectedProvider?.id, + selectedProvider?.base ?? selectedProvider?.id, ) ?? [] ).filter((o) => !isExcludedAutomationOption(o)), ); diff --git a/src/features/agents/AutomationsEditor.tsx b/src/features/agents/AutomationsEditor.tsx index 93ef80a13f..1b074d010c 100644 --- a/src/features/agents/AutomationsEditor.tsx +++ b/src/features/agents/AutomationsEditor.tsx @@ -41,8 +41,8 @@ import { type AutomationsBackend, } from "./automationsModel"; import { useAgentSettings } from "./agentSettings"; -import { AUTOMATIONS_PAGE, providerIcon } from "./model"; -import { openTask, useAgents } from "./store"; +import { AUTOMATIONS_PAGE } from "./model"; +import { agentIcon, openTask, useAgents } from "./store"; import styles from "./Automations.module.css"; const STARTER_TEMPLATES = [ @@ -587,7 +587,7 @@ export function AutomationsEditor({ isAutomationActivelyScheduled(auto) ? tx("Active") : auto.enabled ? tx("Idle") : tx("Paused") } /> - +
diff --git a/src/features/agents/NewTaskTitleItem.tsx b/src/features/agents/NewTaskTitleItem.tsx index 439fbfffcc..837061ee25 100644 --- a/src/features/agents/NewTaskTitleItem.tsx +++ b/src/features/agents/NewTaskTitleItem.tsx @@ -24,7 +24,7 @@ export function NewTaskTitleItem() { id: p.id, label: p.name, verbatim: true, - icon: providerIcon(p.id), + icon: providerIcon(p.id, p.base), checked: p.id === selected?.id, run: () => { if (p.id !== selected?.id) updateDraft({ provider: p.id, config: {} }); @@ -44,7 +44,7 @@ export function NewTaskTitleItem() { shortcut={shortcutLabel("agents.newTask")} onClick={() => void executeAction("agents.newTask")} > - + {tx("New Task")} diff --git a/src/features/agents/agentRegistry.test.tsx b/src/features/agents/agentRegistry.test.tsx index d4d6a66eb4..a207d1f4b0 100644 --- a/src/features/agents/agentRegistry.test.tsx +++ b/src/features/agents/agentRegistry.test.tsx @@ -1623,4 +1623,172 @@ describe("custom agents", () => { ); expect(commands.importAcp).toHaveBeenCalledTimes(1); }); + + describe("copies of a built-in agent", () => { + const claude = (): AgentProvider => ({ ...claudeProvider("claude"), canDuplicate: true }); + const copy = (partial: Partial = {}): AgentProvider => ({ + ...claudeProvider("claude"), + id: "claude-work", + name: "Claude Work", + base: "claude", + defaultProgram: null, + defaultArgs: [], + commandOverridden: false, + commandEditable: false, + commandReadOnlyReason: "customAgent", + canSignIn: true, + canCheckCliUpdate: false, + env: { CLAUDE_CONFIG_DIR: "/Users/me/.claude-work" }, + source: { kind: "custom" }, + ...partial, + }); + const duplicate = async () => { + await waitFor(() => expect(row("Claude Code")).toBeInTheDocument()); + fireEvent.click(within(row("Claude Code")).getByRole("button", { name: "Duplicate…" })); + return screen.findByRole("dialog", { name: "Duplicate Claude Code" }); + }; + const logo = (id: string) => { + const expected = document.createElement("div"); + expected.innerHTML = iconMarkup(id)!; + return expected.querySelector("svg")?.innerHTML; + }; + + it("offers Duplicate… only on agents that can be duplicated", async () => { + const commands = new FakeCommands(); + commands.list = [ + claude(), + { ...claudeProvider("gemini"), id: "gemini", name: "Gemini CLI", defaultProgram: "gemini" }, + customProvider(), + copy(), + ]; + openList(commands); + await waitFor(() => expect(row("Claude Code")).toBeInTheDocument()); + expect(within(row("Claude Code")).getByRole("button", { name: "Duplicate…" })).toBeEnabled(); + for (const name of ["Gemini CLI", "Mine", "Claude Work"]) + expect(within(row(name)).queryByRole("button", { name: "Duplicate…" })).toBeNull(); + }); + + it("suggests a free name and id, and follows the name until the id is edited", async () => { + const commands = new FakeCommands(); + commands.list = [claude(), copy({ id: "claude-code-2", name: "Claude Code 2" })]; + openList(commands); + const dialog = await duplicate(); + const name = within(dialog).getByRole("textbox", { name: "Name" }); + const id = within(dialog).getByRole("textbox", { name: "ID" }); + expect(name).toHaveValue("Claude Code 3"); + expect(id).toHaveValue("claude-code-3"); + expect(name).toHaveFocus(); + expect(within(dialog).queryByRole("textbox", { name: "Command" })).toBeNull(); + expect(within(dialog).queryByRole("textbox", { name: "Arguments" })).toBeNull(); + expect(dialog).toHaveTextContent("Set CLAUDE_CONFIG_DIR to give this copy its own configuration and sign-in."); + expect(dialog).toHaveTextContent("Paths must be absolute: ~ is not expanded."); + fireEvent.change(name, { target: { value: "Claude Work" } }); + expect(id).toHaveValue("claude-work"); + fireEvent.change(id, { target: { value: "work" } }); + fireEvent.change(name, { target: { value: "Claude at Work" } }); + expect(id).toHaveValue("work"); + fireEvent.change(id, { target: { value: "" } }); + expect(within(dialog).getByRole("button", { name: "Duplicate" })).toBeDisabled(); + }); + + it("keeps the environment hint generic for an agent without a known configuration variable", async () => { + const commands = new FakeCommands(); + commands.list = [{ ...claudeProvider("gemini"), id: "gemini", name: "Gemini CLI", canDuplicate: true }]; + openList(commands); + await waitFor(() => expect(row("Gemini CLI")).toBeInTheDocument()); + fireEvent.click(within(row("Gemini CLI")).getByRole("button", { name: "Duplicate…" })); + const dialog = await screen.findByRole("dialog", { name: "Duplicate Gemini CLI" }); + expect(dialog).toHaveTextContent( + "Variables this copy starts with, such as its own configuration directory. Paths must be absolute: ~ is not expanded.", + ); + }); + + it("saves the copy with its base and no command, then selects it", async () => { + const onChanged = vi.fn(); + const commands = new FakeCommands(); + commands.list = [claude()]; + commands.saveCustom.mockImplementation(async () => { + commands.list = [...commands.list, copy()]; + }); + const backend = new FakeBackend(); + dispose = registerSettingsPage({ + id: REGISTRY_PAGE, + title: "Agents", + group: "Tools", + component: () => , + }); + render(); + const dialog = await duplicate(); + fireEvent.change(within(dialog).getByRole("textbox", { name: "Name" }), { target: { value: "Claude Work" } }); + fireEvent.change(within(dialog).getByRole("textbox", { name: "Environment variables" }), { + target: { value: "CLAUDE_CONFIG_DIR=/Users/me/.claude-work" }, + }); + fireEvent.click(within(dialog).getByRole("button", { name: "Duplicate" })); + await waitFor(() => + expect(commands.saveCustom).toHaveBeenCalledWith({ + id: "claude-work", + name: "Claude Work", + command: "", + base: "claude", + env: { CLAUDE_CONFIG_DIR: "/Users/me/.claude-work" }, + }), + ); + await waitFor(() => expect(screen.queryByRole("dialog", { name: "Duplicate Claude Code" })).toBeNull()); + expect(await screen.findByRole("region", { name: "Claude Work" })).toBeInTheDocument(); + expect(item("Claude Work")).toHaveAttribute("aria-selected", "true"); + await waitFor(() => expect(screen.getByRole("listbox", { name: "Agents" })).toHaveFocus()); + expect(onChanged).toHaveBeenCalled(); + }); + + it("shows why the copy cannot be saved and keeps the dialog open", async () => { + const commands = new FakeCommands(); + commands.list = [claude()]; + commands.saveCustom.mockRejectedValueOnce(new Error("there is already an agent 'claude-code-2'")); + openList(commands); + const dialog = await duplicate(); + const env = within(dialog).getByRole("textbox", { name: "Environment variables" }); + fireEvent.change(env, { target: { value: "BROKEN" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Duplicate" })); + expect(await within(dialog).findByRole("alert")).toHaveTextContent("Expected NAME=value: BROKEN"); + expect(commands.saveCustom).not.toHaveBeenCalled(); + fireEvent.change(env, { target: { value: "" } }); + fireEvent.click(within(dialog).getByRole("button", { name: "Duplicate" })); + await waitFor(() => + expect(within(dialog).getByRole("alert")).toHaveTextContent("there is already an agent 'claude-code-2'"), + ); + expect(screen.getByRole("dialog", { name: "Duplicate Claude Code" })).toBeInTheDocument(); + }); + + it("names the copy's base, edits its environment, signs it in and removes it", async () => { + const commands = new FakeCommands(); + commands.list = [claude(), copy()]; + openList(commands); + await waitFor(() => expect(row("Claude Work")).toBeInTheDocument()); + const page = row("Claude Work"); + expect(within(page).getByText("Based on Claude Code · Agent file")).toBeInTheDocument(); + expect(within(page).getByText("Runs the same command as Claude Code.")).toBeInTheDocument(); + const launch = within(page).getByRole("region", { name: "Launch" }); + expect(within(launch).getByText("claude", { selector: "code" })).toBeInTheDocument(); + expect(within(page).getByRole("button", { name: "Sign In…" })).toBeEnabled(); + const env = within(page).getByRole("textbox", { name: "Environment variables" }); + expect(env).toHaveValue("CLAUDE_CONFIG_DIR=/Users/me/.claude-work"); + fireEvent.change(env, { target: { value: "CLAUDE_CONFIG_DIR=/Users/me/.claude-other" } }); + await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" }))); + expect(commands.savedEnv).toEqual([["claude-work", { CLAUDE_CONFIG_DIR: "/Users/me/.claude-other" }]]); + fireEvent.click(within(row("Claude Work")).getByRole("button", { name: "Remove" })); + const confirm = await screen.findByRole("dialog", { name: "Remove Claude Work" }); + fireEvent.click(within(confirm).getByRole("button", { name: "Remove" })); + await waitFor(() => expect(commands.removeCustom).toHaveBeenCalledWith("claude-work")); + }); + + it("shows a copy with the logo of the agent it copies", async () => { + const commands = new FakeCommands(); + commands.list = [claude(), copy(), customProvider()]; + openList(commands); + await waitFor(() => expect(row("Claude Work")).toBeInTheDocument()); + expect(item("Claude Work").querySelector("svg")?.innerHTML).toBe(logo("agent-claude")); + expect(row("Claude Work").querySelector("header svg")?.innerHTML).toBe(logo("agent-claude")); + expect(item("Mine").querySelector("svg")?.innerHTML).toBe(logo("toolwindow-agents")); + }); + }); }); diff --git a/src/features/agents/agents.test.ts b/src/features/agents/agents.test.ts index aaf5ff44c0..04af986e0f 100644 --- a/src/features/agents/agents.test.ts +++ b/src/features/agents/agents.test.ts @@ -102,6 +102,13 @@ describe("providerIcon", () => { it("falls back to the generic agents icon", () => { expect(providerIcon("my-agent")).toBe("toolwindow-agents"); + expect(providerIcon("my-agent", null)).toBe("toolwindow-agents"); + }); + + it("shows a copy of a built-in agent with the logo of the agent it copies", () => { + expect(providerIcon("claude-work", "claude")).toBe("agent-claude"); + expect(providerIcon("copilot-2", "copilot")).toBe("agent-copilot"); + expect(providerIcon("claude-acp-2", "claude-acp")).toBe("agent-claude"); }); }); diff --git a/src/features/agents/index.ts b/src/features/agents/index.ts index 3118ead0ee..69ef0e6e9f 100644 --- a/src/features/agents/index.ts +++ b/src/features/agents/index.ts @@ -40,7 +40,6 @@ import { TASK_DRAG, TOOL_WINDOW, isInterrupted, - providerIcon, } from "./model"; import { openAutomationDialog, @@ -57,6 +56,7 @@ import { cycleFocusedEffort } from "./effortFocus"; import { clearAgentTabFontZoom } from "./fontZoom"; import { activeAgentTasks, + agentIcon, closeActiveTask, closeAndNewTask, connect, @@ -196,7 +196,7 @@ export function activate(): () => void { }, icon: (input) => { const task = useAgents.getState().tasks.get((input.data as { task: string }).task); - return task ? providerIcon(task.provider) : "toolwindow-agents"; + return task ? agentIcon(task.provider) : "toolwindow-agents"; }, // Busy / done marker in the tab's trailing slot (#2233). trailing: (input) => createElement(TaskStatusMark, { task: (input.data as { task: string }).task }), @@ -247,7 +247,7 @@ export function activate(): () => void { title: () => "New Agent Task", icon: (input) => { const task = useAgents.getState().tasks.get((input.data as { task: string }).task); - return task ? providerIcon(task.provider) : "toolwindow-agents"; + return task ? agentIcon(task.provider) : "toolwindow-agents"; }, onTabClose: (tabId) => clearAgentTabFontZoom(tabId), restorable: true, diff --git a/src/features/agents/model.ts b/src/features/agents/model.ts index d143303d0e..239724aaff 100644 --- a/src/features/agents/model.ts +++ b/src/features/agents/model.ts @@ -86,8 +86,12 @@ const ICON_ALIASES: Record = { "opencode-v2": "opencode", }; -/** The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. */ -export function providerIcon(provider: string): string { +/** + * The agent's logo; custom agents get the generic agents icon, Hermes profiles Hermes'. A copy of + * a built-in agent (`base`) shows the logo of the agent it copies. + */ +export function providerIcon(provider: string, base?: string | null): string { + if (base) return providerIcon(base); const id = ICON_ALIASES[provider] ?? (provider.startsWith("hermes-") ? "hermes" : provider); return isIconName(`agent-${id}`) ? `agent-${id}` : "toolwindow-agents"; } diff --git a/src/features/agents/providerOptions.ts b/src/features/agents/providerOptions.ts index 2a58e39696..b8afef17fb 100644 --- a/src/features/agents/providerOptions.ts +++ b/src/features/agents/providerOptions.ts @@ -13,7 +13,7 @@ export const ADD_AGENT = "__addAgent__"; export function providerOptions( providers: readonly AgentProvider[], tx: typeof Tx, - icon: (id: string) => string, + icon: (id: string, base?: string | null) => string, ): SelectOption[] { const version = (p: AgentProvider) => p.source.kind !== "registry" ? undefined : p.source.update ? tx`${p.source.update} available` : p.source.version; @@ -25,7 +25,7 @@ export function providerOptions( verbatim: true, verbatimDetail: true, label: p.name, - icon: icon(p.id), + icon: icon(p.id, p.base), detail: version(p), })), ...(missing.length ? [{ value: "__missing__", label: tx("Not installed"), section: true }] : []), @@ -34,7 +34,7 @@ export function providerOptions( verbatim: true, verbatimDetail: true, label: p.name, - icon: icon(p.id), + icon: icon(p.id, p.base), detail: p.command, })), { value: ADD_AGENT, label: tx("More agents…") }, diff --git a/src/features/agents/session/SessionStatus.tsx b/src/features/agents/session/SessionStatus.tsx index 8f392a374e..35069780dc 100644 --- a/src/features/agents/session/SessionStatus.tsx +++ b/src/features/agents/session/SessionStatus.tsx @@ -7,10 +7,10 @@ import { Icon, IconButton, showContextMenu, T } from "@/ui"; import styles from "../Session.module.css"; import { ContextMeter } from "./ContextMeter"; import { formatSentAt } from "../conversation"; -import { branchLabel, hasTaskTerminal, isBusy, providerIcon, statusLabel } from "../model"; -import { useAgents } from "../store"; +import { branchLabel, hasTaskTerminal, isBusy, statusLabel } from "../model"; +import { agentIcon, useAgents } from "../store"; import { taskMenu } from "../taskActions"; -import { providerName, useNow } from "./shared"; +import { useNow } from "./shared"; /** The task's terminal, at the end of its status line. */ function StatusActions({ task }: { task: AgentTask }) { @@ -50,6 +50,8 @@ export function SessionStatus({ onOpenMemory?: () => void; }) { const tx = useTx(); + const icon = useAgents((s) => agentIcon(task.provider, s.providers)); + const agentName = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.name ?? task.provider); const project = useProject((s) => s.project); const projectRoot = task.projectRoot ?? project?.root ?? null; const projectName = project?.workspace && projectRoot ? basename(projectRoot) : project?.name; @@ -76,9 +78,9 @@ export function SessionStatus({ {/* Where the task works, in one quiet line like the new-task page: project (in a workspace), branch, worktree. */} {/* Which agent runs the task: with several tasks side by side, this tells their answers apart. */} - - - {providerName(task.provider)} + + + {agentName} {project?.workspace && projectName && ( diff --git a/src/features/agents/session/Stream.tsx b/src/features/agents/session/Stream.tsx index ea79685b01..70bcde97b8 100644 --- a/src/features/agents/session/Stream.tsx +++ b/src/features/agents/session/Stream.tsx @@ -29,19 +29,10 @@ import { import { useAgentSettings } from "../agentSettings"; import { clampSelectionToRow } from "./clampSelection"; import { ImageStrip } from "../ImageStrip"; -import { - entriesKey, - isBusy, - providerIcon, - replyTimes, - replyTurns, - subagentWorking, - turnNumbers, - type SubagentEntry, -} from "../model"; +import { entriesKey, isBusy, replyTimes, replyTurns, subagentWorking, turnNumbers, type SubagentEntry } from "../model"; import { selectionIn } from "../selection"; import styles from "../Session.module.css"; -import { useAgents } from "../store"; +import { agentIcon, useAgents } from "../store"; import { thoughtDurations } from "../timeline"; import { conversationRows, isProcessEntry, rowEntries, type ConversationRow, type EntryRow } from "./conversationRows"; import { FindBar } from "./FindBar"; @@ -49,7 +40,7 @@ import { KeepFoldHeader, OpenFolds } from "./Folds"; import { Entry } from "./messages"; import { ProcessRun } from "./ProcessRows"; import { type QuestionAnswer } from "./QuestionForm"; -import { providerName, useRowTask } from "./shared"; +import { useRowTask } from "./shared"; import { WorkingRow } from "./WorkingRow"; /** @@ -805,7 +796,8 @@ export function Stream({ ), [rowTask, lastIndex, busy, thinking, onDiagramDrawn, renderRow], ); - const agentName = providerName(task.provider); + const icon = useAgents((s) => agentIcon(task.provider, s.providers)); + const agentName = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.name ?? task.provider); // Switching tabs changes visibility without changing the conversation rows. const renderedRows = useMemo( () => @@ -824,7 +816,7 @@ export function Stream({ {authorHeaders.has(row.index) && (
- + {agentName}
@@ -838,7 +830,7 @@ export function Stream({
); }), - [rows, authorHeaders, task.provider, agentName, renderConversationRow], + [rows, authorHeaders, icon, agentName, renderConversationRow], ); return ( diff --git a/src/features/agents/session/messages.tsx b/src/features/agents/session/messages.tsx index b8c929276b..df0317a84d 100644 --- a/src/features/agents/session/messages.tsx +++ b/src/features/agents/session/messages.tsx @@ -255,10 +255,11 @@ function AgentErrorEntry({ task, message }: { task: RowTask; message: string }) const [recovering, setRecovering] = useState(false); const text = useAgentErrorText(message); const providerCanSignIn = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.canSignIn ?? false); + const providerBase = useAgents((s) => s.providers.find((p) => p.id === task.provider)?.base ?? task.provider); const entries = useAgents((s) => s.entries.get(task.id)); const canSignIn = isTauri() && providerCanSignIn && isSignInErrorMessage(message); const locked = - task.provider === "codex" && + providerBase === "codex" && task.status === "failed" && task.error === message && message.includes("already has an active writer"); diff --git a/src/features/agents/store.ts b/src/features/agents/store.ts index 43d3f9095e..5c9a762eb7 100644 --- a/src/features/agents/store.ts +++ b/src/features/agents/store.ts @@ -82,6 +82,7 @@ import { isBusy, isInterrupted, isWaitingForNetwork, + providerIcon, sessionKey, upsertEntry, } from "./model"; @@ -267,6 +268,10 @@ export function updateDraft(patch: Partial) { export const providerDefaults = (provider: string | undefined): Record => (provider && useProject.getState().settings?.agents?.defaults?.[provider]) || {}; +/** The logo of agent `id`: a copy of a built-in agent shows the logo of the agent it copies. */ +export const agentIcon = (id: string, providers: readonly AgentProvider[] = useAgents.getState().providers) => + providerIcon(id, providers.find((p) => p.id === id)?.base); + /** * New Task settings use the authoritative catalog, retaining an explicitly selected * model even if it disappears so the user must choose its replacement. @@ -307,7 +312,7 @@ export function draftConfig( (catalog ?? provider)?.thoughtLevels?.[model], draft.thoughtLevels?.[model], defaults, - provider?.id, + provider?.base ?? provider?.id, ) ?? []), ); } diff --git a/src/features/build-tools/BuildToolView.tsx b/src/features/build-tools/BuildToolView.tsx index a0398afd2e..b08f297183 100644 --- a/src/features/build-tools/BuildToolView.tsx +++ b/src/features/build-tools/BuildToolView.tsx @@ -29,10 +29,11 @@ import { mavenChildren, mavenGoalConfig, mavenRoots, + nextProfileChoice, nodeIcon, nodeLabel, pluginCoordinates, - profileChecked, + profileState, withGradleOptions, gradleHasTestTask, type BuildNode, @@ -300,13 +301,14 @@ function NodeRow({ node, state }: { node: BuildNode; state: TreeRowState }) { const mavenSkipTests = useBuild((s) => s.settings.maven.skipTests); const gradleSkipTests = useBuild((s) => s.settings.gradle.skipTests); if (node.kind === "profile") { + const state = profileState(node.profile, choices); return ( e.stopPropagation()} onDoubleClick={(e) => e.stopPropagation()}> setProfile(node.profile, v)} - label={node.profile.id} - className={styles.profile} + checked={state === "default" || state === "enabled"} + onChange={() => setProfile(node.profile, nextProfileChoice(node.profile, choices))} + label={{node.profile.id}} + className={clsx(styles.profile, state === "default" && styles.profileDefault)} /> ); @@ -500,7 +502,7 @@ function BuildToolView({ tool }: { tool: BuildTool }) { renderNode={(n, state) => } onActivate={(n) => { if (n.kind === "profile") { - setProfile(n.profile, !profileChecked(n.profile, useBuild.getState().settings.maven.profiles)); + setProfile(n.profile, nextProfileChoice(n.profile, useBuild.getState().settings.maven.profiles)); return; } if (isRunnable(n)) run([n], "run"); diff --git a/src/features/build-tools/BuildTools.module.css b/src/features/build-tools/BuildTools.module.css index 328d4deeaf..a71030114e 100644 --- a/src/features/build-tools/BuildTools.module.css +++ b/src/features/build-tools/BuildTools.module.css @@ -111,6 +111,12 @@ .profile { min-width: 0; } +/* Implicitly active (activeByDefault / settings.xml activeProfiles) profile: grey check until explicitly toggled. */ +.profileDefault input + [aria-hidden] { + background: var(--bg-checkbox, var(--bg-button)); + box-shadow: inset 0 0 0 1px var(--border-checkbox, var(--control-off)); + color: var(--fg-muted); +} /* Execute Maven Goal / Gradle Task popup */ .popup { diff --git a/src/features/build-tools/model.test.ts b/src/features/build-tools/model.test.ts index 45dd8559f4..396cc4f69d 100644 --- a/src/features/build-tools/model.test.ts +++ b/src/features/build-tools/model.test.ts @@ -16,11 +16,13 @@ import { mavenGoalConfig, mavenRoots, mavenPomAtPath, + nextProfileChoice, nodeIcon, nodeLabel, parseGoalLine, parseTaskLine, profilesArg, + profileState, splitArgs, taskCompletions, withGradleOptions, @@ -222,6 +224,21 @@ describe("Maven runs", () => { it("passes goals, offline, skip tests and changed profiles", () => { expect(profilesArg(maven.profiles, {})).toBeNull(); expect(profilesArg(maven.profiles, { ci: true, dev: false })).toBe("!dev,ci"); + expect(profilesArg(maven.profiles, { dev: true, ci: true })).toBe("dev,ci"); + expect(profilesArg(maven.profiles, { dev: true })).toBe("dev"); + + const def = { id: "test3", activeByDefault: true }; + const opt = { id: "ci", activeByDefault: false }; + expect(profileState(def, {})).toBe("default"); + expect(nextProfileChoice(def, {})).toBe(false); + expect(profileState(def, { test3: false })).toBe("disabled"); + expect(nextProfileChoice(def, { test3: false })).toBe(true); + expect(profileState(def, { test3: true })).toBe("enabled"); + expect(nextProfileChoice(def, { test3: true })).toBeUndefined(); + expect(profileState(opt, {})).toBe("unchecked"); + expect(nextProfileChoice(opt, {})).toBe(true); + expect(nextProfileChoice(opt, { ci: true })).toBeUndefined(); + const config = mavenGoalConfig(core, ["clean", "test"], maven, { offline: true, skipTests: false, diff --git a/src/features/build-tools/model.ts b/src/features/build-tools/model.ts index 41236c89c8..867eebb853 100644 --- a/src/features/build-tools/model.ts +++ b/src/features/build-tools/model.ts @@ -108,18 +108,34 @@ export function profileKey(profile: MavenProfile): string { return profile.projectRoot ? JSON.stringify([profile.projectRoot, profile.id]) : profile.id; } -/** Whether a profile is active for runs: the explicit choice, else `activeByDefault`. */ -export function profileChecked(profile: MavenProfile, choices: Record): boolean { - return choices[profileKey(profile)] ?? profile.activeByDefault; +/** How a Maven profile shows: active by default (grey check), explicitly enabled or disabled, or off. */ +type MavenProfileState = "default" | "enabled" | "disabled" | "unchecked"; + +export function profileState(profile: MavenProfile, choices: Record): MavenProfileState { + const choice = choices[profileKey(profile)]; + if (choice === true) return "enabled"; + if (choice === false) return profile.activeByDefault ? "disabled" : "unchecked"; + return profile.activeByDefault ? "default" : "unchecked"; } -/** `-P` value for the choices that differ from the defaults (`a,!b`), or null. */ +/** + * The choice a click stores: explicitly disabled → enabled → default, as IDEA's Toggle Profile. From + * the default, an active profile becomes explicitly disabled and an inactive one explicitly enabled. + */ +export function nextProfileChoice(profile: MavenProfile, choices: Record): boolean | undefined { + const choice = choices[profileKey(profile)]; + if (choice === false) return true; + if (choice === true) return undefined; + return !profile.activeByDefault; +} + +/** `-P` value for explicit profile choices (`a,!b`), or null. Explicitly enabled default profiles are included so `-P` does not deactivate them. */ export function profilesArg(profiles: readonly MavenProfile[], choices: Record): string | null { const ids: string[] = []; for (const p of profiles) { - const checked = profileChecked(p, choices); - if (checked && !p.activeByDefault) ids.push(p.id); - else if (!checked && p.activeByDefault) ids.push(`!${p.id}`); + const choice = choices[profileKey(p)]; + if (choice === true) ids.push(p.id); + else if (choice === false && p.activeByDefault) ids.push(`!${p.id}`); } return ids.length ? ids.join(",") : null; } diff --git a/src/features/build-tools/profiles.test.tsx b/src/features/build-tools/profiles.test.tsx new file mode 100644 index 0000000000..a9befe3669 --- /dev/null +++ b/src/features/build-tools/profiles.test.tsx @@ -0,0 +1,98 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { useI18n } from "@/platform/i18n"; +import type { BuildModel, MavenModel, ProjectInfo } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { MavenView } from "./BuildToolView"; +import styles from "./BuildTools.module.css"; +import { profilesArg } from "./model"; +import { resetBuild, useBuild } from "./store"; + +vi.mock("@/platform/ipc", async (original) => { + const real = await original(); + return { + ...real, + isTauri: () => true, + call: (value: unknown) => value, + commands: { + ...real.commands, + buildModel: () => Promise.resolve({ maven: null, gradle: [] }), + runConfigs: () => Promise.resolve([]), + buildSync: () => Promise.resolve({ maven: null, gradle: [] }), + cancelRequest: () => Promise.resolve(), + }, + }; +}); + +const maven: MavenModel = { + syncedAt: 1, + stale: false, + syncError: null, + profiles: [ + { id: "dev", activeByDefault: true }, + { id: "test3", activeByDefault: true }, + { id: "luckin", activeByDefault: false }, + ], + projects: [], +}; + +const model: BuildModel = { maven, gradle: [] }; + +beforeEach(() => { + localStorage.clear(); + resetBuild(); + useProject.setState({ project: { root: "/p", trusted: true } as ProjectInfo }); + useBuild.setState({ + root: "/p", + model, + expanded: { maven: new Set(["mvn:profiles"]), gradle: new Set() }, + }); +}); + +afterEach(() => { + resetBuild(); +}); + +it("renders activeByDefault profiles with a grey default check, cycles through -P! and explicit -P, and never translates profile IDs", () => { + const prevTexts = useI18n.getState().texts; + useI18n.setState({ texts: { ...prevTexts, dev: "开发" } }); + try { + render(); + + // Profile IDs stay verbatim even when a locale contains a translation for "dev". + const devBox = screen.getByRole("checkbox", { name: "dev" }); + const test3Box = screen.getByRole("checkbox", { name: "test3" }); + const luckinBox = screen.getByRole("checkbox", { name: "luckin" }); + + const defaultClass = styles.profileDefault!; + expect(devBox).toBeChecked(); + expect(devBox.closest("label")).toHaveClass(defaultClass); + expect(test3Box).toBeChecked(); + expect(test3Box.closest("label")).toHaveClass(defaultClass); + expect(luckinBox).not.toBeChecked(); + expect(luckinBox.closest("label")).not.toHaveClass(defaultClass); + + // Click test3 once: default (grey) -> explicitly disabled (unchecked, passed as !test3). + act(() => fireEvent.click(test3Box)); + expect(test3Box).not.toBeChecked(); + expect(profilesArg(maven.profiles, useBuild.getState().settings.maven.profiles)).toBe("!test3"); + + // Click luckin too: it is passed next to !test3. + act(() => fireEvent.click(luckinBox)); + expect(profilesArg(maven.profiles, useBuild.getState().settings.maven.profiles)).toBe("!test3,luckin"); + + // Click test3 again: explicitly disabled -> explicitly enabled (solid check, included in -P). + act(() => fireEvent.click(test3Box)); + expect(test3Box).toBeChecked(); + expect(test3Box.closest("label")).not.toHaveClass(defaultClass); + expect(profilesArg(maven.profiles, useBuild.getState().settings.maven.profiles)).toBe("test3,luckin"); + + // Click test3 a third time: explicitly enabled -> back to default (grey check). + act(() => fireEvent.click(test3Box)); + expect(test3Box).toBeChecked(); + expect(test3Box.closest("label")).toHaveClass(defaultClass); + expect(profilesArg(maven.profiles, useBuild.getState().settings.maven.profiles)).toBe("luckin"); + } finally { + useI18n.setState({ texts: prevTexts }); + } +}); diff --git a/src/features/build-tools/store.ts b/src/features/build-tools/store.ts index ee3d16e3b7..18d23beecb 100644 --- a/src/features/build-tools/store.ts +++ b/src/features/build-tools/store.ts @@ -148,10 +148,15 @@ export const PROFILE_RELOAD_DELAY_MS = 800; let profileReload: ReturnType | undefined; const profileRoots = new Set(); -export function setProfile(profile: string | MavenProfile, checked: boolean) { +export function setProfile(profile: string | MavenProfile, checked: boolean | undefined) { const id = typeof profile === "string" ? profile : profileKey(profile); const projectRoot = typeof profile === "string" ? null : (profile.projectRoot ?? null); - updateSettings((s) => ({ ...s, maven: { ...s.maven, profiles: { ...s.maven.profiles, [id]: checked } } })); + updateSettings((s) => { + const profiles = { ...s.maven.profiles }; + if (checked === undefined) delete profiles[id]; + else profiles[id] = checked; + return { ...s, maven: { ...s.maven, profiles } }; + }); // The Java language server and Build Project resolve the project with the profiles of the // last sync, so a new choice reloads it (IDEA re-imports on a profile change too). scheduleMavenReload(projectRoot); diff --git a/src/features/code-insight/UsagesPopup.tsx b/src/features/code-insight/UsagesPopup.tsx index 931a76d4af..da1e0b1d78 100644 --- a/src/features/code-insight/UsagesPopup.tsx +++ b/src/features/code-insight/UsagesPopup.tsx @@ -228,9 +228,11 @@ function UsagesPopupInner() {
{symbol ? tx`Usages of ${symbol}` : tx("Usages")}{" "} - - {filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`} - + {(total > 0 || !loading) && ( + + {filter || items.length !== total ? tx`${items.length} of ${total} found` : tx`${total} found`} + + )}
@@ -309,9 +311,11 @@ function UsagesPopupInner() {
{filter ? tx`Nothing matches '${filter}'` - : loading && !total - ? tx("Searching for usages…") - : tx("No usages match the access filters")} + : total + ? tx("No usages match the access filters") + : loading + ? tx("Searching for usages…") + : tx("No usages found")}
} renderItem={(u) => ( diff --git a/src/features/code-insight/usagesPopup.test.tsx b/src/features/code-insight/usagesPopup.test.tsx index 5b528ab1bd..e1fcd3ecd6 100644 --- a/src/features/code-insight/usagesPopup.test.tsx +++ b/src/features/code-insight/usagesPopup.test.tsx @@ -362,6 +362,7 @@ it("opens while a slow search has found nothing yet, and closes when it ends wit await act(() => new Promise((r) => setTimeout(r, 350))); expect(useUsagesPopup.getState()).toMatchObject({ open: true, loading: true, groups: [] }); expect(screen.getByText("Searching for usages…")).toBeInTheDocument(); + expect(screen.queryByText("0 found")).not.toBeInTheDocument(); await act(async () => { resolve({ locations, incomplete: null }); await pending; @@ -385,6 +386,25 @@ it("opens while a slow search has found nothing yet, and closes when it ends wit expect(calls.slice(before)).toEqual(["hint No usages of 'used' found"]); }); +it("shows the count once a search in the open popup ends with none", async () => { + render(); + const at = (line: number) => ({ ...loc, range: { start: { line, col: 4 }, end: { line, col: 8 } } }); + referenceResponse.mockResolvedValueOnce({ locations: [], incomplete: null, librariesSkipped: true }); + await showUsagesPopup(); + referenceResponse.mockResolvedValueOnce({ locations: [at(1), at(2)], incomplete: null }); + await act(() => showUsagesPopup()); + expect(useUsagesPopup.getState()).toMatchObject({ open: true, scope: "libraries" }); + expect(screen.getByText("2 found")).toBeInTheDocument(); + referenceResponse.mockResolvedValueOnce({ locations: [], incomplete: null, librariesSkipped: true }); + await act(async () => setUsagesPopupScope("project")); + await vi.waitFor(() => expect(useUsagesPopup.getState()).toMatchObject({ loading: false, scope: "project" })); + expect(useUsagesPopup.getState().open).toBe(true); + expect(screen.getByText("0 found")).toBeInTheDocument(); + expect(screen.getByText("No usages found")).toBeInTheDocument(); + expect(screen.queryByText("No usages match the access filters")).toBeNull(); + act(() => dismissUsagesPopup()); +}); + it("searches Project Files, and Project and Libraries when invoked again", async () => { render(); const at = (line: number) => ({ ...loc, range: { start: { line, col: 4 }, end: { line, col: 8 } } }); diff --git a/src/features/database/CsvEditor.tsx b/src/features/database/CsvEditor.tsx index 67113290f3..571dbc73c6 100644 --- a/src/features/database/CsvEditor.tsx +++ b/src/features/database/CsvEditor.tsx @@ -8,8 +8,8 @@ import clsx from "clsx"; import { editorsFor } from "@/editor/api"; import { tx } from "@/platform/i18n"; import { Checkbox, Tabs, T } from "@/ui"; -import type { CsvTable } from "./csv"; -import { useCsvModes, useCsvVersions, type CsvMode } from "./csvModes"; +import { csvCellAt, type CsvTable } from "./csv"; +import { useCsvModes, useCsvReveals, useCsvVersions, type CsvMode } from "./csvModes"; import { DataView, type DataPanel } from "./DataView"; import styles from "./Database.module.css"; @@ -22,6 +22,16 @@ function CsvData({ path }: { path: string }) { const [failed, setFailed] = useState(false); const [panel, setPanel] = useState(null); const [searchOpen, setSearchOpen] = useState(false); + // A navigation into the text while the table is shown (Find in Files, Go to Line) selects its cell. + const reveal = useCsvReveals((s) => s[path]); + const [shownFrom] = useState(() => useCsvReveals.getState()[path]?.seq ?? 0); + const revealCell = useMemo(() => { + if (!table || !reveal || reveal.seq <= shownFrom) return null; + const text = editorsFor(path)[0]?.view.state.doc.toString(); + const cell = text == null ? null : csvCellAt(text, table.delimiter, reveal.offset); + const row = cell ? cell.record - (table.header ? 1 : 0) : -1; + return cell && row >= 0 && cell.col < table.columns.length ? { row, col: cell.col } : null; + }, [table, reveal, path, shownFrom]); useEffect(() => { const text = editorsFor(path)[0]?.view.state.doc.toString(); @@ -67,6 +77,7 @@ function CsvData({ path }: { path: string }) { onPanelChange={setPanel} searchOpen={searchOpen} onSearchOpenChange={setSearchOpen} + revealCell={revealCell} aria-label={tx("Table view of the file")} />
diff --git a/src/features/database/DataView.tsx b/src/features/database/DataView.tsx index 4e3191964e..3070433884 100644 --- a/src/features/database/DataView.tsx +++ b/src/features/database/DataView.tsx @@ -208,6 +208,8 @@ export interface DataViewProps extends Pick< searchOpen?: boolean; onSearchOpenChange?: (open: boolean) => void; revealColumn?: GridProps["revealColumn"]; + /** A new object selects that cell of the loaded rows, wherever sorting put it; nothing when a filter hides it. */ + revealCell?: { row: number; col: number } | null; "aria-label"?: string; } @@ -261,6 +263,14 @@ export function DataView(props: DataViewProps) { return base.filter((r) => rowMatches(r, columns.length, value, test)); }, [shaped, test, search.filterRows, rowCount, columns.length, value]); const at = (r: number) => (order ? order[r]! : r); + const { revealCell } = props; + const gridReveal = useMemo(() => { + if (!revealCell) return null; + const row = order ? order.indexOf(revealCell.row) : revealCell.row; + return row < 0 ? null : { row, col: revealCell.col }; + // A new request only, not a reshaped table. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [revealCell]); const shown = order ? order.length : rowCount; const extractor = props.extractor; const copySelectedCells = @@ -324,6 +334,7 @@ export function DataView(props: DataViewProps) { currentMatch={currentMatch} onFind={onSearchOpenChange && openSearch} revealColumn={props.revealColumn} + revealCell={gridReveal} aria-label={props["aria-label"]} columns={columns} rowCount={shown} diff --git a/src/features/database/Grid.test.tsx b/src/features/database/Grid.test.tsx index 3c5298a9c6..362ccdd275 100644 --- a/src/features/database/Grid.test.tsx +++ b/src/features/database/Grid.test.tsx @@ -1239,3 +1239,39 @@ describe("the data view's context menu (DataGrip)", () => { expect(writeText).toHaveBeenCalledExactlyOnceWith("WHERE city = 'Beijing'"); }); }); + +describe("revealing a cell", () => { + it("selects the cell a navigation asks for, each request once", () => { + const rows = [ + ["Alice", "London"], + ["Bob", "Tokyo"], + ["Charlie", "Paris"], + ]; + const props = { + columns: [ + { name: "name", type: "" }, + { name: "city", type: "" }, + ], + rowCount: rows.length, + value: (r: number, c: number) => rows[r]![c]!, + panel: null, + onPanelChange: () => {}, + }; + const selected = () => + screen + .getAllByRole("gridcell") + .filter((c) => c.getAttribute("aria-selected") === "true") + .map((c) => c.textContent); + const { rerender } = render(); + expect(selected()).toEqual([]); + rerender(); + expect(selected()).toEqual(["Tokyo"]); + fireEvent.mouseDown( + screen.getAllByRole("gridcell").find((c) => c.textContent === "Alice")!, + { button: 0 }, + ); + expect(selected()).toEqual(["Alice"]); + rerender(); + expect(selected()).toEqual(["Paris"]); + }); +}); diff --git a/src/features/database/Grid.tsx b/src/features/database/Grid.tsx index 9bbfe8817e..28344eb0ce 100644 --- a/src/features/database/Grid.tsx +++ b/src/features/database/Grid.tsx @@ -109,6 +109,8 @@ export interface GridProps { onFind?: () => void; /** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */ revealColumn?: { col: number } | null; + /** A new object selects that cell, scrolls to it and focuses the grid (a navigation into the text behind it). */ + revealCell?: { row: number; col: number } | null; /** Horizontal scroll offset to restore on mount, when a caller keeps view state across mounts. */ initialScrollLeft?: number; /** Reports horizontal scroll changes to a caller that keeps view state across mounts. */ @@ -298,6 +300,24 @@ export function Grid(props: GridProps) { // Runs once per request. // eslint-disable-next-line react-hooks/exhaustive-deps }, [revealColumn]); + const { revealCell } = props; + // Focused once the cell is selected: focusing with no selection yet selects the first cell. + const focusRevealed = useRef(false); + useEffect(() => { + if (!revealCell || revealCell.row >= rowCount) return; + const { row, col } = revealCell; + setSel({ r0: row, c0: col, r1: row, c1: col }); + focusRevealed.current = true; + virtualizer.scrollToIndex(row, { align: "center" }); + scrollColumnIntoView(col); + // Runs once per request. + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [revealCell]); + useEffect(() => { + if (!focusRevealed.current || !sel) return; + focusRevealed.current = false; + scrollRef.current?.focus({ preventScroll: true }); + }, [sel]); const totalWidth = useMemo(() => numberWidth + widths.reduce((a, b) => a + b, 0), [numberWidth, widths]); const template = `${numberWidth}px ${widths.map((w) => `${w}px`).join(" ")}`; // Retried as columns are measured, until the content is wide enough to reach the offset. diff --git a/src/features/database/csv.test.ts b/src/features/database/csv.test.ts index cacf8b257f..76fb2658c0 100644 --- a/src/features/database/csv.test.ts +++ b/src/features/database/csv.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { detectDelimiter, looksLikeHeader, parseCsv } from "./csv"; +import { csvCellAt, detectDelimiter, looksLikeHeader, parseCsv } from "./csv"; const BOM = String.fromCharCode(0xfeff); @@ -56,3 +56,25 @@ describe("csv", () => { expect([forced.header, forced.rows.length]).toEqual([false, 2]); }); }); + +describe("csvCellAt", () => { + const text = 'name,age,city\nAlice,20,London\n\nBob,25,"Tokyo, ""JP"""\r\nCharlie,30,"Paris\nFR"\n'; + const at = (needle: string) => csvCellAt(text, ",", text.indexOf(needle)); + + it("finds the record and field of an offset as parseCsv reads them", () => { + const { rows } = parseCsv(text, "x.csv"); + expect(at("city")).toEqual({ record: 0, col: 2 }); + expect(at("London")).toEqual({ record: 1, col: 2 }); + // The blank line is skipped; quoted delimiters, doubled quotes and CRLF stay inside one field. + expect(at("Bob")).toEqual({ record: 2, col: 0 }); + expect(at("JP")).toEqual({ record: 2, col: 2 }); + expect(rows[1]![2]).toBe('Tokyo, "JP"'); + // A line break inside quotes doesn't end the record. + expect(at("FR")).toEqual({ record: 3, col: 2 }); + expect(rows[2]![2]).toBe("Paris\nFR"); + }); + + it("is null on a blank line", () => { + expect(csvCellAt(text, ",", text.indexOf("\n\n") + 1)).toBeNull(); + }); +}); diff --git a/src/features/database/csv.ts b/src/features/database/csv.ts index 78e87b3d24..7cd80f8c73 100644 --- a/src/features/database/csv.ts +++ b/src/features/database/csv.ts @@ -65,3 +65,36 @@ export function parseCsv(text: string, path: string, header?: boolean): CsvTable for (const r of rows) while (r.length < width) r.push(""); return { delimiter, header: named, columns, rows }; } + +/** + * The record and field the text offset `at` falls in, counted the way `parseCsv` reads the file + * (blank lines skipped, the header row included); null on a blank line. + */ +export function csvCellAt(text: string, delimiter: string, at: number): { record: number; col: number } | null { + let record = 0; + let col = 0; + let length = 0; + let quoted = false; + let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; + for (; i < text.length && i < at; i++) { + const ch = text[i]!; + if (quoted) { + if (ch !== '"') length++; + else if (text[i + 1] === '"') { + length++; + i++; + } else quoted = false; + } else if (ch === '"' && length === 0) quoted = true; + else if (ch === delimiter) { + col++; + length = 0; + } else if (ch === "\n" || ch === "\r") { + if (ch === "\r" && text[i + 1] === "\n") i++; + if (col > 0 || length > 0) record++; + col = 0; + length = 0; + } else length++; + } + const blank = !quoted && col === 0 && length === 0 && (at >= text.length || text[at] === "\n" || text[at] === "\r"); + return blank ? null : { record, col }; +} diff --git a/src/features/database/csvModes.ts b/src/features/database/csvModes.ts index cdcac5ff0b..ae65db1978 100644 --- a/src/features/database/csvModes.ts +++ b/src/features/database/csvModes.ts @@ -9,6 +9,10 @@ export type CsvMode = "text" | "data"; export const useCsvModes = create>(() => ({})); export const useCsvSourceHidden = (tabId: string) => useCsvModes((s) => s[tabId] === "data"); +/** The last caret a navigation placed in each CSV file's text (Find in Files, Go to Line…). */ +export const useCsvReveals = create>(() => ({})); +let revealSeq = 0; + /** Bumped when a CSV file's text changes. */ export const useCsvVersions = create>(() => ({})); const bump = (path: string) => useCsvVersions.setState((s) => ({ [path]: (s[path] ?? 0) + 1 })); @@ -27,6 +31,8 @@ export function registerCsvLiveSource(): () => void { bump(ctx.path); } update(u: ViewUpdate) { + if (u.transactions.some((tr) => tr.isUserEvent("select.reveal"))) + useCsvReveals.setState({ [ctx.path]: { offset: u.state.selection.main.head, seq: ++revealSeq } }); if (!u.docChanged) return; clearTimeout(this.timer); this.timer = setTimeout(() => bump(ctx.path), TEXT_DELAY); diff --git a/src/features/project-tree/model.test.ts b/src/features/project-tree/model.test.ts index a0e255332f..2b919270f9 100644 --- a/src/features/project-tree/model.test.ts +++ b/src/features/project-tree/model.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import type { FileEntry } from "@/bindings"; +import { useProject } from "@/platform/project"; import { DEFAULT_TREE_OPTIONS, buildModel, @@ -68,6 +69,36 @@ describe("buildModel", () => { ]); }); + it("reuses file rows until the listing or the view settings change", () => { + const folder = "/r/files"; + const first = entry(folder + "/first.txt", "file", { mtimeMs: 1 }); + const second = entry(folder + "/second.txt", "file", { mtimeMs: 2 }); + const other = "/r/other"; + const original = listings({ "/r": [entry(folder, "dir"), entry(other, "dir")], [folder]: [first, second] }); + const loaded = new Map(original).set(other, [entry(other + "/child.txt")]); + const before = buildModel(ROOT, original, DEFAULT_TREE_OPTIONS); + const after = buildModel(ROOT, loaded, DEFAULT_TREE_OPTIONS); + const sorted = buildModel(ROOT, loaded, { ...DEFAULT_TREE_OPTIONS, sortBy: "modified" }); + const updated = buildModel(ROOT, new Map(loaded).set(folder, [second]), DEFAULT_TREE_OPTIONS); + const settings = useProject.getState().settings; + let filtered: ReturnType; + try { + useProject.setState({ settings: { ...settings, files: { ...settings?.files, ignoredNames: ["second.txt"] } } }); + filtered = buildModel(ROOT, loaded, DEFAULT_TREE_OPTIONS); + } finally { + useProject.setState({ settings }); + } + + expect(after.children.get(folder)).toBe(before.children.get(folder)); + expect(after.byKey.get(first.path)).toBe(before.byKey.get(first.path)); + expect(after.keyOfPath.get(first.path)).toBe(first.path); + expect(labels(sorted, folder)).toEqual(["second.txt", "first.txt"]); + expect(labels(updated, folder)).toEqual(["second.txt"]); + expect(updated.byKey.has(first.path)).toBe(false); + expect(labels(filtered, folder)).toEqual(["first.txt"]); + expect(filtered.keyOfPath.has(second.path)).toBe(false); + }); + it("sorts names naturally, optionally mixing folders and files", () => { const l = listings({ "/r": [entry("/r/b", "dir"), entry("/r/a10.txt"), entry("/r/a2.txt"), entry("/r/c.txt")], diff --git a/src/features/project-tree/model.ts b/src/features/project-tree/model.ts index 481e53559e..a91ae8df44 100644 --- a/src/features/project-tree/model.ts +++ b/src/features/project-tree/model.ts @@ -5,6 +5,7 @@ */ import type { FileEntry, OutlineItem } from "@/bindings"; import { isIgnoredName } from "@/platform/ignoredNames"; +import { useProject } from "@/platform/project"; import { ancestorsWithin, insideAnyOf, isInside, isSameOrInside, nameOf, parentOf, relativeTo } from "./paths"; export interface TreeOptions { @@ -209,20 +210,7 @@ export function buildModel( const makeNode = (entry: FileEntry): ProjectNode => { const dir = isDirEntry(entry); - if (!dir) { - return { - key: entry.path, - path: entry.path, - chain: [entry.path], - label: entry.name, - dir: false, - root: false, - entry, - ignored: entry.ignored, - excluded: entry.excluded, - symlink: entry.kind === "symlink", - }; - } + if (!dir) return fileNode(entry); const chain = [entry.path]; const names = [entry.name]; let end = entry; @@ -264,20 +252,30 @@ export function buildModel( excludeRootNames && node === rootNode ? listing.filter((e) => !excludeRootNames.has(e.name.toLowerCase())) : listing; + const creating = placeholder?.parent === node.path ? placeholder : null; + const files = entries === listing && !creating ? fileChildren(listing, opts) : undefined; + if (files) { + children.set(node.key, files); + for (const file of files) { + byKey.set(file.key, file); + keyOfPath.set(file.path, file.key); + } + return; + } const kids = visibleEntries(entries, opts).map(makeNode); - if (placeholder && placeholder.parent === node.path) { + if (creating) { const ph: ProjectNode = { key: node.path + PLACEHOLDER_SUFFIX, path: node.path, chain: [], label: "", - dir: placeholder.kind === "dir", + dir: creating.kind === "dir", root: false, entry: null, ignored: false, excluded: false, symlink: false, - placeholder: placeholder.kind, + placeholder: creating.kind, }; kids.unshift(ph); } @@ -294,6 +292,39 @@ export function buildModel( return { roots: [rootNode], children, byKey, keyOfPath }; } +interface FileChildren { + options: TreeOptions; + ignoredNames: readonly string[] | undefined; + nodes: ProjectNode[] | undefined; +} + +const filesByListing = new WeakMap(); + +function fileChildren(listing: readonly FileEntry[], options: TreeOptions): ProjectNode[] | undefined { + const ignoredNames = useProject.getState().settings?.files?.ignoredNames; + const cached = filesByListing.get(listing); + if (cached?.options === options && cached.ignoredNames === ignoredNames) return cached.nodes; + // Folder rows can depend on another listing through compacted chains. File rows depend only here. + const nodes = listing.some(isDirEntry) ? undefined : visibleEntries(listing, options).map(fileNode); + filesByListing.set(listing, { options, ignoredNames, nodes }); + return nodes; +} + +function fileNode(entry: FileEntry): ProjectNode { + return { + key: entry.path, + path: entry.path, + chain: [entry.path], + label: entry.name, + dir: false, + root: false, + entry, + ignored: entry.ignored, + excluded: entry.excluded, + symlink: entry.kind === "symlink", + }; +} + /** A contributed root (scratches, External Libraries) or one of its child entries. */ export interface ExtraRoot { id?: string; diff --git a/src/features/settings/__tests__/dialog.test.tsx b/src/features/settings/__tests__/dialog.test.tsx index e998fb7f30..681ae9490b 100644 --- a/src/features/settings/__tests__/dialog.test.tsx +++ b/src/features/settings/__tests__/dialog.test.tsx @@ -853,6 +853,17 @@ describe("Settings dialog", () => { const nav = within(psDialog).getByRole("navigation", { name: "Project Structure sections" }); expect(within(nav).getByText("Project Settings")).toBeInTheDocument(); expect(within(nav).getByText("Platform Settings")).toBeInTheDocument(); + const navIcons = within(nav) + .getAllByRole("button") + .map((button) => button.querySelector("svg")!); + expect(navIcons).toHaveLength(7); + for (const icon of navIcons) { + expect(icon).toHaveAttribute("width", "14"); + expect(icon).toHaveAttribute("height", "14"); + expect(icon.innerHTML).toContain("currentColor"); + expect(icon.innerHTML).not.toMatch(/#[0-9a-f]{3,8}\b/i); + } + expect(new Set(navIcons.map((icon) => icon.innerHTML)).size).toBe(navIcons.length); expect(within(nav).getByRole("button", { name: "Project" })).toHaveAttribute("aria-current", "page"); await act(async () => { fireEvent.click(within(nav).getByRole("button", { name: "Modules" })); diff --git a/src/features/settings/languages/ProjectStructurePage.tsx b/src/features/settings/languages/ProjectStructurePage.tsx index 0c6cbc7104..3626783fae 100644 --- a/src/features/settings/languages/ProjectStructurePage.tsx +++ b/src/features/settings/languages/ProjectStructurePage.tsx @@ -2144,7 +2144,7 @@ const NAV_GROUPS: Array<{ { id: "project", label: "Project", - icon: "folder", + icon: "toolwindow-project", searchLabels: [ "Project name", "Project SDK", @@ -2158,7 +2158,7 @@ const NAV_GROUPS: Array<{ { id: "modules", label: "Modules", - icon: "module", + icon: "module-outline", searchLabels: [ ...MODULE_SEARCH_LABELS.sources, ...MODULE_SEARCH_LABELS.paths, @@ -2168,19 +2168,19 @@ const NAV_GROUPS: Array<{ { id: "dependencies", label: "Dependencies", - icon: "build-dependencies", + icon: "hierarchy", searchLabels: ["Project Dependencies", "Add Project…"], }, { id: "libraries", label: "Libraries", - icon: "folder-library", + icon: "library-outline", searchLabels: ["Library Details", "Resolved Build & SDK Libraries", "Classes", "Sources", "Scope", "JAR"], }, { id: "facets", label: "Facets", - icon: "file-config", + icon: "layers", searchLabels: [ "Framework Facets", "Framework", @@ -2194,7 +2194,7 @@ const NAV_GROUPS: Array<{ { id: "artifacts", label: "Artifacts", - icon: "file-archive", + icon: "artifact", searchLabels: [ "Packaging Artifacts", "JAR", diff --git a/src/features/tools/__tests__/expired.test.ts b/src/features/tools/__tests__/expired.test.ts index fab6574202..930577f79a 100644 --- a/src/features/tools/__tests__/expired.test.ts +++ b/src/features/tools/__tests__/expired.test.ts @@ -11,7 +11,8 @@ vi.mock("../store", async (orig) => ({ installTool: store.installTool, })); -const { isExpiredBuild, promptUpdateExpired } = await import("../expired"); +const { installExpiredServerPrompts, isExpiredBuild, promptUpdateExpired } = await import("../expired"); +const { emitLocalIdeEvent } = await import("@/platform/ipc"); const { provideNotificationService } = await import("@/workbench/contributions"); type Note = Parameters[0]; @@ -67,4 +68,25 @@ describe("expired language server builds", () => { await promptUpdateExpired("kotlin-lsp"); expect(notes.at(-1)!.actions?.map((a) => a.label)).toEqual(["Language Servers…"]); }); + + it("ask once when a running build reports that it expired", async () => { + store.tool = { ...KOTLIN, status: "installed" }; + const off = installExpiredServerPrompts(); + const message = "This build of kotlin-lsp has expired and stops working soon; update it."; + const status = (status: "ready" | "busy" | "starting", msg: string | null) => + emitLocalIdeEvent({ type: "languageServer", server: 4, name: "kotlin-lsp", status, message: msg }); + status("ready", null); + status("busy", message); + status("ready", message); + await vi.waitFor(() => expect(notes).toHaveLength(1)); + expect(notes[0]!.body).toBe( + "This build of Kotlin LSP (JetBrains) has expired and stops working soon. Update it to the latest release?", + ); + expect(notes[0]!.actions?.map((a) => a.label)).toEqual(["Update", "Language Servers…"]); + // A restarted instance asks again. + status("starting", null); + status("ready", message); + await vi.waitFor(() => expect(notes).toHaveLength(2)); + off(); + }); }); diff --git a/src/features/tools/expired.ts b/src/features/tools/expired.ts index a8b0a64829..ad88f8f2af 100644 --- a/src/features/tools/expired.ts +++ b/src/features/tools/expired.ts @@ -1,6 +1,7 @@ /** * "kotlin-lsp has expired — Update": JetBrains preview builds stop starting once their date - * passes, and the backend then stops restarting them. Offer the latest release instead. + * passes, and the backend then stops restarting them. One already running keeps its process but + * stops serving after a short grace period; its status says so. Offer the latest release instead. * A managed copy comes before `PATH` (Homebrew), so installing it also replaces one found there. */ import { executeAction } from "@/platform/actions"; @@ -13,7 +14,8 @@ export const isExpiredBuild = (message: string | null) => !!message && /This bui export const expiredKey = (name: string) => `lsp-expired-${name}`; -export async function promptUpdateExpired(name: string) { +/** `running`: the build expired while running, so it still serves for a short while. */ +export async function promptUpdateExpired(name: string, running = false) { await refreshTools(); const tool = toolByName(name); const display = tool?.displayName ?? name; @@ -23,11 +25,17 @@ export async function promptUpdateExpired(name: string) { group: "lsp", level: "warning", title: tx`${display} has expired`, - body: !installable - ? tx`This build of ${display} no longer starts. Choose a newer build in Language Servers.` - : tool.status === "installed" - ? tx`This build of ${display} no longer starts. Update it to the latest release?` - : tx`This build of ${display} no longer starts. Install the latest release for the IDE? It is used instead of ${tool.path ?? tool.command}.`, + body: running + ? !installable + ? tx`This build of ${display} has expired and stops working soon. Choose a newer build in Language Servers.` + : tool.status === "installed" + ? tx`This build of ${display} has expired and stops working soon. Update it to the latest release?` + : tx`This build of ${display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of ${tool.path ?? tool.command}.` + : !installable + ? tx`This build of ${display} no longer starts. Choose a newer build in Language Servers.` + : tool.status === "installed" + ? tx`This build of ${display} no longer starts. Update it to the latest release?` + : tx`This build of ${display} no longer starts. Install the latest release for the IDE? It is used instead of ${tool.path ?? tool.command}.`, key, sticky: true, actions: [ @@ -45,7 +53,15 @@ export async function promptUpdateExpired(name: string) { } export function installExpiredServerPrompts(): () => void { + // A running instance's status repeats its message on every Ready ⇄ Busy change: ask once. + const asked = new Set(); return onIdeEvent("languageServer", (e) => { - if (e.status === "crashed" && isExpiredBuild(e.message)) void promptUpdateExpired(e.name); + if (e.status === "starting") asked.delete(e.server); + if (!isExpiredBuild(e.message)) return; + if (e.status === "crashed") void promptUpdateExpired(e.name); + else if ((e.status === "ready" || e.status === "busy") && !asked.has(e.server)) { + asked.add(e.server); + void promptUpdateExpired(e.name, true); + } }); } diff --git a/src/features/vcs/LogSettingsPage.tsx b/src/features/vcs/LogSettingsPage.tsx index f70ccad693..ed97c4f36f 100644 --- a/src/features/vcs/LogSettingsPage.tsx +++ b/src/features/vcs/LogSettingsPage.tsx @@ -15,6 +15,10 @@ const OPTIONS: { key: Flag; label: string }[] = [ { key: "refsOnLeft", label: "Show references on the left" }, ]; +const BRANCHES: { key: Flag; label: string }[] = [ + { key: "branchClickFilters", label: "Update branch filter on single click" }, +]; + const COLUMNS: { key: Flag; label: string }[] = [ { key: "showAuthor", label: "Author" }, { key: "showHash", label: "Hash" }, @@ -43,6 +47,7 @@ export function LogSettingsPage() { return (
{OPTIONS.map(flag)} + {BRANCHES.map(flag)} {COLUMNS.map(flag)}
); diff --git a/src/features/vcs/__tests__/logBranches.test.tsx b/src/features/vcs/__tests__/logBranches.test.tsx index 1261a8bcb1..5c7d0a8168 100644 --- a/src/features/vcs/__tests__/logBranches.test.tsx +++ b/src/features/vcs/__tests__/logBranches.test.tsx @@ -46,6 +46,7 @@ import { ContextMenuHost, iconMarkup } from "@/ui"; import syncStyles from "../BranchSync.module.css"; import { BranchesPanel } from "../log/BranchesPanel"; import { FilterBar } from "../log/FilterBar"; +import { setLogOptions } from "../logOptions"; import { useBranchesPane } from "../logPaneActions"; import { emptyFilters, useGitLog } from "../logStore"; import { useVcs } from "../store"; @@ -113,6 +114,35 @@ describe("Git Log branches pane", () => { expect(screen.getByText("feature").closest("[data-row]")).toHaveAttribute("aria-selected", "true"); }); + it("one click filters the log when branchClickFilters is enabled, ignoring group rows", () => { + setLogOptions({ branchClickFilters: true }); + try { + render(); + fireEvent.mouseDown(screen.getByText("feature")); + expect(useGitLog.getState().filters.branches).toEqual(["feature"]); + fireEvent.mouseDown(screen.getByText("Local")); + expect(useGitLog.getState().filters.branches).toEqual(["feature"]); + fireEvent.mouseDown(screen.getByText("main")); + expect(useGitLog.getState().filters.branches).toEqual(["main"]); + } finally { + setLogOptions({ branchClickFilters: false }); + } + }); + + it("right click selects the branch without changing the log filter when branchClickFilters is enabled", () => { + setLogOptions({ branchClickFilters: true }); + try { + render(); + fireEvent.mouseDown(screen.getByText("feature")); + expect(useGitLog.getState().filters.branches).toEqual(["feature"]); + fireEvent.mouseDown(screen.getByText("main"), { button: 2 }); + expect(useGitLog.getState().filters.branches).toEqual(["feature"]); + expect(screen.getByText("main").closest("[data-row]")).toHaveAttribute("aria-selected", "true"); + } finally { + setLogOptions({ branchClickFilters: false }); + } + }); + it("collapses and expands every group from the toolbar", () => { render(); expect(screen.getByText("feature")).toBeInTheDocument(); diff --git a/src/features/vcs/__tests__/logPanes.test.tsx b/src/features/vcs/__tests__/logPanes.test.tsx index aabfee7cbc..89112b3af7 100644 --- a/src/features/vcs/__tests__/logPanes.test.tsx +++ b/src/features/vcs/__tests__/logPanes.test.tsx @@ -558,5 +558,7 @@ describe("Settings › Version Control › Log", () => { expect(useLogOptions.getState().tagNames).toBe(!DEFAULT_LOG_OPTIONS.tagNames); fireEvent.click(screen.getByLabelText("Hash")); expect(useLogOptions.getState().showHash).toBe(!DEFAULT_LOG_OPTIONS.showHash); + fireEvent.click(screen.getByLabelText("Update branch filter on single click")); + expect(useLogOptions.getState().branchClickFilters).toBe(!DEFAULT_LOG_OPTIONS.branchClickFilters); }); }); diff --git a/src/features/vcs/__tests__/rewordMerge.test.ts b/src/features/vcs/__tests__/rewordMerge.test.ts new file mode 100644 index 0000000000..3e44c4bd05 --- /dev/null +++ b/src/features/vcs/__tests__/rewordMerge.test.ts @@ -0,0 +1,134 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { BranchInfo, Commit } from "@/bindings"; + +const mocks = vi.hoisted(() => ({ + vcsBranchInfo: vi.fn<(repo: string | null) => Promise>(), + vcsBranches: vi.fn<() => Promise>(), + vcsMergeBase: vi.fn<(repo: string | null, a: string, b: string) => Promise>(), + vcsReword: vi.fn<(repo: string | null, id: string, msg: string) => Promise<{ before: string; after: string }>>(), + promptCommitMessage: vi.fn<() => Promise>(), + showError: vi.fn(), + notify: vi.fn(), + refreshNow: vi.fn(async () => {}), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + call: (p: Promise) => p, + commands: { + ...actual.commands, + vcsBranchInfo: (repo: string | null) => mocks.vcsBranchInfo(repo), + vcsBranches: () => mocks.vcsBranches(), + vcsMergeBase: (repo: string | null, a: string, b: string) => mocks.vcsMergeBase(repo, a, b), + vcsReword: (repo: string | null, id: string, msg: string) => mocks.vcsReword(repo, id, msg), + }, + }; +}); + +vi.mock("../CommitMessageDialog", () => ({ + promptCommitMessage: (...args: unknown[]) => (mocks.promptCommitMessage as (...a: unknown[]) => unknown)(...args), +})); + +vi.mock("@/workbench/messages", () => ({ + ask: vi.fn(), + showError: (...args: unknown[]) => mocks.showError(...args), +})); + +vi.mock("@/workbench/contributions", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + notifications: () => ({ notify: mocks.notify }), + }; +}); + +vi.mock("../store", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + currentRepo: () => "/repo", + refreshNow: () => mocks.refreshNow(), + useVcs: { getState: () => ({ root: "/repo" }) }, + }; +}); + +const { editCommitMessage } = await import("../rebase"); + +function makeCommit(id: string, parents: string[], message = "Merge branch 'main' into dev"): Commit { + return { + id, + shortId: id.slice(0, 8), + parents, + author: "Dev", + email: "dev@example.com", + timeMs: 0, + summary: message.split("\n")[0]!, + message, + messageTruncated: false, + refs: [], + }; +} + +function makeBranch(headCommit: string): BranchInfo { + return { + head: "dev", + headCommit, + upstream: null, + ahead: 0, + behind: 0, + operation: null, + }; +} + +describe("editCommitMessage on merge commits", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.vcsBranches.mockResolvedValue([]); + mocks.promptCommitMessage.mockResolvedValue("Merged main into dev (custom)"); + mocks.vcsReword.mockResolvedValue({ before: "m1111111", after: "m2222222" }); + }); + + it("allows editing the commit message of a merge commit at HEAD", async () => { + const merge = makeCommit("m1111111", ["p1", "p2"]); + mocks.vcsBranchInfo.mockResolvedValue(makeBranch(merge.id)); + + await editCommitMessage(merge); + + expect(mocks.showError).not.toHaveBeenCalled(); + expect(mocks.promptCommitMessage).toHaveBeenCalledWith( + "Edit Commit Message", + expect.stringContaining("m1111111"), + merge.message, + ); + expect(mocks.vcsReword).toHaveBeenCalledWith("/repo", merge.id, "Merged main into dev (custom)"); + }); + + it("allows editing an earlier merge commit in the current branch", async () => { + const merge = makeCommit("m1111111", ["p1", "p2"]); + mocks.vcsBranchInfo.mockResolvedValue(makeBranch("head9999")); + mocks.vcsMergeBase.mockResolvedValue(merge.id); + mocks.vcsReword.mockResolvedValue({ before: "head9999", after: "headnew0" }); + + await editCommitMessage(merge); + + expect(mocks.showError).not.toHaveBeenCalled(); + expect(mocks.vcsMergeBase).toHaveBeenCalledWith("/repo", merge.id, "head9999"); + expect(mocks.vcsReword).toHaveBeenCalledWith("/repo", merge.id, "Merged main into dev (custom)"); + }); + + it("refuses commits not in the current branch", async () => { + const other = makeCommit("side1111", ["p1", "p2"]); + mocks.vcsBranchInfo.mockResolvedValue(makeBranch("head9999")); + mocks.vcsMergeBase.mockResolvedValue("base0000"); + + await editCommitMessage(other); + + expect(mocks.showError).toHaveBeenCalledWith( + "Cannot edit commit message", + "The commit is not in the current branch", + ); + expect(mocks.vcsReword).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/vcs/log/BranchesPanel.tsx b/src/features/vcs/log/BranchesPanel.tsx index ffda7adf15..a8f1c8af44 100644 --- a/src/features/vcs/log/BranchesPanel.tsx +++ b/src/features/vcs/log/BranchesPanel.tsx @@ -27,6 +27,7 @@ import { summarizeBranchSync, type BranchSyncSummary } from "../branchSyncState" import { FetchButton } from "../FetchButton"; import styles from "../GitLog.module.css"; import { LogIdContext } from "../logContext"; +import { useLogOptions } from "../logOptions"; import { canUpdateBranch, useBranchesPane, type BranchTarget } from "../logPaneActions"; import { reloadLog, scopedLogRepositories, setLogBranches, setLogFilters, useGitLog } from "../logStore"; import { branchesByRepo } from "../multiRoot"; @@ -87,6 +88,7 @@ function sharedHead(roots: readonly string[]): string | null { export function BranchesPanel() { const scope = useContext(LogIdContext); + const branchClickFilters = useLogOptions((s) => s.branchClickFilters); const shown = useGitLog((s) => s.shownLog); const active = !scope || scope === shown; const logGeneration = useGitLog((s) => s.generation); @@ -475,7 +477,16 @@ export function BranchesPanel() { }} getTooltip={(n) => mergedRefTooltip(n, (r) => repoName(branchRoots[r] ?? r))} selected={selected} - onSelectionChange={(sel) => setSelected(sel)} + onSelectionChange={(sel, _lead, reason) => { + setSelected(sel); + if (!branchClickFilters || reason === "contextMenu") return; + const branchTargets = refs.filter((r) => sel.has(r.key)).map(({ ref, repo }) => ({ ref, repo })); + if (!branchTargets.length) return; + setLogFilters({ + branches: [...new Set(branchTargets.map(({ ref }) => ref))], + branchTargets: branchTargets.some(({ repo }) => repo) ? branchTargets : undefined, + }); + }} onActivate={(n) => { if (!n.ref) return; const activated = selected.has(n.key) ? targets : expand(n, scopedRepo); diff --git a/src/features/vcs/logOptions.ts b/src/features/vcs/logOptions.ts index a56277d18b..f4b3e457f7 100644 --- a/src/features/vcs/logOptions.ts +++ b/src/features/vcs/logOptions.ts @@ -34,6 +34,8 @@ export interface LogOptions { highlightCurrentBranch: boolean; /** The Branches pane on the left of the log. */ showBranches: boolean; + /** Single-clicking a branch in the Branches pane updates the log's branch filter. */ + branchClickFilters: boolean; /** Changed files grouped by directory (else a flat list). */ groupByDirectory: boolean; /** Selecting a changed file updates the embedded preview or an open editor preview. */ @@ -74,6 +76,7 @@ export const DEFAULT_LOG_OPTIONS: LogOptions = { highlightMerges: true, highlightCurrentBranch: true, showBranches: true, + branchClickFilters: false, groupByDirectory: true, diffPreview: true, showLineStats: false, @@ -101,6 +104,7 @@ const APPLICATION_LOG_OPTION_KEYS = [ "showHash", "showSignature", "showGitHubChecks", + "branchClickFilters", "diffPreview", "changesFromParents", "diffLocation", diff --git a/src/features/vcs/rebase.tsx b/src/features/vcs/rebase.tsx index 4f20b3771f..8c8cd4d3a8 100644 --- a/src/features/vcs/rebase.tsx +++ b/src/features/vcs/rebase.tsx @@ -283,9 +283,61 @@ async function runRebase(range: RewriteRange, entries: RebaseEntry[], done: stri ); } +/** Validates and prepares `target` for rewording (supports merge commits without interactive rebase). */ +async function rewordRange(target: Commit): Promise { + const repo = commitRepo(target) ?? currentRepo(); + const refusal = tx(rewriteRefusals["edit commit message"]); + await refreshNow(); + try { + const branch = await call(commands.vcsBranchInfo(repo)); + const op = inProgress(branch.operation); + if (op) { + refuse(refusal, `A ${op} is in progress`); + return null; + } + const head = branch.headCommit; + if (!head) { + refuse(refusal, "The commit is not in the current branch"); + return null; + } + if (target.id !== head) { + const base = await call(commands.vcsMergeBase(repo, target.id, head)).catch(() => null); + if (base !== target.id) { + refuse(refusal, "The commit is not in the current branch"); + return null; + } + } + const protectedProblem = await protectedHistoryProblem(repo, target.id); + if (protectedProblem) { + refuse(refusal, protectedProblem); + return null; + } + const range: RewriteRange = { + base: target.parents[0] ?? null, + commits: target.id === head ? [target] : [target, { ...target, id: head }], + repo, + branch: branch.head, + refusal, + }; + if (await rangeTouchesUpstream(branch, range, repo)) { + const ok = await confirmDialog({ + title: "Edit Commit Message", + message: pushedWarning("Edit Commit Message", branch), + okLabel: "Continue", + danger: true, + }); + if (!ok) return null; + } + return range; + } catch (e) { + refuse(refusal, e instanceof Error ? e.message : String(e)); + return null; + } +} + /** Edit Commit Message…: rewords one commit of the current branch. */ export async function editCommitMessage(commit: Commit) { - const range = await rangeFrom(commit, "edit commit message"); + const range = await rewordRange(commit); if (!range) return; // A paged log only carries the summary line: load the full message so the // dialog edits subject and body, not the subject alone (#2238). diff --git a/src/features/vcs/settingsPages.ts b/src/features/vcs/settingsPages.ts index 4058a0fc60..32c1ffbbf0 100644 --- a/src/features/vcs/settingsPages.ts +++ b/src/features/vcs/settingsPages.ts @@ -16,7 +16,7 @@ export function activateSettingsPages(): () => void { id: "vcs.log", title: "Log", order: 6, - keywords: ["git log", "references", "tags", "columns", "commit time"], + keywords: ["git log", "references", "tags", "columns", "commit time", "branches", "branch filter", "single click"], component: lazyComponent(() => import("./LogSettingsPage").then((m) => m.LogSettingsPage)), }); return () => { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 7b1ce6da57..15a2c3daaf 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2116,6 +2116,13 @@ "Remove {name} from this computer? Its tasks stay, but can't continue until it is installed again.": "Remove {name} from this computer? Its tasks stay, but can't continue until it is installed again.", "ACP Registry · {version}": "ACP Registry · {version}", "Agent file": "Agent file", + "Duplicate…": "Duplicate…", + "Duplicate": "Duplicate", + "Duplicate {name}": "Duplicate {name}", + "Based on {baseName}": "Based on {baseName}", + "Runs the same command as {baseName}.": "Runs the same command as {baseName}.", + "Set {variable} to give this copy its own configuration and sign-in. Paths must be absolute: ~ is not expanded.": "Set {variable} to give this copy its own configuration and sign-in. Paths must be absolute: ~ is not expanded.", + "Variables this copy starts with, such as its own configuration directory. Paths must be absolute: ~ is not expanded.": "Variables this copy starts with, such as its own configuration directory. Paths must be absolute: ~ is not expanded.", "Launch": "Launch", "This agent is installed from the ACP Registry, which launches it.": "This agent is installed from the ACP Registry, which launches it.", "{version} is available": "{version} is available", @@ -4288,6 +4295,8 @@ "Cannot read the whole values": "Cannot read the whole values", "The result changed since this page was read. Run the query again.": "The result changed since this page was read. Run the query again.", "View Options": "View Options", + "Branches pane": "Branches pane", + "Update branch filter on single click": "Update branch filter on single click", "Visible columns": "Visible columns", "Install Ruff to optimize imports in Python files": "Install Ruff to optimize imports in Python files", "Optimize Imports (Ruff)": "Optimize Imports (Ruff)", @@ -5661,5 +5670,8 @@ "Changelist:": "Changelist:", "Clone Sources": "Clone Sources", "Could not load the {label} icon": "Could not load the {label} icon", - "plugin {pluginId}: {e}": "plugin {pluginId}: {e}" + "plugin {pluginId}: {e}": "plugin {pluginId}: {e}", + "This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.": "This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.", + "This build of {display} has expired and stops working soon. Update it to the latest release?": "This build of {display} has expired and stops working soon. Update it to the latest release?", + "This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index f9502afd60..32ea301cc5 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6847,6 +6847,8 @@ "{removed} lines deleted": "删除了 {removed} 行", "Show commit time rather than author time": "显示提交时间而非作者时间", "Show references on the left": "在左侧显示引用", + "Branches pane": "分支面板", + "Update branch filter on single click": "单击时更新分支过滤", "Visible columns": "可见列", "Open Repository Version": "打开仓库版本", "Open the selected files as they exist after the change": "打开所选文件在该更改之后的版本", @@ -9176,6 +9178,11 @@ "Import acp.json": "导入 acp.json", "Select executable": "选择可执行文件", "Add Custom Agent": "添加自定义 Agent", + "Duplicate {name}": "复制 {name}", + "Based on {baseName}": "基于 {baseName}", + "Runs the same command as {baseName}.": "与 {baseName} 运行相同的命令。", + "Set {variable} to give this copy its own configuration and sign-in. Paths must be absolute: ~ is not expanded.": "设置 {variable} 可让此副本使用独立的配置和登录。路径必须是绝对路径:~ 不会被展开。", + "Variables this copy starts with, such as its own configuration directory. Paths must be absolute: ~ is not expanded.": "此副本启动时使用的环境变量,例如它自己的配置目录。路径必须是绝对路径:~ 不会被展开。", "My agent": "我的 Agent", "ID": "ID", "Letters, digits, dashes and underscores only; names the agent file.": "仅限字母、数字、短横线和下划线;用作 Agent 文件名。", @@ -12564,5 +12571,8 @@ "Included changes": "包含的更改", "Clone Sources": "克隆来源", "Could not load the {label} icon": "无法加载 {label} 图标", - "plugin {pluginId}: {e}": "插件 {pluginId}:{e}" + "plugin {pluginId}: {e}": "插件 {pluginId}:{e}", + "This build of {display} has expired and stops working soon. Choose a newer build in Language Servers.": "此版本的 {display} 已过期,很快将停止工作。请在“语言服务器”中选择更新的版本。", + "This build of {display} has expired and stops working soon. Update it to the latest release?": "此版本的 {display} 已过期,很快将停止工作。要更新到最新版本吗?", + "This build of {display} has expired and stops working soon. Install the latest release for the IDE? It is used instead of {path}.": "此版本的 {display} 已过期,很快将停止工作。要为 IDE 安装最新版本吗?安装后将代替 {path} 使用。" } diff --git a/src/platform/locales/textCatalog.test.ts b/src/platform/locales/textCatalog.test.ts index 5619911559..3fe9ab45fc 100644 --- a/src/platform/locales/textCatalog.test.ts +++ b/src/platform/locales/textCatalog.test.ts @@ -331,6 +331,7 @@ const COMPLETE_LOCALES = new Set(["zh"]); const TEMPLATES_AS_WRITTEN = new Set([ "{name} (#[cfg(test)])", // Rust attribute after a module name "HEAD ({renamedFrom})", // Git revision and a path + "var({m}) = {fill}", // a CSS custom property and the color it resolves to ]); /** diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index f82cdbd400..b8ec4bf243 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -359,6 +359,8 @@ const ICONS = { quote: "openidea/general/quote", settings: "general/settings", "project-structure": "openidea/general/projectStructure", + "module-outline": "openidea/general/moduleOutline", + "library-outline": "openidea/general/libraryOutline", help: "openidea/general/help", "page-first": "openidea/general/pageFirst", "page-last": "openidea/general/pageLast", diff --git a/src/ui/openidea/general/libraryOutline.svg b/src/ui/openidea/general/libraryOutline.svg new file mode 100644 index 0000000000..c0bab1ee98 --- /dev/null +++ b/src/ui/openidea/general/libraryOutline.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/src/ui/openidea/general/moduleOutline.svg b/src/ui/openidea/general/moduleOutline.svg new file mode 100644 index 0000000000..56520617cf --- /dev/null +++ b/src/ui/openidea/general/moduleOutline.svg @@ -0,0 +1,6 @@ + + + + + +