From b1ab5afa6793d7c9d6a4905f981feb6eab2fe391 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Fri, 27 Nov 2026 00:00:19 +0800 Subject: [PATCH] feat(plugins): Services menus on the IDE's own nodes and plugin executors (API 1.18) (#6216) services.context and services.toolbar menus let plugins act on the IDE's own Services nodes (run configurations, Docker containers): when keys per selected service (serviceProvider, serviceKind, serviceId, serviceName, serviceRunning, runConfigurationId, serviceSelectionCount) and the selection as the command's JSON argument, through a new workbench registerServiceSelectionItems registry fed by ServiceProviderContribution.context. executor = "" on [[contributes.javaAgents]] binds the agent to a plugin executor: Run/Debug '<name>' with <title> beside Run and Debug (run widget, gutter, context menus, Services), the only launches that get the agent. The launch carries the plugin id (RunConfig.executor, or executor in the debug launch extras); the java.agent grant and jar pin are unchanged; without the grant the IDE asks instead of launching. The Services menu of a run configuration now also lists its executors (Coverage, Profile). Fixes #4528 --- crates/ide-host/src/ops/debug.rs | 31 ++- crates/ide-host/src/ops/run.rs | 5 +- crates/ide-host/src/plugins/java_agents.rs | 60 +++++- crates/ide-host/src/plugins/mod.rs | 1 + crates/ide-host/src/plugins/types.rs | 4 + crates/ide-host/src/plugins/ui_points.rs | 34 ++- crates/ide-host/tests/plugins.rs | 39 ++++ crates/ide-run/src/config.rs | 1 + crates/ide-run/src/java_agent.rs | 71 ++++++- crates/ide-run/src/lib.rs | 6 + docs/en/plugins/guides/commands.mdx | 48 +++-- docs/en/plugins/manifest.mdx | 64 +++--- docs/en/plugins/versioning.mdx | 42 ++-- docs/zh/plugins/guides/commands.mdx | 44 ++-- docs/zh/plugins/manifest.mdx | 2 +- docs/zh/plugins/versioning.mdx | 42 ++-- plugins/README.md | 115 +++++++--- src/bindings.ts | 15 ++ src/features/debugger/java.ts | 6 +- .../plugins/__tests__/serviceMenus.test.tsx | 196 ++++++++++++++++++ src/features/plugins/executors.ts | 139 +++++++++++++ src/features/plugins/index.ts | 3 + src/features/plugins/uiPoints.tsx | 74 ++++++- src/features/run/executors.ts | 10 +- src/features/run/services.test.ts | 34 ++- src/features/run/services.tsx | 26 +++ src/features/services/ServicesTree.test.tsx | 32 ++- src/features/services/docker.tsx | 12 ++ src/features/services/selection.ts | 40 +++- src/platform/locales/text/zh.json | 11 +- src/workbench/contributions.ts | 46 ++++ 31 files changed, 1105 insertions(+), 148 deletions(-) create mode 100644 src/features/plugins/__tests__/serviceMenus.test.tsx create mode 100644 src/features/plugins/executors.ts diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index a0ec5bf569..9bf9dc599b 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -34,9 +34,10 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide }; let mut config = config; let enhanced = take_enhanced_redefinition(&mut config); + let executor = take_executor(&mut config); let java_exec = java_exec_path(&config); let mut agents = if is_jvm_launch(&config) { - ide_run::java_agent::current_for(java_exec.as_deref()) + ide_run::java_agent::current_for_executor(java_exec.as_deref(), executor.as_deref()) } else { ide_run::java_agent::Agents::default() }; @@ -271,6 +272,19 @@ fn take_enhanced_redefinition(config: &mut LaunchConfig) -> Option<Result<&'stat .then(|| ide_run::java_hotswap::enhanced_redefinition(java_exec_path(config).as_deref())) } +/// The plugin executor the session launches through (`executor` in the launch extras, which +/// this removes): its plugin's executor-bound Java agent loads only then. +fn take_executor(config: &mut LaunchConfig) -> Option<String> { + let Some(serde_json::Value::Object(mut extra)) = + config.extra_json.as_deref().and_then(|e| serde_json::from_str(e).ok()) + else { + return None; + }; + let executor = extra.remove("executor")?; + config.extra_json = Some(serde_json::Value::Object(extra).to_string()); + executor.as_str().filter(|s| !s.is_empty()).map(str::to_owned) +} + /// Plugins' Java agents ([`ide_run::java_agent`]) after the configuration's VM options: /// java-debug's and java-analyzer's `vmArgs` (one line, or a list) or the Kotlin debugger's /// `vmArguments` (a list). @@ -995,6 +1009,21 @@ mod tests { } } + #[test] + fn the_executor_is_taken_out_of_the_launch_extras() { + let extras = |config: &LaunchConfig| { + serde_json::from_str::<serde_json::Value>(config.extra_json.as_deref().unwrap()).unwrap() + }; + let mut config = + launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g", "executor": "acme.reload"})); + assert_eq!(take_executor(&mut config).as_deref(), Some("acme.reload")); + assert!(extras(&config).get("executor").is_none(), "not passed on to the adapter"); + assert_eq!(extras(&config)["vmArgs"], "-Xmx1g"); + let mut plain = launch("java-debug", "launch", serde_json::json!({"vmArgs": "-Xmx1g"})); + assert_eq!(take_executor(&mut plain), None); + assert_eq!(extras(&plain)["vmArgs"], "-Xmx1g"); + } + #[test] fn debug_server_port_only_for_local_java_debug() { let port = |adapter: &str, request: &str, extra| debug_server_port(&launch(adapter, request, extra)); diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 43aa2ebf72..06247f3e2d 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -559,7 +559,8 @@ async fn start_inner( /// Plugins' Java agents (`[[contributes.javaAgents]]`, granted `java.agent`) for the JVM of an /// Application, Spring Boot or JAR Application configuration started on this machine. A JVM on a -/// run target gets none; the console says so, and why an approved agent was left out. +/// run target gets none; the console says so, and why an approved agent was left out. A launch +/// through a plugin executor (`extras.executor`) also gets that plugin's executor-bound agent. fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_dir: Option<&Path>) { if !ide_run::java_agent::applies(&config.kind) { return; @@ -575,7 +576,7 @@ fn add_java_agents(config: &mut RunConfig, on_output: &Emit<OutputChunk>, run_di .or_else(|| std::env::var_os("JAVA_HOME").map(std::path::PathBuf::from)); ide_run::java_agent::launched_java(&config.command, &search, home.as_deref()) }); - let agents = ide_run::java_agent::current_for(java.as_deref()); + let agents = ide_run::java_agent::current_for_executor(java.as_deref(), config.extras.executor.as_deref()); let say = |text: &str| on_output(OutputChunk::System { text: format!("{text}\n") }); if run_dir.is_none() { if !agents.options.is_empty() { diff --git a/crates/ide-host/src/plugins/java_agents.rs b/crates/ide-host/src/plugins/java_agents.rs index a450d98d4a..d299755564 100644 --- a/crates/ide-host/src/plugins/java_agents.rs +++ b/crates/ide-host/src/plugins/java_agents.rs @@ -8,8 +8,13 @@ //! args = "optional-arguments" # optional //! vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] # optional, API 1.14 //! jdk = "jetbrains" # optional: only those VM options on JBR +//! executor = "Hot Reload" # optional, API 1.18: see below //! ``` //! +//! With `executor`, the agent is not added to every launch: the plugin contributes an +//! executor beside Run and Debug ("Run with Hot Reload", "Debug with Hot Reload"), and only +//! launches through it get the agent and its `vmOptions`. +//! //! One agent per plugin. The declaration derives the optional high-risk `java.agent` //! capability; granting it records the jar's hash, and a launch adds the agent only //! while the jar still has it ([`ide_run::java_agent`]). @@ -28,6 +33,7 @@ pub const POINT_ID: &str = "javaAgents"; const MAX_ARGS: usize = 4096; const MAX_VM_OPTION: usize = 512; const MAX_VM_OPTIONS: usize = 32; +const MAX_EXECUTOR: usize = 40; #[derive(Clone, Debug, Deserialize)] #[serde(deny_unknown_fields)] @@ -39,6 +45,8 @@ struct Decl { vm_options: Vec<String>, #[serde(default)] jdk: Option<String>, + #[serde(default)] + executor: Option<String>, } #[derive(Clone, Debug)] @@ -48,6 +56,8 @@ pub(super) struct Agent { pub(super) args: Option<String>, pub(super) vm_options: Vec<String>, pub(super) jdk: Option<String>, + /// The executor title: only launches through it get the agent. + pub(super) executor: Option<String>, } /// Agents of enabled plugins. @@ -111,9 +121,16 @@ impl ExtensionPoint for JavaAgentsPoint { if !vm_options.is_empty() || jdk.is_some() { pkg.manifest.needs_api("contributes.javaAgents.vmOptions", 14)?; } - let label = label(&d.path, args.as_deref(), &vm_options); + let executor = validate_executor(d.executor)?; + if executor.is_some() { + pkg.manifest.needs_api("contributes.javaAgents.executor", 18)?; + } + let mut label = label(&d.path, args.as_deref(), &vm_options); + if let Some(title) = &executor { + label = format!("{label} (Run with {title})"); + } let (store, plugin) = (self.store.clone(), pkg.id().to_owned()); - let agent = Agent { jar, args, vm_options, jdk }; + let agent = Agent { jar, args, vm_options, jdk, executor }; Ok(Prepared::new(label, move || Ok(store.add(plugin, agent))).file(d.path).capability(Capability::JavaAgent)) } } @@ -153,6 +170,17 @@ fn validate_jdk(jdk: Option<String>) -> Result<Option<String>, String> { Ok(Some(raw)) } +/// The executor's title: one line, short enough for "Debug '<configuration>' with <title>". +fn validate_executor(executor: Option<String>) -> Result<Option<String>, String> { + let Some(title) = executor.map(|s| s.trim().to_owned()) else { return Ok(None) }; + if title.is_empty() || title.chars().count() > MAX_EXECUTOR || title.contains(|c: char| c.is_control()) { + return Err(format!( + "contributes.javaAgents: `executor` must be a title of 1–{MAX_EXECUTOR} characters on one line" + )); + } + Ok(Some(title)) +} + /// What Settings › Plugins shows: jar name, args, and any JVM options. fn label(path: &Path, args: Option<&str>, vm_options: &[String]) -> String { let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); @@ -224,6 +252,7 @@ impl JavaAgentSource for PluginJavaAgents { vm_options: agent.vm_options.clone(), jdk: agent.jdk.clone(), approved_hash: pins.get(&(plugin.clone(), cap.clone())).map(|pin| pin.hash.clone()), + executor: agent.executor.clone(), }) .collect() } @@ -306,6 +335,33 @@ mod tests { assert_eq!(agent.jdk.as_deref(), Some("jetbrains")); } + #[test] + fn parses_an_executor_from_api_18() { + let tmp = tempfile::tempdir().unwrap(); + let manifest = MANIFEST.replace("^1.10", "^1.18"); + let decl = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" Hot Reload \"\n"; + let pkg = package(&tmp.path().join("ok"), &format!("{manifest}{decl}")); + assert_eq!(prepare(&pkg).unwrap().label, "spring agent.jar (Run with Hot Reload)"); + let store: Arc<JavaAgents> = Arc::default(); + let point = JavaAgentsPoint::new(store.clone()); + let _keep = (point.prepare(&pkg, pkg.manifest.declarations(POINT_ID).remove(0)).unwrap().commit)().unwrap(); + assert_eq!(store.for_plugin("acme.spring").unwrap().executor.as_deref(), Some("Hot Reload")); + let source = PluginJavaAgents { store, pins: Arc::default() }; + assert_eq!(source.agents()[0].executor.as_deref(), Some("Hot Reload")); + + let old = package(&tmp.path().join("old"), &format!("{MANIFEST_14}{decl}")); + assert!(prepare(&old).map(|_| ()).unwrap_err().contains("new in plugin API 1.18")); + let long = format!( + "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \"{}\"\n", + "x".repeat(41) + ); + let long = package(&tmp.path().join("long"), &format!("{manifest}{long}")); + assert!(prepare(&long).map(|_| ()).unwrap_err().contains("`executor`")); + let empty = "[[contributes.javaAgents]]\npath = \"agent/spring agent.jar\"\nexecutor = \" \"\n"; + let empty = package(&tmp.path().join("empty"), &format!("{manifest}{empty}")); + assert!(prepare(&empty).map(|_| ()).unwrap_err().contains("`executor`")); + } + #[test] fn refuses_what_would_fail_at_launch() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-host/src/plugins/mod.rs b/crates/ide-host/src/plugins/mod.rs index f632b74ef7..57e9235d7b 100644 --- a/crates/ide-host/src/plugins/mod.rs +++ b/crates/ide-host/src/plugins/mod.rs @@ -3403,6 +3403,7 @@ impl PluginHost { vm_options: agent.vm_options, jdk: agent.jdk, approved, + executor: agent.executor, } }), source: p.source, diff --git a/crates/ide-host/src/plugins/types.rs b/crates/ide-host/src/plugins/types.rs index c97832d3a4..4bc4238e1f 100644 --- a/crates/ide-host/src/plugins/types.rs +++ b/crates/ide-host/src/plugins/types.rs @@ -70,6 +70,10 @@ pub struct PluginJavaAgent { pub jdk: Option<String>, /// The jar still has the hash recorded when `java.agent` was granted. pub approved: bool, + /// The title of the executor the agent is bound to (API 1.18): "Run with <title>" and + /// "Debug with <title>" launch with it; other launches leave it out. + #[serde(default)] + pub executor: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] diff --git a/crates/ide-host/src/plugins/ui_points.rs b/crates/ide-host/src/plugins/ui_points.rs index d77d9a1ecc..8d5ba3f6ea 100644 --- a/crates/ide-host/src/plugins/ui_points.rs +++ b/crates/ide-host/src/plugins/ui_points.rs @@ -5,7 +5,8 @@ //! //! ```toml //! [[contributes.menus]] -//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message +//! menu = "editor.context" # projectView.context, editorTab.context, tools, viewItem.context, commit.message, +//! # services.context / services.toolbar (API 1.18: the Services tree's own nodes) //! command = "check" //! when = "editorLang == java" //! # view = "<view id>" # required for (only allowed on) viewItem.context @@ -112,7 +113,10 @@ pub const SERVER_COMMANDS: &str = "serverCommands"; const VIEW_ITEM_MENU: &str = "viewItem.context"; /// The toolbar above the commit message (Commit tool window and dialog). const COMMIT_MESSAGE_MENU: &str = "commit.message"; -const MENU_IDS: [&str; 10] = [ +/// The Services tool window's context menu and toolbar for the IDE's own nodes (run +/// configurations, Docker containers…): the command gets the selected services. +const SERVICES_MENUS: [&str; 2] = ["services.context", "services.toolbar"]; +const MENU_IDS: [&str; 12] = [ "editor.context", "projectView.context", "editorTab.context", @@ -123,6 +127,8 @@ const MENU_IDS: [&str; 10] = [ "mainToolbar", "problems.context", "searchResults.context", + SERVICES_MENUS[0], + SERVICES_MENUS[1], ]; const MAX_TITLE: usize = 256; const MAX_SETTINGS: usize = 200; @@ -187,6 +193,9 @@ pub(super) fn menu(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> { if d.menu == COMMIT_MESSAGE_MENU { pkg.manifest.needs_api(&format!("contributes.menus: {COMMIT_MESSAGE_MENU}"), 3)?; } + if SERVICES_MENUS.contains(&d.menu.as_str()) { + pkg.manifest.needs_api(&format!("contributes.menus: {}", d.menu), 18)?; + } if let Some(w) = &d.when { validate_when(w).map_err(|e| format!("contributes.menus: {e}"))?; } @@ -1372,6 +1381,27 @@ mod tests { } } + #[test] + fn services_menus_require_api_1_18() { + for location in SERVICES_MENUS { + for (api, valid) in [("^1.17", false), ("^1.18", true)] { + let manifest = ide_extension::Manifest::parse(&format!("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='{api}'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'")).unwrap(); + let pkg = Package::new(manifest, std::path::PathBuf::from("/unused")); + let decl = toml::from_str(&format!( + "menu='{location}'\ncommand='reload'\nwhen=\"serviceKind == 'spring-boot' && serviceRunning\"" + )) + .unwrap(); + assert_eq!(menu(&pkg, decl).is_ok(), valid, "{api}:{location}"); + } + } + let manifest = ide_extension::Manifest::parse("id='test'\nname='Test'\nversion='1.0.0'\nengines.openidea='^1.18'\n[[contributes.commands]]\nid='reload'\ntitle='Reload'").unwrap(); + let pkg = Package::new(manifest, std::path::PathBuf::from("/unused")); + let grouped = toml::from_str("menu='services.context'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap(); + assert!(menu(&pkg, grouped).is_ok()); + let toolbar = toml::from_str("menu='services.toolbar'\ncommand='reload'\nsubmenu='Hot Reload'").unwrap(); + assert!(menu(&pkg, toolbar).unwrap_err().contains("only for context menus")); + } + #[test] fn escape_bindings_need_api_1_10_and_a_when_clause() { let pkg = |api: &str| { diff --git a/crates/ide-host/tests/plugins.rs b/crates/ide-host/tests/plugins.rs index f64e0d6a8c..107aabf767 100644 --- a/crates/ide-host/tests/plugins.rs +++ b/crates/ide-host/tests/plugins.rs @@ -2274,6 +2274,45 @@ fn java_agent_loads_only_while_granted_and_unchanged() { assert_eq!(launch(), (plain, vec![])); } +/// A Java agent bound to an executor (`executor = "Hot Reload"`, API 1.18): the plugin's +/// "Run/Debug with Hot Reload" launches get it, plain launches don't, and the same grant +/// and jar pin apply. +#[test] +fn an_executor_bound_java_agent_loads_only_through_its_executor() { + let f = fixture(Limits::default()); + let tmp = tempfile::tempdir().unwrap(); + let pkg = tmp.path().join("java-agent"); + copy_dir(&sample("java-agent"), &pkg); + let manifest = std::fs::read_to_string(pkg.join("plugin.toml")).unwrap(); + let manifest = manifest + .replace("^1.10", "^1.18") + .replace("args = \"mode=test\"", "args = \"mode=test\"\nexecutor = \"Hot Reload\""); + std::fs::write(pkg.join("plugin.toml"), manifest).unwrap(); + + let info = f.host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert!(info.contributions.iter().any(|c| c.label == "fixture agent.jar=mode=test (Run with Hot Reload)")); + let agent = info.java_agent.expect("agent metadata"); + assert_eq!(agent.executor.as_deref(), Some("Hot Reload")); + assert!(!agent.approved); + let source = f.host.java_agents(); + let ungranted = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert!(ungranted.options.is_empty()); + assert!(ungranted.notes[0].contains("needs the java.agent permission"), "{:?}", ungranted.notes); + + f.host.set_capability("java-agent", "java.agent", true).unwrap(); + let jar = dunce::canonicalize(f.installed("java-agent").join("agent/fixture agent.jar")).unwrap(); + let option = format!("-javaagent:{}=mode=test", jar.display()); + let plain = ide_run::java_agent::for_executor(&source.agents(), None, None); + assert_eq!(plain, ide_run::java_agent::Agents::default(), "a plain Run leaves it out"); + let through = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert_eq!(through.options, [option]); + assert!(through.notes.is_empty()); + + f.host.set_enabled("java-agent", false).unwrap(); + let gone = ide_run::java_agent::for_executor(&source.agents(), None, Some("java-agent")); + assert!(gone.options.is_empty() && gone.notes.len() == 1); +} + /// Compiled components are cached across runs (keyed by module and /// engine), so a cold activation only deserializes. #[test] diff --git a/crates/ide-run/src/config.rs b/crates/ide-run/src/config.rs index 8a306f0b28..75aea08a79 100644 --- a/crates/ide-run/src/config.rs +++ b/crates/ide-run/src/config.rs @@ -186,6 +186,7 @@ fn convert(configs: Vec<FileConfig>, local: bool) -> Vec<RunConfig> { stop_command: non_empty(c.stop_command), target: non_empty(c.target), test_runner: non_empty(c.test_runner), + executor: None, }, }); } diff --git a/crates/ide-run/src/java_agent.rs b/crates/ide-run/src/java_agent.rs index c96adc5bd7..e274d5fedc 100644 --- a/crates/ide-run/src/java_agent.rs +++ b/crates/ide-run/src/java_agent.rs @@ -3,6 +3,10 @@ //! per plugin whose `java.agent` capability the user granted, for Run and Debug alike, //! plus any `vmOptions` the declaration lists (before the agent). //! +//! An agent bound to a plugin executor (`executor = "<title>"`, API 1.18) is added only to +//! launches through that executor ("Run with <title>" / "Debug with <title>"), whose id is +//! the plugin's id. +//! //! The grant records the jar's content hash; an agent whose jar no longer has it is //! left out (with a console line) until the user approves it again. The desktop //! installs the [`JavaAgentSource`]; elsewhere (`openidea-server`) there is none, so @@ -33,6 +37,8 @@ pub struct ContributedAgent { pub jdk: Option<String>, /// The jar's hash recorded when the user granted `java.agent`; `None`: not granted. pub approved_hash: Option<String>, + /// The title of the plugin executor the agent is bound to: added only to its launches. + pub executor: Option<String>, } /// The agents of the enabled plugins. @@ -61,8 +67,42 @@ pub fn current() -> Agents { /// Like [`current`], gating `vmOptions` with `jdk = "jetbrains"` against `java`. pub fn current_for(java: Option<&Path>) -> Agents { + current_for_executor(java, None) +} + +/// Like [`current_for`] for a launch through `executor` (a plugin id) or a plain one. +pub fn current_for_executor(java: Option<&Path>, executor: Option<&str>) -> Agents { let source = SOURCE.read().clone(); - source.map(|s| approved_for(&s.agents(), java)).unwrap_or_default() + match source { + Some(s) => for_executor(&s.agents(), java, executor), + None => { + Agents { options: Vec::new(), notes: executor.map(|e| missing_executor(e, None)).into_iter().collect() } + } + } +} + +/// The agents a launch gets: those bound to no executor, plus the one of `executor` (a plugin +/// id). A launch through an executor whose agent is not there or not granted says so. +pub fn for_executor(agents: &[ContributedAgent], java: Option<&Path>, executor: Option<&str>) -> Agents { + let chosen: Vec<ContributedAgent> = + agents.iter().filter(|a| a.executor.is_none() || (executor == Some(a.plugin.as_str()))).cloned().collect(); + let mut out = approved_for(&chosen, java); + if let Some(executor) = executor { + let own = agents.iter().find(|a| a.plugin == executor && a.executor.is_some()); + if own.is_none_or(|a| a.approved_hash.is_none()) { + out.notes.push(missing_executor(executor, own.and_then(|a| a.executor.as_deref()))); + } + } + out +} + +fn missing_executor(plugin: &str, title: Option<&str>) -> String { + match title { + Some(title) => format!( + "{title} was not applied: the Java agent of plugin {plugin} needs the java.agent permission (Settings › Plugins)." + ), + None => format!("The executor of plugin {plugin} is not available: the plugin is disabled or was removed."), + } } /// Granted agents whose jar still has the hash approved for it; an ungranted one is @@ -311,6 +351,7 @@ mod tests { vm_options: Vec::new(), jdk: None, approved_hash: granted.then(|| jar.hash.clone()), + executor: None, } } @@ -452,6 +493,34 @@ mod tests { assert_eq!(again, strings(&["-XX:+AllowEnhancedClassRedefinition", "-cp", "x", &javaagent, "Main"])); } + #[test] + fn an_executor_agent_loads_only_through_its_executor() { + let (plain_jar, bound_jar) = (jar(), jar()); + let plain = agent(&plain_jar, None, true); + let mut bound = agent(&bound_jar, None, true); + bound.plugin = "acme.reload".into(); + bound.executor = Some("Hot Reload".into()); + let agents = [plain, bound.clone()]; + let plain_opt = format!("-javaagent:{}", plain_jar.path.display()); + let bound_opt = format!("-javaagent:{}", bound_jar.path.display()); + + let run = for_executor(&agents, None, None); + assert_eq!(run.options, std::slice::from_ref(&plain_opt), "a plain launch leaves the executor's agent out"); + assert!(run.notes.is_empty()); + let with = for_executor(&agents, None, Some("acme.reload")); + assert_eq!(with.options, [plain_opt.clone(), bound_opt]); + assert!(with.notes.is_empty()); + // Another plugin's executor id: only the plain agent, and a note. + let other = for_executor(&agents, None, Some("acme.spring")); + assert_eq!(other.options, std::slice::from_ref(&plain_opt)); + assert_eq!(other.notes.len(), 1); + + bound.approved_hash = None; + let ungranted = for_executor(&[bound], None, Some("acme.reload")); + assert!(ungranted.options.is_empty()); + assert!(ungranted.notes[0].starts_with("Hot Reload was not applied"), "{:?}", ungranted.notes); + } + #[test] fn jetbrains_vm_options_skip_on_other_jdks() { let jar = jar(); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 5aa61f8f3e..2dde037512 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -188,6 +188,11 @@ pub struct RunExtras { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub test_runner: Option<String>, + /// The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + /// on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub executor: Option<String>, } impl Default for RunExtras { @@ -212,6 +217,7 @@ impl Default for RunExtras { stop_command: None, target: None, test_runner: None, + executor: None, } } } diff --git a/docs/en/plugins/guides/commands.mdx b/docs/en/plugins/guides/commands.mdx index 9c894087ff..3771e811e0 100644 --- a/docs/en/plugins/guides/commands.mdx +++ b/docs/en/plugins/guides/commands.mdx @@ -159,18 +159,20 @@ command = "test-selection" when = "editorLangId == markdown" # optional ``` -| `menu` | Where | API | -| ----------------------- | ----------------------------------------------------------------------------- | --- | -| `editor.context` | Editor right-click menu | 1.0 | -| `projectView.context` | Project tool window right-click menu | 1.0 | -| `editorTab.context` | Editor tab right-click menu | 1.0 | -| `tools` | **Tools** in the main menu | 1.0 | -| `viewItem.context` | Right-click menu of the items of one of the plugin's own views (needs `view`) | 1.2 | -| `commit.message` | Toolbar above the commit message (Commit tool window and Commit dialog) | 1.3 | -| `editor.title` | Actions area of the editor tab bar | 1.4 | -| `mainToolbar` | Main toolbar | 1.4 | -| `problems.context` | Right-click menu of a problem in the Problems tool window | 1.4 | -| `searchResults.context` | Right-click menu of a search result | 1.4 | +| `menu` | Where | API | +| ----------------------- | ----------------------------------------------------------------------------- | ---- | +| `editor.context` | Editor right-click menu | 1.0 | +| `projectView.context` | Project tool window right-click menu | 1.0 | +| `editorTab.context` | Editor tab right-click menu | 1.0 | +| `tools` | **Tools** in the main menu | 1.0 | +| `viewItem.context` | Right-click menu of the items of one of the plugin's own views (needs `view`) | 1.2 | +| `commit.message` | Toolbar above the commit message (Commit tool window and Commit dialog) | 1.3 | +| `editor.title` | Actions area of the editor tab bar | 1.4 | +| `mainToolbar` | Main toolbar | 1.4 | +| `problems.context` | Right-click menu of a problem in the Problems tool window | 1.4 | +| `searchResults.context` | Right-click menu of a search result | 1.4 | +| `services.context` | Right-click menu of the IDE's own Services nodes (run configurations, Docker) | 1.18 | +| `services.toolbar` | Services toolbar, for the selected IDE-owned nodes | 1.18 | Using a menu newer than 1.0 means declaring at least that API in `engines.openidea`. Every entry names a command the plugin declares. The menu's `when` applies alongside the @@ -205,6 +207,28 @@ command = "kube.logs" when = "viewItemKind == pod" ``` +**Services menus** (API 1.18). `services.context` and `services.toolbar` act on the nodes +the IDE puts in Services itself: run configurations and Docker containers. The `when` +clause sees, for each selected service, `serviceProvider` (`runConfigurations` or +`docker`), `serviceKind` (the configuration kind, such as `spring-boot`, or +`docker-container`), `serviceId`, `serviceName`, `serviceRunning`, `runConfigurationId` +(empty for a container) and `serviceSelectionCount`. An entry shows only when its `when` +holds for every selected service. The command's argument is JSON text, +`{"services": [{"provider", "id", "kind", "name", "running", "runConfigurationId"}]}`. +A toolbar entry shows the command's `icon`, else the plugin's. + +```toml +[[contributes.menus]] +menu = "services.context" +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" +``` + +To launch the selected configuration with the plugin's Java agent, bind the agent to an +executor instead (`executor` on `[[contributes.javaAgents]]`): **Run … with** and +**Debug … with** entries then appear beside Run and Debug, also in this menu. + ## Status bar items ```toml diff --git a/docs/en/plugins/manifest.mdx b/docs/en/plugins/manifest.mdx index 33b6af4d55..0a8466c0cc 100644 --- a/docs/en/plugins/manifest.mdx +++ b/docs/en/plugins/manifest.mdx @@ -100,38 +100,38 @@ The user approves **required** capabilities as a whole when installing. **Option Each contribution point is a table (`[contributes.settings]`) or an array of tables (`[[contributes.commands]]`). Contributions are live as soon as the plugin is enabled, before its code loads. -| Point | Declaration | Code needed | Guide | -| ------------------- | -------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | -| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | -| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | -| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | -| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | -| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | -| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | -| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | -| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | -| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | -| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | -| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | -| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | -| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | -| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | -| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | -| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | -| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | -| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | -| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | -| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | -| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | -| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | -| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | -| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | -| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | -| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) | +| Point | Declaration | Code needed | Guide | +| ------------------- | ----------------------------------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `commands` | `id`, `title`, `category?`, `when?`, `icon?` | to run them | [Commands and actions](/en/plugins/guides/commands) | +| `menus` | `menu`, `command`, `when?`, `view?`, `submenu?` | no | [Commands and actions](/en/plugins/guides/commands) | +| `keymaps` | `command`, `key`, `mac?`, `when?` (Escape only) | no | [Commands and actions](/en/plugins/guides/commands) | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | [Views and decorations](/en/plugins/guides/views) | +| `settings` | `schema` (a JSON file), or `pages` (API 1.3), `title?` | no | [Lifecycle and events](/en/plugins/lifecycle#settings) | +| `secrets` | `name`, `label`, `description?` | to use them | [Permissions and capabilities](/en/plugins/capabilities#secrets) | +| `providers` | `kinds`, `languages` | yes | [Language features](/en/plugins/guides/language-features) | +| `documentIndexers` | `extensions` | yes | [Indexing](/en/plugins/guides/indexing) | +| `endpoints` | `files` (API 1.3) | yes | [README: Project HTTP endpoints](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#project-http-endpoints-api-13) | +| `searchCategories` | `id`, `title` (API 1.13) | yes | [Custom search categories](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#custom-search-everywhere-categories-api-111) | +| `views` | `id`, `title`, `icon?`, `location`, `web?`, `group?`, `when?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `customEditors` | `id`, `title`, `patterns`, `priority`, `layout?`, `web?` | without `web` | [Views and decorations](/en/plugins/guides/views) | +| `markerIcons` | `id`, `icon`, `iconDark?`, `markers?`, `tooltip?` (API 1.3): gutter marker icons | no | [Language features](/en/plugins/guides/language-features) | +| `editorPanels` | `id`, `web`, `width`, `when?` (API 1.9; needs `editor.read`) | no | [README: Editor panels](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#editor-panels) | +| `overlays` | `id`, `web`, `width`, `height`, `anchor?`, `when?`, `interactive?` (API 1.18) | no | [README: Overlays](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#overlays) | +| `runAnything` | `prefix`, `title?` (API 1.18) | no | [README: Run Anything entries](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#run-anything-entries-api-118) | +| `dialogs` | `id`, `title`, `web`, `width`, `height` (API 1.18) | no | [README: Dialogs](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#dialogs) | +| `fileIcons` | `id`, `patterns`, `icon`, `iconDark?` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables` | no | [File actions](/en/plugins/guides/file-actions) | +| `snippets` | `language`, `path` (API 1.4) | no | [Language features](/en/plugins/guides/language-features) | +| `commitChecks` | `id`, `title` | yes | [README: Commits](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commits) | +| `serverCommands` | `server`, `command`, `run` (API 1.9) | yes | [README: Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?`, `outputMode?` | no | [Run targets](/en/plugins/guides/run-targets) | +| `runConfigurations` | `files` (API 1.4) | yes | [Run targets](/en/plugins/guides/run-targets) | +| `javaAgents` | `path`, `args?` (API 1.10); `vmOptions?`, `jdk?` (API 1.14); `executor?` (API 1.18) | no | [README: Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `skills` | `path` (`skills/<name>/SKILL.md`, API 1.15) | no | [README: API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | +| `mcpTools` | `name`, `description`, `inputSchema`, `readOnly`, `destructive` (API 1.4) | yes | [MCP tools](/en/plugins/guides/mcp) | +| `themes` | `path`, `editor-scheme?` | no | [Themes](/en/plugins/guides/themes) | +| `iconThemes` | `id`, `label`, `path` | no | [Icon themes](/en/plugins/guides/icon-themes) | +| `languages` | `path` (a `languages/<id>.toml` file) | no | [Adding a language](/en/languages/adding) | Item ids (commands, views, themes, …) match `[a-z0-9][a-z0-9._-]*`, at most 64 characters. Menus, shortcuts and status bar items refer to the plugin's own declared commands; inside the IDE a command's action id is `plugin.<plugin id>.<command id>`. diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index 1b054be36f..ef8dbc49d4 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -12,27 +12,27 @@ The plugin API has one version number: the version of the WIT package in [`wit/` ## Versions -| API | Shipped with | Highlights | -| ------ | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | -| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | -| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | -| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | -| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | -| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | -| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | -| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | -| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | -| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | -| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins | -| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | -| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations | +| API | Shipped with | Highlights | +| ------ | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | The base API: commands, events, storage, tasks, project and editor access, VCS, diagnostics, network and secrets, processes, declarative views and custom editors, settings, editor providers, syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`, `ui.copy-to-clipboard`, `ui.open-url`, opening a project file at a line from a view | +| 1.2.0 | OpenIDEA 0.1.38 | Background document indexers, pickers, input boxes and confirmations, plugin context keys for `when` clauses, the files selected in the Project view, a manifest `icon`, the `viewItem.context` menu | +| 1.3.0 | OpenIDEA 0.1.39 | Commit message and before-commit checks, Services detail panes, diagnostics while typing, hover, inlay hints, semantic tokens, file-changing code actions, HTTP endpoints, files outside the project (`fs.read`/`fs.write`, `project.write`, private plugin directory), batched `files-changed` events and path filters, workspace symbols, long-running processes, notifications with buttons, translations, multi-page settings, file template variables, web view PTYs, log tabs and content tabs | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`, `ipc:`, `ide.commands` and `database.sources` capabilities; editor and project snapshots, decorations, text search, Problems, Git log/blame/diff; output channels; OAuth loopback; runs, terminal sessions, run configurations, test result parsing and run targets; formatting and other language features; embedded languages; snippets; more menu locations; database sources; MCP tools | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify` (a notification in one project's window), the `net:ask` capability, run target validation, per-command run target working-directory arguments | +| 1.6.0 | OpenIDEA 0.1.43 | Bounded, project-bound background WebSockets for event-stream plugins | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`: two texts in the diff viewer, such as a review's file before and after | +| 1.8.0 | OpenIDEA 0.1.45 | The `problems-changed` workbench event: the host keeps every producer's diagnostics per file, so an annotation follows the file rather than the invoking window | +| 1.9.0 | OpenIDEA 0.1.46 | Run configurations with an environment and a debugger, requests to a running language server (`lsp:<server>`), server commands routed to plugins, editor panels | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`: the Maven / Gradle dependency graph the IDE resolved (`build.read`) | +| 1.11.0 | In development on `main` | `ui.read-clipboard`: the clipboard's text and image in commands the user ran (`clipboard.read`) | +| 1.12.0 | In development on `main` | `ui.set-console-rules`: highlight rules (regex, palette colours, styles) for Run and Debug console output | +| 1.13.0 | OpenIDEA 0.1.49 | Optional `search-provider` export and `searchCategories`: custom Search Everywhere tabs with cancellable queries | +| 1.14.0 | In development on `main` | Optional `hover-actions` export: left-edge line actions revealed by line-edge hover, with an anchor line and inclusive trigger range; `[[contributes.javaAgents]]` `vmOptions` / `jdk`: JVM flags (optionally JetBrains Runtime–only) before `-javaagent:`; `ui.set-status-item-menu` / `set-window-status-item-menu`: a menu on a status bar item | +| 1.15.0 | In development on `main` | `caret-moved` event; declarative `[[contributes.skills]]` (`path = "skills/<name>/SKILL.md"`) for bundling agent skills in plugins | +| 1.16.0 | OpenIDEA 0.1.52 | Optional `completion-list-provider` export: completion marked incomplete is asked again while typing on, without re-asking the language server or other plugins; `decorations.set-markdown`: line-end decorations whose hover is a Markdown card | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | +| 1.18.0 | In development on `main` | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '<name>' with <title>" beside Run and Debug, the only launches that get that agent | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/zh/plugins/guides/commands.mdx b/docs/zh/plugins/guides/commands.mdx index fa34922241..0d72380437 100644 --- a/docs/zh/plugins/guides/commands.mdx +++ b/docs/zh/plugins/guides/commands.mdx @@ -143,18 +143,20 @@ command = "test-selection" when = "editorLangId == markdown" # 可选 ``` -| `menu` | 位置 | API | -| ----------------------- | ------------------------------------------------ | --- | -| `editor.context` | 编辑器右键菜单 | 1.0 | -| `projectView.context` | 项目工具窗口右键菜单 | 1.0 | -| `editorTab.context` | 编辑器标签页右键菜单 | 1.0 | -| `tools` | 主菜单中的 **工具** | 1.0 | -| `viewItem.context` | 插件自有视图中条目的右键菜单(需要 `view`) | 1.2 | -| `commit.message` | 提交信息上方的工具栏(提交工具窗口和提交对话框) | 1.3 | -| `editor.title` | 编辑器标签栏的动作区 | 1.4 | -| `mainToolbar` | 主工具栏 | 1.4 | -| `problems.context` | 问题工具窗口中问题条目的右键菜单 | 1.4 | -| `searchResults.context` | 搜索结果的右键菜单 | 1.4 | +| `menu` | 位置 | API | +| ----------------------- | ---------------------------------------------------- | ---- | +| `editor.context` | 编辑器右键菜单 | 1.0 | +| `projectView.context` | 项目工具窗口右键菜单 | 1.0 | +| `editorTab.context` | 编辑器标签页右键菜单 | 1.0 | +| `tools` | 主菜单中的 **工具** | 1.0 | +| `viewItem.context` | 插件自有视图中条目的右键菜单(需要 `view`) | 1.2 | +| `commit.message` | 提交信息上方的工具栏(提交工具窗口和提交对话框) | 1.3 | +| `editor.title` | 编辑器标签栏的动作区 | 1.4 | +| `mainToolbar` | 主工具栏 | 1.4 | +| `problems.context` | 问题工具窗口中问题条目的右键菜单 | 1.4 | +| `searchResults.context` | 搜索结果的右键菜单 | 1.4 | +| `services.context` | IDE 自带 Services 节点(运行配置、Docker)的右键菜单 | 1.18 | +| `services.toolbar` | 选中 IDE 自带节点时的 Services 工具栏 | 1.18 | 使用 1.0 之后加入的菜单,需要在 `engines.openidea` 中至少声明对应的 API 版本。每个条目都必须指向插件声明过的命令。 菜单的 `when` 与命令自身的 `when` 同时生效。 @@ -185,6 +187,24 @@ command = "kube.logs" when = "viewItemKind == pod" ``` +**Services 菜单**(API 1.18)。`services.context` 和 `services.toolbar` 作用于 IDE 自己放进 Services 的节点: +运行配置和 Docker 容器。`when` 可以对每个选中的服务使用 `serviceProvider`(`runConfigurations` 或 `docker`)、 +`serviceKind`(运行配置类型,例如 `spring-boot`;容器为 `docker-container`)、`serviceId`、`serviceName`、 +`serviceRunning`、`runConfigurationId`(容器为空)和 `serviceSelectionCount`。只有 `when` 对每个选中的服务都成立时 +才显示该条目。命令参数是 JSON 文本:`{"services": [{"provider", "id", "kind", "name", "running", "runConfigurationId"}]}`。 +工具栏条目显示命令的 `icon`,否则使用插件图标。 + +```toml +[[contributes.menus]] +menu = "services.context" +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" +``` + +要用插件的 Java 代理启动选中的配置,请把代理绑定到执行器(`[[contributes.javaAgents]]` 的 `executor`): +“使用 … 运行”和“使用 … 调试”会出现在运行和调试旁边,也会出现在这个菜单中。 + ## 状态栏项 ```toml diff --git a/docs/zh/plugins/manifest.mdx b/docs/zh/plugins/manifest.mdx index bf1b3f6d31..adcaddfbe3 100644 --- a/docs/zh/plugins/manifest.mdx +++ b/docs/zh/plugins/manifest.mdx @@ -126,7 +126,7 @@ optional = ["net:api.openai.com", "secrets"] | `serverCommands` | `server`、`command`、`run`(API 1.9) | 是 | [README:Commands a server hands to the client](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#commands-a-server-hands-to-the-client) | | `runDetectors` | `id`、`name`、`files`、`command`、`args?`、`test?`、`framework?`、`outputMode?`(API 1.18) | 否 | [运行目标](/zh/plugins/guides/run-targets) | | `runConfigurations` | `files`(API 1.4) | 是 | [运行目标](/zh/plugins/guides/run-targets) | -| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | +| `javaAgents` | `path`、`args?`(API 1.10);`vmOptions?`、`jdk?`(API 1.14);`executor?`(API 1.18) | 否 | [README:Java agents](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#java-agents-api-110) | | `skills` | `path`(`skills/<name>/SKILL.md`,API 1.15) | 否 | [README:API 1.15](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md#api-115) | | `mcpTools` | `name`、`description`、`inputSchema`、`readOnly`、`destructive`(API 1.4) | 是 | [MCP 工具](/zh/plugins/guides/mcp) | | `themes` | `path`、`editor-scheme?` | 否 | [主题](/zh/plugins/guides/themes) | diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index 6b21535f16..c46d3d0347 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -9,27 +9,27 @@ description: "engines.openidea、插件 API 从 1.0 到 1.13 的各个版本, ## 版本历史 -| API | 随哪个版本发布 | 主要内容 | -| ------ | --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | -| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | -| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | -| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | -| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | -| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | -| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | -| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | -| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | -| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | -| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | -| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | -| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | -| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | -| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | -| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | -| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | -| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | -| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段 | +| API | 随哪个版本发布 | 主要内容 | +| ------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1.0.0 | OpenIDEA 0.1.36 | 基础 API:命令、事件、存储、任务、项目和编辑器访问、VCS、诊断、网络与密钥、进程、声明式视图和自定义编辑器、设置、编辑器 provider、syntax provider | +| 1.1.0 | OpenIDEA 0.1.37 | `vcs.remotes`、`ui.copy-to-clipboard`、`ui.open-url`,从视图中打开项目文件的指定行 | +| 1.2.0 | OpenIDEA 0.1.38 | 后台文档索引器;选择器、输入框和确认框;插件自定义的 `when` 上下文键;项目视图中选中的文件;清单 `icon`;`viewItem.context` 菜单 | +| 1.3.0 | OpenIDEA 0.1.39 | 提交信息和提交前检查、Services 详情面板、输入时诊断、悬停、内嵌提示、语义 token、改动文件的代码操作、HTTP 端点、项目外文件(`fs.read`/`fs.write`、`project.write`、插件私有目录)、批量 `files-changed` 事件和路径过滤、工作区符号、长时间运行的进程、带按钮的通知、翻译、多页设置、文件模板变量、Web 视图 PTY、日志标签页和内容标签页 | +| 1.4.0 | OpenIDEA 0.1.40 | `net.http:`、`ipc:`、`ide.commands` 和 `database.sources` 能力;编辑器与项目快照、装饰、文本搜索、问题视图、Git log/blame/diff;输出通道;OAuth 回环;运行、终端会话、运行配置、测试结果解析和运行目标;格式化等语言功能;嵌入语言;代码片段;更多菜单位置;数据库数据源;MCP 工具 | +| 1.5.0 | OpenIDEA 0.1.41 | `Project::notify`(只在某个项目的窗口中显示通知)、`net:ask` 能力、运行目标启动前校验、运行目标按命令设置工作目录参数 | +| 1.6.0 | OpenIDEA 0.1.43 | 面向事件流插件、受容量限制且绑定项目的后台 WebSocket | +| 1.7.0 | OpenIDEA 0.1.44 | `views.open-diff`:在差异查看器中对比两段文本,例如评审中某个文件的修改前后 | +| 1.8.0 | OpenIDEA 0.1.45 | `problems-changed` 工作台事件:宿主按文件保存每个生产者的诊断,注解跟着文件走,而不是跟着调用它的窗口 | +| 1.9.0 | OpenIDEA 0.1.46 | 带环境变量和调试器的运行配置、向正在运行的语言服务器发送请求(`lsp:<server>`)、交给插件处理的服务器命令、编辑器面板 | +| 1.10.0 | OpenIDEA 0.1.47 | `build.dependencies`:IDE 已解析的 Maven / Gradle 依赖图(`build.read`) | +| 1.11.0 | `main` 上开发中 | `ui.read-clipboard`:在用户运行的命令中读取剪贴板的文本和图片(`clipboard.read`) | +| 1.12.0 | `main` 上开发中 | `ui.set-console-rules`:Run/Debug 控制台输出的高亮规则(正则、调色板颜色、文本样式) | +| 1.13.0 | OpenIDEA 0.1.49 | 新增 `search-provider` 导出和 `searchCategories` 贡献点:可取消查询的全局搜索自定义分类 | +| 1.14.0 | `main` 上开发中 | 可选 `hover-actions` 导出:行内侧 hover 显示的左侧操作,带锚定行和包含式触发行范围; `[[contributes.javaAgents]]` 的 `vmOptions` / `jdk`:在 `-javaagent:` 之前注入 JVM 参数(可选仅 JetBrains Runtime);`ui.set-status-item-menu` / `set-window-status-item-menu`:状态栏项菜单 | +| 1.15.0 | `main` 上开发中 | `caret-moved` 事件;声明式 `[[contributes.skills]]`(`path = "skills/<name>/SKILL.md"`),在插件包中打包代理技能 | +| 1.16.0 | OpenIDEA 0.1.52 | 可选 `completion-list-provider` 导出:标记为不完整的补全在继续输入时再次询问,不会重新询问语言服务器和其他插件;`decorations.set-markdown`:悬停显示 Markdown 卡片的行尾装饰 | +| 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | +| 1.18.0 | `main` 上开发中 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/plugins/README.md b/plugins/README.md index 182c9479e5..997ac9873e 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -136,34 +136,34 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK. ### Contribution points -| Point | Declaration | Code needed | -| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | -| `commands` | `id`, `title`, `category?`, `when?` | to run them | -| `themes` | `path` (theme JSON), `editor-scheme?` | no | -| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | -| `languages` | `path` (`languages/<id>.toml` format, see §6) | no | -| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | -| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | -| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; _Java agents_) | no | -| `skills` | `path` (`skills/<name>/SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | -| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | -| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | -| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | -| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | -| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`), `view?`, `command`, `when?` | no | -| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | -| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | -| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | -| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | -| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | -| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | -| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | -| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | -| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | -| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | -| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | -| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | -| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | +| Point | Declaration | Code needed | +| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | +| `commands` | `id`, `title`, `category?`, `when?` | to run them | +| `themes` | `path` (theme JSON), `editor-scheme?` | no | +| `iconThemes` | `id`, `label`, `path` (icon theme JSON, see §5) | no | +| `languages` | `path` (`languages/<id>.toml` format, see §6) | no | +| `runDetectors` | `id`, `name`, `files`, `command`, `args?`, `test?`, `framework?` (API 1.4; §6.2) | no | +| `runConfigurations` | `files`: marker files for the optional `run-configurations` export (API 1.4) | yes | +| `javaAgents` | `path` (a jar in the package), `args?`, `vmOptions?`, `jdk?`, `executor?` — a Java agent for Java run configurations, behind `java.agent` (API 1.10; `vmOptions`/`jdk` in 1.14; `executor` in 1.18; _Java agents_) | no | +| `skills` | `path` (`skills/<name>/SKILL.md` in the package) — agent skill folder staged into coding-agent sessions (API 1.15) | no | +| `mcpTools` | `name`, `description`, `inputSchema` (package JSON Schema path), `readOnly`, `destructive` (API 1.4; see _Plugin MCP tools_) | yes | +| `snippets` | `language`, `path` (named JSON snippets; API 1.4) | no | +| `providers` | `kinds`, `languages` (editor providers, see _Providers_) | yes | +| `secrets` | `name`, `label`, `description?` (see _Network_) | to use them | +| `menus` | `menu` (`editor.context`, `projectView.context`, `editorTab.context`, `viewItem.context`, `tools`, `commit.message`; API 1.4: `editor.title`, `mainToolbar`, `problems.context`, `searchResults.context`; API 1.18: `services.context`, `services.toolbar`), `view?`, `command`, `when?` | no | +| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no | +| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no | +| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no | +| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` | +| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?`, `binary?` (API 1.16) | without `web` | +| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no | +| `overlays` | `id`, `web`, `width`, `height` (pixels, 40–800), `anchor?`, `when?`, `interactive?` — floats over the workbench, never takes the focus (API 1.18; _Overlays_) | no | +| `runAnything` | `prefix`, `title?` — Run Anything lines starting with `prefix`, answered by the `run-anything-provider` export (API 1.18; _Run Anything entries_) | no | +| `dialogs` | `id`, `title`, `web`, `width` (320–1600), `height` (200–1200) — a modal, resizable dialog opened by `views::reveal(id)` (API 1.18; _Dialogs_) | no | +| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no | +| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no | +| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes | +| `serverCommands` | `server`, `command`, `run` — a language server's client command run by this plugin's command (API 1.9; see _Commands a server hands to the client_) | A `viewItem.context` menu needs `view`, the id of one of the plugin's own views. It adds the commands to the right-click menu of the items in that @@ -2284,6 +2284,46 @@ use (ANSI stripped, the last 5000 lines and 16 KiB per line, Soft-wrap, Clear, the exit code at the end). A toggle appends its `args` and starts the program again. It stops when the node's pane closes or the Services window is hidden. +#### Actions on the IDE's own Services nodes (API 1.18) + +A plugin can also act on the nodes the IDE puts in Services itself: run +configurations (Spring Boot, Application, …) and Docker containers. Two menus +take its commands, with `engines.openidea = "^1.18"`: + +```toml +[[contributes.menus]] +menu = "services.context" # right-click menu of the selected services +command = "hotreload.attach" +submenu = "Hot Reload" +when = "serviceKind == 'spring-boot' && serviceRunning" + +[[contributes.menus]] +menu = "services.toolbar" # Services toolbar button (the command's icon, else the plugin's) +command = "hotreload.attach" +when = "serviceSelectionCount == 1 && serviceKind == 'spring-boot'" +``` + +The `when` clause sees, for each selected service, `serviceProvider` +(`runConfigurations` or `docker`), `serviceKind` (the run configuration's kind, +such as `spring-boot`, `application` or `jar-application`, or +`docker-container`), `serviceId`, `serviceName`, `serviceRunning`, +`runConfigurationId` (empty for a container) and `serviceSelectionCount`. An +entry shows only when its `when` holds for every selected service, and not when +the selection includes a group node. The command gets the selection as its +argument, JSON text: + +```json +{"services": [{"provider": "runConfigurations", "id": "app", "kind": "spring-boot", + "name": "App", "running": true, "runConfigurationId": "app"}]} +``` + +`host::start_run` still starts only the plugin's own configurations. To launch +the user's configuration with the plugin's Java agent, bind the agent to an +executor (_Java agents_): **Run '<name>' with <title>** and **Debug '<name>' +with <title>** then appear in this menu for Application, Spring Boot and JAR +Application configurations, and go through the normal launch (build, +classpath, JDK, debugger, Stop). + #### Web views A view or custom editor can instead be a web page of the package, for UIs the @@ -2806,6 +2846,25 @@ jdk = "jetbrains" # optional: only those VM options on when the launcher is not JetBrains Runtime; the agent still loads. Arguments are separate argv items (no shell), so a path with spaces needs no quoting; a shortened command line moves only the classpath into its argument file. +- **Executors** (API 1.18). With `executor = "<title>"` (1–40 characters) the + agent no longer loads into every launch. The plugin gets an executor beside + Run and Debug instead, as IDEA's "Run with JRebel" or "Profile": **Run '<name>' + with <title>** and **Debug '<name>' with <title>** in the run widget's ⋮ menu, + the gutter's ▶ menu, the context menus' run entries and the Services context + menu of those configurations, plus the actions **Run with <title>** and + **Debug with <title>** (Find Action, Keymap). Only launches through them get + the agent and its `vmOptions`; the grant and jar pin are the same. Without + `java.agent` the IDE says so instead of launching, and a configuration on a + run target is refused the same way. + + ```toml + [[contributes.javaAgents]] + path = "agent/hotreload-agent.jar" + vmOptions = ["-XX:+AllowEnhancedClassRedefinition"] + jdk = "jetbrains" + executor = "Hot Reload" + ``` + - Not in this version: tests (JUnit), Maven and Gradle goals (an Application set to _Build and run using: Gradle_ runs as a Gradle task), application servers (Tomcat), remote JVM debug, configurations on a run target, and diff --git a/src/bindings.ts b/src/bindings.ts index f81fd81438..b797a03af1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -11041,6 +11041,11 @@ export type PluginJavaAgent = { jdk: string | null, /** The jar still has the hash recorded when `java.agent` was granted. */ approved: boolean, + /** + * The title of the executor the agent is bound to (API 1.18): "Run with <title>" and + * "Debug with <title>" launch with it; other launches leave it out. + */ + executor?: string | null, }; /** @@ -12535,6 +12540,11 @@ export type RunExtras_Deserialize = { * test output parser and how a single test is selected. */ testRunner?: string | null, + /** + * The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + * on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + */ + executor?: string | null, }; export type RunExtras_Serialize = { @@ -12585,6 +12595,11 @@ export type RunExtras_Serialize = { * test output parser and how a single test is selected. */ testRunner?: string | null, + /** + * The plugin executor a launch goes through ("Run with <title>"): the plugin's id. Set + * on the launched copy, not saved; the plugin's executor-bound Java agent loads only then. + */ + executor?: string | null, }; /** A process started from a run configuration. */ diff --git a/src/features/debugger/java.ts b/src/features/debugger/java.ts index a7127f5b6d..ba04ea6ca2 100644 --- a/src/features/debugger/java.ts +++ b/src/features/debugger/java.ts @@ -180,7 +180,11 @@ export async function javaLaunchConfig( const agentNote = await remoteJavaAgentNote(rc); if (agentNote) preparation?.report?.(agentNote); // The host adds JetBrains Runtime's flag for it, or says in the console why the session runs without. - const enhanced = rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {}; + const enhanced = { + ...(rc.params?.enhancedClassRedefinition === "true" ? { enhancedClassRedefinition: true } : {}), + // A plugin executor's launch ("Debug with …"): the host adds that plugin's Java agent. + ...(rc.executor ? { executor: rc.executor } : {}), + }; if (kotlin) { return { name: rc.name, diff --git a/src/features/plugins/__tests__/serviceMenus.test.tsx b/src/features/plugins/__tests__/serviceMenus.test.tsx new file mode 100644 index 0000000000..346d79bcd7 --- /dev/null +++ b/src/features/plugins/__tests__/serviceMenus.test.tsx @@ -0,0 +1,196 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { PluginInfo } from "@/bindings"; +import { registerAction } from "@/platform/actions"; +import type { RunConfig } from "@/platform/ipc"; +import { + provideNotificationService, + runExecutors, + type NotificationService, + type ServiceContext, +} from "@/workbench/contributions"; +import { executorLaunch, pluginExecutors, syncPluginExecutors } from "../executors"; +import { defineBuiltinUiPoints } from "../points"; +import { clearUiContributions, syncUiContributions } from "../projection"; +import { usePlugins } from "../store"; +import { pluginServiceActions, pluginServiceMenuItems } from "../uiPoints"; + +let undefinePoints: () => void = () => {}; + +beforeEach(() => { + undefinePoints = defineBuiltinUiPoints(); +}); + +afterEach(() => { + clearUiContributions(); + undefinePoints(); + usePlugins.setState({ plugins: [] }); +}); + +const plugin = (extra: Partial<PluginInfo> = {}) => + ({ id: "hot", name: "Hot Reload Tools", status: "active", enabled: true, icon: null, ...extra }) as PluginInfo; + +const spring: ServiceContext = { + provider: "runConfigurations", + id: "app", + kind: "spring-boot", + name: "App", + running: false, + runConfigurationId: "app", +}; +const container: ServiceContext = { provider: "docker", id: "c1", kind: "docker-container", name: "db", running: true }; + +const config = (extra: Partial<RunConfig> = {}): RunConfig => ({ + id: "app", + name: "App", + kind: "spring-boot", + command: "java", + args: [], + cwd: null, + env: {}, + detected: false, + isTest: false, + debugAdapter: "java-debug", + ...extra, +}); + +describe("plugin Services menus", () => { + it("offers entries whose when holds for every selected service, with the services as argument", async () => { + const run = vi.fn(); + const offs = [ + registerAction({ id: "plugin.hot.reload", title: "Reload", icon: "refresh", run: ({ arg }) => run(arg) }), + registerAction({ id: "plugin.hot.logs", title: "Logs", run: () => {} }), + ]; + syncUiContributions( + [ + { + pluginId: "hot", + point: "menus", + key: "services.context/reload", + decl: { + menu: "services.context", + command: "reload", + submenu: "Hot Reload", + when: "serviceKind == 'spring-boot' && !serviceRunning", + }, + }, + { + pluginId: "hot", + point: "menus", + key: "services.context/logs", + decl: { menu: "services.context", command: "logs", submenu: "Hot Reload", when: "serviceRunning" }, + }, + { + pluginId: "hot", + point: "menus", + key: "services.toolbar/reload", + decl: { menu: "services.toolbar", command: "reload", when: "serviceSelectionCount == 1" }, + }, + ], + [plugin()], + ); + + const json = (services: ServiceContext[]) => + JSON.stringify({ services: services.map((s) => ({ ...s, runConfigurationId: s.runConfigurationId ?? null })) }); + const arg = json([spring]); + expect(JSON.parse(arg)).toEqual({ + services: [ + { + provider: "runConfigurations", + id: "app", + kind: "spring-boot", + name: "App", + running: false, + runConfigurationId: "app", + }, + ], + }); + // One visible entry of the submenu: no nesting. + expect(pluginServiceMenuItems([spring])).toEqual([{ kind: "action", action: "plugin.hot.reload", arg }]); + expect(pluginServiceMenuItems([container])).toEqual([ + { kind: "action", action: "plugin.hot.logs", arg: json([container]) }, + ]); + // Mixed selection: an entry shows only when it holds for each service. + expect(pluginServiceMenuItems([spring, container])).toEqual([]); + const running = { ...spring, running: true }; + expect(pluginServiceMenuItems([running])).toEqual([ + { kind: "action", action: "plugin.hot.logs", arg: json([running]) }, + ]); + + const [button, ...rest] = pluginServiceActions([spring]); + expect(rest).toEqual([]); + expect(button).toMatchObject({ id: "plugin.hot.reload", title: "Reload", icon: "refresh" }); + button!.run(); + await vi.waitFor(() => expect(run).toHaveBeenCalledWith(arg)); + expect(pluginServiceActions([spring, { ...spring, id: "other" }])).toEqual([]); + offs.forEach((off) => off()); + }); + + it("drops entries whose command is not registered", () => { + syncUiContributions( + [ + { + pluginId: "hot", + point: "menus", + key: "services.context/gone", + decl: { menu: "services.context", command: "gone" }, + }, + ], + [plugin()], + ); + expect(pluginServiceMenuItems([spring])).toEqual([]); + }); +}); + +describe("plugin executors", () => { + const agent = (executor: string | null, approved = true) => ({ + fileName: "hot.jar", + args: null, + vmOptions: [], + jdk: null, + approved, + executor, + }); + + it("lists enabled plugins whose agent names an executor", () => { + expect( + pluginExecutors([ + plugin({ javaAgent: agent("Hot Reload") }), + plugin({ id: "plain", javaAgent: agent(null) }), + plugin({ id: "off", enabled: false, javaAgent: agent("Off") }), + ]), + ).toEqual([{ pluginId: "hot", pluginName: "Hot Reload Tools", title: "Hot Reload", approved: true }]); + }); + + it("registers Run and Debug with <title> for JVM configurations", async () => { + usePlugins.setState({ plugins: [plugin({ javaAgent: agent("Hot Reload") })] }); + const stop = syncPluginExecutors(); + const mine = runExecutors().filter((e) => e.id.startsWith("plugin:hot")); + expect(mine.map((e) => [e.id, e.label("App"), e.debug ?? false])).toEqual([ + ["plugin:hot", "Run 'App' with Hot Reload", false], + ["plugin:hot:debug", "Debug 'App' with Hot Reload", true], + ]); + const [run, debug] = mine; + expect(run!.supports(config())).toBe(true); + expect(run!.supports(config({ kind: "maven" }))).toBe(false); + expect(debug!.supports(config({ kind: "jar-application", debugAdapter: null }))).toBe(true); + expect(debug!.supports(config({ kind: "junit" }))).toBe(false); + const plan = await run!.prepare(config()); + expect(plan?.launch).toMatchObject({ id: "app", executor: "hot" }); + + // Disabled: gone. + usePlugins.setState({ plugins: [plugin({ enabled: false, javaAgent: agent("Hot Reload") })] }); + expect(runExecutors().some((e) => e.id.startsWith("plugin:hot"))).toBe(false); + stop(); + }); + + it("asks for the permission, and refuses run targets, instead of launching without the agent", () => { + const notify = vi.fn(); + provideNotificationService({ notify } as unknown as NotificationService); + const e = { pluginId: "hot", pluginName: "Hot Reload Tools", title: "Hot Reload", approved: false }; + expect(executorLaunch(e, config())).toBeNull(); + expect(notify.mock.calls[0]![0]).toMatchObject({ title: "Hot Reload needs the Java agent of Hot Reload Tools" }); + expect(executorLaunch({ ...e, approved: true }, config({ target: "ssh-1" }))).toBeNull(); + expect(notify.mock.calls[1]![0]).toMatchObject({ title: "Cannot run 'App' with Hot Reload" }); + expect(executorLaunch({ ...e, approved: true }, config())).toMatchObject({ executor: "hot" }); + }); +}); diff --git a/src/features/plugins/executors.ts b/src/features/plugins/executors.ts new file mode 100644 index 0000000000..fc583f98ea --- /dev/null +++ b/src/features/plugins/executors.ts @@ -0,0 +1,139 @@ +/** + * Plugin executors (`executor = "<title>"` on `[[contributes.javaAgents]]`, API 1.18): + * "Run '<config>' with <title>" and "Debug '<config>' with <title>" beside Run and Debug + * for the JVM configurations the agent loads into (the run widget's ⋮ menu, the gutter, + * the context menus' More Run/Debug and the Services tree). The launch carries the + * plugin's id; the host adds that plugin's agent to it, and to no other launch. + */ +import type { PluginInfo } from "@/bindings"; +import { executeAction, registerActions } from "@/platform/actions"; +import { tx } from "@/platform/i18n"; +import type { RunConfig } from "@/platform/ipc"; +import { isRemoteWindow } from "@/platform/remote"; +import { + notifications, + registerRunExecutor, + type ExecutorLaunch, + type RunExecutorContribution, +} from "@/workbench/contributions"; +import { usePlugins } from "./store"; + +/** Configuration kinds whose JVM gets plugin agents (`ide_run::java_agent::KINDS`). */ +const KINDS = ["application", "spring-boot", "jar-application"]; + +export const pluginExecutorId = (pluginId: string, debug: boolean) => `plugin:${pluginId}${debug ? ":debug" : ""}`; + +const actionId = (pluginId: string, debug: boolean) => `pluginExecutor.${pluginId}.${debug ? "debug" : "run"}`; + +export interface PluginExecutor { + pluginId: string; + pluginName: string; + title: string; + /** The agent jar is approved (`java.agent` granted, jar unchanged). */ + approved: boolean; +} + +/** Executors of the enabled plugins that declare one. */ +export function pluginExecutors(plugins: readonly PluginInfo[]): PluginExecutor[] { + return plugins.flatMap((p) => + p.enabled && p.javaAgent?.executor + ? [{ pluginId: p.id, pluginName: p.name, title: p.javaAgent.executor, approved: p.javaAgent.approved }] + : [], + ); +} + +/** What "Run/Debug with <title>" launches: the configuration marked with the plugin's id. */ +export function executorLaunch(e: PluginExecutor, config: RunConfig): RunConfig | null { + if (!e.approved) { + notifications().notify({ + group: "run", + level: "warning", + key: `plugin-executor-${e.pluginId}`, + title: tx`${e.title} needs the Java agent of ${e.pluginName}`, + body: tx`Allow the java.agent permission of ${e.pluginName} in Settings › Plugins, then try again.`, + userInitiated: true, + actions: [{ label: "Plugins…", run: () => void executeAction("plugins.settings") }], + }); + return null; + } + if (config.target) { + notifications().notify({ + group: "run", + level: "warning", + key: `plugin-executor-${e.pluginId}`, + title: tx`Cannot run '${config.name}' with ${e.title}`, + body: tx`Plugin Java agents load only into JVMs started on this machine. Choose “Local machine” under “Run on”.`, + userInitiated: true, + actions: [{ label: "Edit Configuration…", run: () => void executeAction("run.editConfigs", config.id) }], + }); + return null; + } + return { ...config, executor: e.pluginId }; +} + +function executor(e: PluginExecutor, debug: boolean): RunExecutorContribution { + return { + id: pluginExecutorId(e.pluginId, debug), + label: (name) => (debug ? tx`Debug '${name}' with ${e.title}` : tx`Run '${name}' with ${e.title}`), + icon: debug ? "debug" : "run", + action: actionId(e.pluginId, debug), + order: debug ? 101 : 100, + debug, + checksTarget: true, + // All three debug: Application / Spring Boot through the Java debugger, JAR Application through JDWP. + supports: (config) => KINDS.includes(config.kind) && !isRemoteWindow(), + prepare: async (config): Promise<ExecutorLaunch | null> => { + const launch = executorLaunch(e, config); + return launch ? { launch, finished: () => {} } : null; + }, + }; +} + +function register(e: PluginExecutor): () => void { + const disposers = [false, true].flatMap((debug) => [ + registerRunExecutor(executor(e, debug)), + registerActions([ + { + id: actionId(e.pluginId, debug), + title: debug ? tx`Debug with ${e.title}` : tx`Run with ${e.title}`, + description: tx`Launches the selected configuration with the Java agent of ${e.pluginName}`, + category: "Run", + icon: debug ? "debug" : "run", + when: "projectOpen", + run: ({ arg }) => + executeAction("run.withExecutor", { + executor: pluginExecutorId(e.pluginId, debug), + ...(arg && typeof arg === "object" ? arg : {}), + }).then(() => undefined), + }, + ]), + ]); + return () => disposers.forEach((d) => d()); +} + +/** Keeps the executors in line with the installed plugins. */ +export function syncPluginExecutors(): () => void { + const live = new Map<string, { sig: string; dispose: () => void }>(); + const sync = (plugins: readonly PluginInfo[]) => { + const next = new Map(pluginExecutors(plugins).map((e) => [e.pluginId, e])); + for (const [id, entry] of live) { + const e = next.get(id); + if (!e || JSON.stringify(e) !== entry.sig) { + entry.dispose(); + live.delete(id); + } + } + for (const [id, e] of next) { + if (!live.has(id)) live.set(id, { sig: JSON.stringify(e), dispose: register(e) }); + } + }; + sync(usePlugins.getState().plugins); + const unsubscribe = usePlugins.subscribe((s, prev) => { + if (s.plugins !== prev.plugins) sync(s.plugins); + }); + return () => { + unsubscribe(); + for (const entry of live.values()) entry.dispose(); + live.clear(); + }; +} diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index 49eb687f4a..210645349e 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -23,6 +23,7 @@ import { providePluginThemePreviews, startPluginBridge } from "./bridge"; import { ConsentDialogHost, provideConsentDialog } from "./consent"; import { pluginLineMarkerGutter } from "./lineMarkerGutter"; import { startViewUi } from "./uiPoints"; +import { syncPluginExecutors } from "./executors"; import { showInstalledIntellijThemes } from "./intellijThemesDialogStore"; import { startWorkspaceContains } from "./workspaceContains"; import { startPluginDecorations } from "./decorations"; @@ -119,6 +120,8 @@ export function activate(): () => void { startPluginConsoleRules(), // Plugin custom editors (tab kind) and context menu entries. startViewUi((input) => void editorService().openInput(input)), + // "Run/Debug with <title>" of plugins whose Java agent is bound to an executor. + syncPluginExecutors(), startWorkspaceContains(), // Gutter icons from plugins' `line-markers` providers (next to the LSP ones). registerEditorContribution({ id: "plugins.languageFeatures", order: 58, extensions: pluginLanguageVisuals }), diff --git a/src/features/plugins/uiPoints.tsx b/src/features/plugins/uiPoints.tsx index 73d37fdafc..585ecf1f95 100644 --- a/src/features/plugins/uiPoints.tsx +++ b/src/features/plugins/uiPoints.tsx @@ -2,8 +2,8 @@ * Client side of the plugin UI points: declarations the * backend validated, projected onto the workbench's own registries. * - * - `menus`: editor / project view / editor tab context menus, Tools in the main menu, and the - * toolbar above the commit message; + * - `menus`: editor / project view / editor tab context menus, Tools in the main menu, the + * toolbar above the commit message, and the Services tree's context menu and toolbar; * - `keymaps`: default shortcuts below the IDE's (a taken keystroke is dropped); * - `statusBar`: items shown before the code runs (its `set-status-item` with the same id updates them); * - `settings`: a page under Settings › Plugins generated from the schema; @@ -19,7 +19,7 @@ */ import type { PluginInfo } from "@/bindings"; import { registerEditorContribution } from "@/editor/api"; -import { getAction } from "@/platform/actions"; +import { executeAction, getAction } from "@/platform/actions"; import { evaluateWhen, getContext, useContextKeys } from "@/platform/context"; import { tx } from "@/platform/i18n"; import { isMacHost, registerExtensionBindings } from "@/platform/keymap"; @@ -34,9 +34,12 @@ import { registerMenuGroup, registerMenuSlotItem, registerServiceProvider, + registerServiceSelectionItems, registerTextEditorWrapper, type ContextMenuId, type ContributedCommitProblem, + type ServiceContext, + type ServiceItemAction, type ToolWindowAnchor, } from "@/workbench/contributions"; import { pluginsBackend } from "./backend"; @@ -90,7 +93,9 @@ interface MenuDecl { | "editorTab.context" | "viewItem.context" | "tools" - | "commit.message"; + | "commit.message" + | "services.context" + | "services.toolbar"; view?: string | null; command: string; when?: string | null; @@ -180,6 +185,66 @@ export function pluginViewItemMenuItems(pluginId: string, view: string, key: str return flattenSingleGroups(out); } +/** The when keys of one selected service. */ +export function serviceWhenContext(service: ServiceContext, count: number) { + return { + ...getContext(), + serviceProvider: service.provider, + serviceKind: service.kind, + serviceId: service.id, + serviceName: service.name, + serviceRunning: service.running, + runConfigurationId: service.runConfigurationId ?? "", + serviceSelectionCount: count, + }; +} + +/** The command's argument (JSON text, as a plugin command's argument is a string): the selected services. */ +export const servicesArg = (services: readonly ServiceContext[]) => + JSON.stringify({ + services: services.map((s) => ({ + provider: s.provider, + id: s.id, + kind: s.kind, + name: s.name, + running: s.running, + runConfigurationId: s.runConfigurationId ?? null, + })), + }); + +/** Plugin entries of `services.context` / `services.toolbar` whose `when` holds for every selected service. */ +function serviceEntries(menu: "services.context" | "services.toolbar", services: readonly ServiceContext[]) { + return [...contextItems.values()].flatMap(({ pluginId, decl }) => { + if (decl.menu !== menu) return []; + if (!services.every((s) => evaluateWhen(decl.when ?? undefined, serviceWhenContext(s, services.length)))) return []; + const action = pluginActionId(pluginId, decl.command); + return getAction(action) ? [{ pluginId, decl, action }] : []; + }); +} + +export function pluginServiceMenuItems(services: readonly ServiceContext[]): MenuItem[] { + const out: MenuItem[] = []; + const groups = new Map<string, MenuItem[]>(); + const arg = servicesArg(services); + for (const { pluginId, decl, action } of serviceEntries("services.context", services)) + addGrouped(out, groups, pluginId, decl.submenu, { kind: "action", action, arg }); + return flattenSingleGroups(out); +} + +export function pluginServiceActions(services: readonly ServiceContext[]): ServiceItemAction[] { + const arg = servicesArg(services); + return serviceEntries("services.toolbar", services).map(({ pluginId, action }) => { + const a = getAction(action)!; + const plugin = usePlugins.getState().plugins.find((p) => p.id === pluginId); + return { + id: action, + title: a.title, + icon: a.icon ?? pluginIconName(pluginId, plugin?.icon ?? null), + run: () => void executeAction(action, arg), + }; + }); +} + function projectMenu(pluginId: string, decl: MenuDecl, plugin: PluginInfo): () => void { if (decl.menu === "tools") { const action = pluginActionId(pluginId, decl.command); @@ -609,6 +674,7 @@ export function startViewUi(openInput: (input: ReturnType<typeof customEditorInp icon: pluginContentEditorIcon, document: pluginContentEditorDocument, }), + registerServiceSelectionItems({ id: "plugins", menu: pluginServiceMenuItems, actions: pluginServiceActions }), registerMenuGroup({ id: "plugins", menus: ["editor", "projectView", "editorTab", "problems", "searchResults"], diff --git a/src/features/run/executors.ts b/src/features/run/executors.ts index 656651106f..b9b94600ff 100644 --- a/src/features/run/executors.ts +++ b/src/features/run/executors.ts @@ -4,6 +4,7 @@ * any other, and the executor hears when the process exits. */ import type { RunConfig } from "@/platform/ipc"; +import { executeAction } from "@/platform/actions"; import { notifications, useRunExecutors, type ExecutorLaunch } from "@/workbench/contributions"; import { containerExecutorBlocked } from "./remote"; import { prepareLaunch, startRun } from "./store"; @@ -11,8 +12,9 @@ import { prepareLaunch, startRun } from "./store"; export async function runWithExecutor(config: RunConfig, executorId: string): Promise<void> { const executor = useRunExecutors.getState().executors.get(executorId); if (!executor) return; - if (containerExecutorBlocked(config)) return; - if (!(await prepareLaunch(config))) return; + if (!executor.checksTarget && containerExecutorBlocked(config)) return; + // Debug runs the before-launch tasks itself. + if (!executor.debug && !(await prepareLaunch(config))) return; let plan: ExecutorLaunch | null; try { plan = await executor.prepare(config); @@ -28,6 +30,10 @@ export async function runWithExecutor(config: RunConfig, executorId: string): Pr } if (!plan) return; const { launch, finished, beforeStop } = plan; + if (executor.debug) { + await executeAction("run.debugConfig", launch); + return; + } await startRun(config, undefined, undefined, { launch, onExit: (exitCode, stopped) => finished({ exitCode, stopped }), diff --git a/src/features/run/services.test.ts b/src/features/run/services.test.ts index 8fc3d345cb..7ad81f60a9 100644 --- a/src/features/run/services.test.ts +++ b/src/features/run/services.test.ts @@ -27,7 +27,12 @@ import { } from "./services"; import { KIND_OPTIONS, categoryOf } from "./configs"; import { startedPort } from "@/platform/serverPort"; -import { registerRunConfigType, useDebugRunSessions, type DebugServiceSession } from "@/workbench/contributions"; +import { + registerRunConfigType, + registerRunExecutor, + useDebugRunSessions, + type DebugServiceSession, +} from "@/workbench/contributions"; import { useRun, type RunSession } from "./store"; const { startRun, stopServiceSessions, openUrl, showContextMenu } = vi.hoisted(() => ({ @@ -427,6 +432,33 @@ describe("running service count (the Services badge)", () => { expect(runningServiceCount()).toBe(2); }); + it("describes a configuration node to other features and offers its executors", () => { + useRun.setState({ configs: [dev], sessions: [session("s1", dev, "running", 1)] }); + const node = { key: "run:config:dev", label: "dev", icon: "" }; + expect(runServiceProvider.context!(node)).toEqual({ + provider: "runConfigurations", + id: "dev", + kind: dev.kind, + name: "dev", + running: true, + runConfigurationId: "dev", + }); + expect(runServiceProvider.context!({ key: `run:type:${dev.kind}`, label: "", icon: "" })).toBeNull(); + const off = registerRunExecutor({ + id: "probe", + label: (name) => `Probe '${name}'`, + icon: "run", + action: "probe.run", + supports: (c) => c.id === "dev", + prepare: async () => null, + }); + const labels = runServiceProvider.menu!(node).flatMap((e) => + e.kind === "separator" || e.kind === "header" || e.kind === "action" ? [] : [e.label], + ); + expect(labels).toContain("Probe 'dev'"); + off(); + }); + it("does not count a configuration removed from the window while it runs", () => { useRun.setState({ configs: [dev], sessions: [session("s1", dev, "running", 1)] }); const node = { key: "run:config:dev", label: "dev", icon: "" }; diff --git a/src/features/run/services.tsx b/src/features/run/services.tsx index b8321e2c66..34fdb3319e 100644 --- a/src/features/run/services.tsx +++ b/src/features/run/services.tsx @@ -18,6 +18,7 @@ import type { MenuItem } from "@/ui"; import { toolWindowService, notifications, + runExecutors, useRunConfigTypes, useDebugRunSessions, useServicesRunningCount, @@ -27,6 +28,7 @@ import { type ServiceTreeItem, } from "@/workbench/contributions"; import { pickServices } from "./serviceImport"; +import { runWithExecutor } from "./executors"; import { CATEGORY_ORDER, categoryOf, commandLine, configIcon, KIND_OPTIONS, kindLabel } from "./configs"; import { openUrl } from "./navigate"; import { showApplicationUpdate } from "./applicationUpdate"; @@ -742,6 +744,18 @@ function menu(item: ServiceTreeItem): MenuItem[] { const config = r.config; const session = r.session?.run; const debuggerSession = serviceDebugger(r.session) ?? r.session?.debug.at(-1); + // IDEA: the configuration's other executors (Run with Coverage, Profile, plugins' executors). + const executors = runExecutors().filter((e) => e.supports(config)); + if (executors.length) + items.push( + { kind: "separator" }, + ...executors.map((e): MenuItem => ({ + id: `executor:${e.id}`, + label: e.label(config.name), + icon: e.icon, + run: () => void runWithExecutor(config, e.id), + })), + ); items.push( { kind: "separator" }, { @@ -925,6 +939,18 @@ export const runServiceProvider: ServiceProviderContribution = { useRoots, actions, menu, + context: (item) => { + const { config, session } = resolve(item); + if (!config) return null; + return { + provider: RUN_PROVIDER, + id: config.id, + kind: config.kind, + name: config.name, + running: !!session && liveServiceSession(session), + runConfigurationId: config.id, + }; + }, activate: (item) => { const r = resolve(item); if (r.config && !(r.session && liveServiceSession(r.session)) && !isDebugOnly(r.config)) run(r); diff --git a/src/features/services/ServicesTree.test.tsx b/src/features/services/ServicesTree.test.tsx index b11af13502..1519bd4aad 100644 --- a/src/features/services/ServicesTree.test.tsx +++ b/src/features/services/ServicesTree.test.tsx @@ -1,7 +1,13 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { fireEvent, render, screen, within } from "@testing-library/react"; import { usePlatform } from "@/platform/platformInfo"; -import { ToolWindowShownProvider, useServiceProviders, type ServiceTreeItem } from "@/workbench/contributions"; +import { + ToolWindowShownProvider, + registerServiceSelectionItems, + useServiceProviders, + type ServiceContext, + type ServiceTreeItem, +} from "@/workbench/contributions"; import { ServicesTreeView } from "./ServicesTree"; import { useServicesTree } from "./tree"; import { selectedServices, selectionActions, selectionMenu } from "./selection"; @@ -190,6 +196,30 @@ it("ignores removed rows and avoids invoking a selected group's descendants twic expect(stop.mock.calls).toEqual([["group"]]); }); +it("adds other features' entries for selected services, never for a group", () => { + const context = (item: ServiceTreeItem): ServiceContext | null => + item.children ? null : { provider: "a", id: item.key, kind: "app", name: item.label, running: false }; + const provider = { id: "a", useRoots: () => [], menu: () => [{ label: "Own", run }], context }; + const seen: string[][] = []; + const off = registerServiceSelectionItems({ + id: "extra", + menu: (services) => { + seen.push(services.map((s) => s.id)); + return [{ label: "Extra", run }]; + }, + actions: () => [{ id: "extra", title: "Extra", icon: "run", run }], + }); + const at = (item: ServiceTreeItem) => ({ provider: "a", item, parent: null }); + expect( + selectionMenu([at(roots[0]!), at(roots[1]!)], [provider]).map((i) => ("label" in i ? i.label : i.kind)), + ).toEqual(["Own", "separator", "Extra"]); + expect(seen).toEqual([["one", "two"]]); + expect(selectionActions([at(roots[0]!)], [provider]).map((a) => a.id)).toEqual(["extra"]); + const group = { key: "g", label: "g", icon: "run", children: [roots[0]!] }; + expect(selectionMenu([at(group)], [provider]).map((i) => ("label" in i ? i.label : i.kind))).toEqual(["Own"]); + off(); +}); + it("disables actions when no selected row can run them", () => { const { row, toolbar } = setup(); fireEvent.mouseDown(row("three")); diff --git a/src/features/services/docker.tsx b/src/features/services/docker.tsx index 0735e768e7..df98cdc1fe 100644 --- a/src/features/services/docker.tsx +++ b/src/features/services/docker.tsx @@ -583,6 +583,18 @@ export const dockerProvider: ServiceProviderContribution = { watch, actions, menu, + context: (item) => { + const t = resolveTarget(item.key); + if (t?.node.kind !== "container") return null; + const c = t.node.container; + return { + provider: DOCKER_PROVIDER, + id: c.id, + kind: "docker-container", + name: c.name, + running: c.state === "running", + }; + }, activate: (item) => { const t = resolveTarget(item.key); if (t?.node.kind === "container") useServices.setState({ detailTab: "log" }); diff --git a/src/features/services/selection.ts b/src/features/services/selection.ts index c7938050b7..d008554055 100644 --- a/src/features/services/selection.ts +++ b/src/features/services/selection.ts @@ -1,6 +1,11 @@ import { executeAction, getAction, isActionEnabled } from "@/platform/actions"; import type { MenuItem } from "@/ui"; -import type { ServiceItemAction, ServiceProviderContribution } from "@/workbench/contributions"; +import { + serviceSelectionContributions, + type ServiceContext, + type ServiceItemAction, + type ServiceProviderContribution, +} from "@/workbench/contributions"; import type { Located } from "./tree"; /** A selected group already targets its descendants; don't invoke those twice. */ @@ -24,15 +29,42 @@ function batch<T extends { disabled?: boolean; run?: () => void }>(items: T[]): return { ...items[0]!, disabled: !enabled.length, run: () => enabled.forEach((item) => item.run?.()) }; } +/** The selected services as other features see them; null when a selected node is no service (a group). */ +export function selectionContexts( + selection: Located[], + providers: readonly ServiceProviderContribution[], +): ServiceContext[] | null { + const contexts = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.context?.(item)); + return contexts.length && contexts.every((c) => !!c) ? (contexts as ServiceContext[]) : null; +} + +function contributed<T>( + selection: Located[], + providers: readonly ServiceProviderContribution[], + pick: (c: ReturnType<typeof serviceSelectionContributions>[number], services: ServiceContext[]) => T[] | undefined, +): T[] { + const services = selectionContexts(selection, providers); + if (!services) return []; + return serviceSelectionContributions().flatMap((c) => { + try { + return pick(c, services) ?? []; + } catch (e) { + console.error(`services contribution ${c.id} failed`, e); + return []; + } + }); +} + export function selectionActions( selection: Located[], providers: readonly ServiceProviderContribution[], ): ServiceItemAction[] { const groups = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.actions?.(item) ?? []); - return (groups[0] ?? []).flatMap((action) => { + const own = (groups[0] ?? []).flatMap((action) => { const matches = groups.flatMap((group) => group.filter((a) => a.id === action.id)); return matches.length === groups.length ? [batch(matches)] : []; }); + return [...own, ...contributed(selection, providers, (c, services) => c.actions?.(services))]; } function menuKey(item: MenuItem): string | undefined { @@ -70,5 +102,7 @@ function commonMenu(groups: MenuItem[][]): MenuItem[] { export function selectionMenu(selection: Located[], providers: readonly ServiceProviderContribution[]): MenuItem[] { const groups = selection.map(({ item, provider }) => providers.find((p) => p.id === provider)?.menu?.(item) ?? []); - return groups.length === 1 ? groups[0]! : commonMenu(groups); + const own = groups.length === 1 ? groups[0]! : commonMenu(groups); + const extra = contributed(selection, providers, (c, services) => c.menu?.(services)); + return extra.length ? [...own, ...(own.length ? [{ kind: "separator" } as const] : []), ...extra] : own; } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index e8798cc0b4..198ec5ee4f 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10450,5 +10450,14 @@ "Dependencies changed since the last install": "依赖在上次安装后有变化", "Run '{command}' in '{rel}' to install them.": "在 '{rel}' 中运行 '{command}' 安装依赖。", "Run '{command}' to install them.": "运行 '{command}' 安装依赖。", - "Install Node.js Dependencies": "安装 Node.js 依赖" + "Install Node.js Dependencies": "安装 Node.js 依赖", + "{title} needs the Java agent of {pluginName}": "{title} 需要 {pluginName} 的 Java 代理", + "Allow the java.agent permission of {pluginName} in Settings › Plugins, then try again.": "请在 设置 › 插件 中允许 {pluginName} 的 java.agent 权限,然后重试。", + "Cannot run '{name}' with {title}": "无法使用 {title} 运行 '{name}'", + "Plugin Java agents load only into JVMs started on this machine. Choose “Local machine” under “Run on”.": "插件的 Java 代理只加载到本机启动的 JVM 中。请在“运行于”中选择“本地计算机”。", + "Run '{name}' with {title}": "使用 {title} 运行 '{name}'", + "Debug '{name}' with {title}": "使用 {title} 调试 '{name}'", + "Run with {title}": "使用 {title} 运行", + "Debug with {title}": "使用 {title} 调试", + "Launches the selected configuration with the Java agent of {pluginName}": "使用 {pluginName} 的 Java 代理启动所选配置" } diff --git a/src/workbench/contributions.ts b/src/workbench/contributions.ts index 364b2cc2d5..de63c537c7 100644 --- a/src/workbench/contributions.ts +++ b/src/workbench/contributions.ts @@ -305,6 +305,8 @@ export interface ServiceProviderContribution { /** Toolbar buttons for a selected node of this provider. */ actions?(item: ServiceTreeItem): ServiceItemAction[]; menu?(item: ServiceTreeItem): MenuItem[]; + /** The service a node stands for, as other contributors see it (plugins' Services menus); null for groups. */ + context?(item: ServiceTreeItem): ServiceContext | null; /** Double click / Enter. */ activate?(item: ServiceTreeItem): void; /** Jump to Source (F4 / ⌘↓); a provider without it activates the node instead. */ @@ -323,6 +325,43 @@ export interface ServiceProviderContribution { reorder?: TreeReorder<ServiceTreeItem>; } +/** A selected Services node as contributors outside its provider see it. */ +export interface ServiceContext { + /** The provider's id: `run`, `docker`. */ + provider: string; + /** Stable within the provider: a run configuration's id, a container's id. */ + id: string; + /** `spring-boot`, `application`, … (a run configuration's kind), `docker-container`. */ + kind: string; + name: string; + running: boolean; + /** When a run configuration backs the service. */ + runConfigurationId?: string; +} + +/** + * Entries other features add to the Services tree's context menu and toolbar for the + * selected services (all of which have a {@link ServiceContext}). + */ +export interface ServiceSelectionContribution { + id: string; + menu?(services: ServiceContext[]): MenuItem[]; + actions?(services: ServiceContext[]): ServiceItemAction[]; +} + +const serviceSelectionItems = new Map<string, ServiceSelectionContribution>(); + +export function registerServiceSelectionItems(c: ServiceSelectionContribution): () => void { + serviceSelectionItems.set(c.id, c); + return () => { + if (serviceSelectionItems.get(c.id) === c) serviceSelectionItems.delete(c.id); + }; +} + +export function serviceSelectionContributions(): ServiceSelectionContribution[] { + return [...serviceSelectionItems.values()].sort((a, b) => a.id.localeCompare(b.id)); +} + export const useServiceProviders = create<{ providers: Map<string, ServiceProviderContribution> }>(() => ({ providers: new Map(), })); @@ -1743,6 +1782,13 @@ export interface RunExecutorContribution { supports(config: RunConfig): boolean; /** Plans the launch; null when it can't run (the executor has said why). */ prepare(config: RunConfig): Promise<ExecutorLaunch | null>; + /** + * The launch starts under the debugger (a plugin's "Debug with …"): no Run before-launch + * pass of its own, and `finished` / `beforeStop` are not called. + */ + debug?: boolean; + /** `prepare` handles a configuration on a run target itself (no container check before it). */ + checksTarget?: boolean; } export const useRunExecutors = create<{ executors: Map<string, RunExecutorContribution> }>(() => ({